repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
javax0-tutorials/object-initialization
src/com/javax0/classinit/Main.java
410
package com.javax0.classinit; import static com.javax0.classinit.Printer.println; public class Main { public static void main(String[] args) throws InterruptedException { println("creating concrete object"); Concrete c = new Concrete(); println("1st concrete object done"); c = new Concrete(); c.x.toString(); println("2nd concrete object done"); } }
apache-2.0
freeVM/freeVM
enhanced/buildtest/tests/vts/vm/src/test/vm/jvmti/funcs/DestroyRawMonitor/DestroyRawMonitor0101/DestroyRawMonitor0101.java
882
/* Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.harmony.vts.test.vm.jvmti; /** * @author Valentin Al. Sitnick * @version $Revision: 1.1 $ * */ public class DestroyRawMonitor0101 { static public void main(String args[]) { return; } }
apache-2.0
openwide-java/owsi-core-parent
owsi-core/owsi-core-components/owsi-core-component-jpa-more/src/test/java/fr/openwide/core/test/jpa/more/business/audit/dao/MockAuditDaoImpl.java
2406
package fr.openwide.core.test.jpa.more.business.audit.dao; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import fr.openwide.core.jpa.more.business.audit.dao.AbstractAuditDaoImpl; import fr.openwide.core.test.jpa.more.business.audit.model.MockAudit; import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditAction; import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditActionEnum; import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditFeature; import fr.openwide.core.test.jpa.more.business.audit.model.MockAuditFeatureEnum; @Repository("mockAuditDao") public class MockAuditDaoImpl extends AbstractAuditDaoImpl<MockAudit> implements IMockAuditDao { @Override public MockAuditAction getAuditActionByEnum(MockAuditActionEnum auditActionEnum) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<MockAuditAction> cq = cb.createQuery(MockAuditAction.class); Root<MockAuditAction> root = cq.from(MockAuditAction.class); cq.select(root); cq.where(cb.equal(root.get("auditActionEnum"), auditActionEnum)); cq.orderBy(cb.asc(root.get("position"))); TypedQuery<MockAuditAction> query = getEntityManager().createQuery(cq); try { return query.getSingleResult(); } catch (NoResultException e) { return null; } catch (NonUniqueResultException e) { return query.getResultList().iterator().next(); } } @Override public MockAuditFeature getAuditFeatureByEnum(MockAuditFeatureEnum auditFeatureEnum) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<MockAuditFeature> cq = cb.createQuery(MockAuditFeature.class); Root<MockAuditFeature> root = cq.from(MockAuditFeature.class); cq.select(root); cq.where(cb.equal(root.get("auditFeatureEnum"), auditFeatureEnum)); cq.orderBy(cb.asc(root.get("position"))); TypedQuery<MockAuditFeature> query = getEntityManager().createQuery(cq); try { return query.getSingleResult(); } catch (NoResultException e) { return null; } catch (NonUniqueResultException e) { return query.getResultList().iterator().next(); } } }
apache-2.0
FearTheBadger/rotate
core/src/com/fearthebadger/studio/rotator/MainMenu.java
4154
package com.fearthebadger.studio.rotator; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.fearthebadger.studio.menus.Settings; import com.fearthebadger.studio.utils.RotatorConstants; public class MainMenu extends InputAdapter implements Screen { private static final String TAG = "Rotator Main"; private MainRotator game; private TextureAtlas atlas; private Skin skin; private Viewport viewport; private Texture buttonUpTex, buttonDownTex, buttonOverTex; private TextButton btnPlay, btnSettings, btnImages; private TextButtonStyle tbs; private BitmapFont font; private Stage stage; public MainMenu(final MainRotator game) { create(); this.game = game; Gdx.app.log(TAG, "Rotator game: " + this.game); } public void create() { Gdx.app.setLogLevel(Application.LOG_DEBUG); viewport = new FitViewport(RotatorConstants.worldWidth, RotatorConstants.worldHeight); stage = new Stage(viewport); Gdx.input.setInputProcessor(stage); font = new BitmapFont(Gdx.files.internal("data/font.fnt")); skin = new Skin(); atlas = new TextureAtlas(Gdx.files.internal("button.atlas")); skin.addRegions(atlas); Gdx.app.log(TAG, "Rotator Before map"); tbs = new TextButtonStyle(); tbs.font = font; tbs.up = skin.getDrawable("myactor"); tbs.down = skin.getDrawable("myactorDown"); tbs.checked = skin.getDrawable("myactorDown"); tbs.over = skin.getDrawable("myactorOver"); skin.add("default", tbs); btnPlay = new TextButton("PLAY", skin); btnPlay.sizeBy(180.0f, 60.0f); btnPlay.setPosition(Gdx.graphics.getWidth()/2 - Gdx.graphics.getWidth()/8 , Gdx.graphics.getHeight()/2); stage.addActor(btnPlay); btnSettings = new TextButton("SETS", skin); btnSettings.sizeBy(30.0f, 60.0f); btnSettings.setPosition(Gdx.graphics.getWidth()/2 + 60, (Gdx.graphics.getHeight()/2)-120); stage.addActor(btnSettings); btnImages = new TextButton("Images", skin); btnImages.sizeBy(30.0f, 60.0f); btnImages.setPosition(Gdx.graphics.getWidth()/2 - 120, (Gdx.graphics.getHeight()/2)-120); stage.addActor(btnImages); btnPlay.addListener( new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { Gdx.app.log(TAG, "Rotator PLAY"); game.setScreen(new MainGame(game)); } }); btnSettings.addListener( new ClickListener() { public void clicked(InputEvent event, float x, float y) { Gdx.app.log(TAG, "Calling Settings"); game.setScreen(new Settings(game)); } }); } @Override public void render(float delta) { Gdx.gl.glClearColor(RotatorConstants.bgColor.r, RotatorConstants.bgColor.g, RotatorConstants.bgColor.b, RotatorConstants.bgColor.a); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); if (Gdx.input.isKeyPressed(Input.Keys.BACK)) { Gdx.app.log(TAG, "Exiting"); Gdx.app.exit(); } stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f)); stage.draw(); } @Override public void resize(int width, int height) { viewport.update(width, height, false); } @Override public void dispose() { buttonDownTex.dispose(); buttonOverTex.dispose(); buttonUpTex.dispose(); stage.dispose(); } @Override public void pause() {} @Override public void resume() {} @Override public void show() { Gdx.input.setCatchBackKey(true); } @Override public void hide() {} }
apache-2.0
mrpantsuit/javactor
src/main/java/javactor/akka/JavactorUntypedActor.java
20806
package javactor.akka; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javactor.Cancellable; import javactor.JavactorContext; import javactor.JavactorFactory; import javactor.JavactorContext.JavactorPreparer; import javactor.JavactorContext.SupervisorDirective; import javactor.JavactorContext.SupervisorStrategyInfo; import javactor.JavactorContext.SupervisorStrategyType; import javactor.annot.Handle; import javactor.annot.OnException; import javactor.annot.PostRestart; import javactor.annot.PostStop; import javactor.annot.PreRestart; import javactor.annot.PreStart; import javactor.msg.TimeoutMsg; import lombok.Data; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.java.Log; import scala.Option; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import akka.actor.ActorInitializationException; import akka.actor.ActorKilledException; import akka.actor.ActorRef; import akka.actor.AllForOneStrategy; import akka.actor.DeathPactException; import akka.actor.OneForOneStrategy; import akka.actor.Props; import akka.actor.SupervisorStrategy; import akka.actor.SupervisorStrategy.Directive; import akka.actor.Terminated; import akka.actor.UntypedActor; import akka.japi.Creator; import akka.japi.Function; import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Maps; @RequiredArgsConstructor @Log public class JavactorUntypedActor extends UntypedActor { private static final ImmutableMap<SupervisorDirective, Directive> JAVACTOR_DIRECTIVES_TO_AKKA = ImmutableMap.of( SupervisorDirective.STOP, (Directive)SupervisorStrategy.stop(), SupervisorDirective.RESTART, SupervisorStrategy.restart(), SupervisorDirective.ESCALATE, SupervisorStrategy.escalate(), SupervisorDirective.RESUME, SupervisorStrategy.resume() ); private static final class MostToLeastSpecificComparator implements Comparator<Class<?>> { @Override public int compare(Class<?> o1, Class<?> o2) { return o1.isAssignableFrom(o2) ? 1 : -1; } } @Data static public class MySupervisorStrategyInfo { private final SupervisorStrategyInfo info; private final ImmutableMap<Class<?>,Method> onExceptionMethods; } @SuppressWarnings("serial") @RequiredArgsConstructor static private final class MyCreator<T> implements Creator<JavactorUntypedActor> { private final Class<T> javactorClass; private final boolean subscribeToEventStream; private final JavactorFactory customJavactorFactory; private final JavactorFactory defaultJavactorFactory; private final JavactorPreparer<T> preparer; @Override public JavactorUntypedActor create() throws Exception { @SuppressWarnings("unchecked") final T javactor = (T) customJavactorFactory.get(javactorClass); if ( preparer != null ) { preparer.prepare(javactor); } return AkkaJavactorBuilder.builder(javactor) .subscribeToEventStream(subscribeToEventStream) .javactorFactory(defaultJavactorFactory) .build(); } } @RequiredArgsConstructor private final class AkkaJavactorContext implements JavactorContext { @Data private class MyActorBuilder<T> implements ActorBuilder<T> { private final Class<T> javactorClass; private final String actorName; private JavactorFactory customFactory; private boolean subscribeToEventStream = false; private String dispatcherName; private JavactorPreparer<T> preparer; @Override public ActorBuilder<T> subscribeToEventBus() { this.subscribeToEventStream = true; return this; } @Override public ActorBuilder<T> factory(JavactorFactory factory) { this.customFactory = factory; return this; } @Override public Object build() { JavactorFactory factoryToUse = customFactory == null ? javactorFactory : customFactory; if ( javactorFactory == null ) throw new RuntimeException("createActor called but no " + "javactorFactory has been set"); Props props = Props.create(new MyCreator<T>( javactorClass, subscribeToEventStream, factoryToUse, javactorFactory, preparer)); if ( dispatcherName != null ) props = props.withDispatcher(dispatcherName); return context().actorOf(props, actorName); } @Override public ActorBuilder<T> preparer(JavactorPreparer<T> preparer) { this.preparer = preparer; return this; } @Override public ActorBuilder<T> dispatcher(String dispatcherName) { this.dispatcherName = dispatcherName; return this; } } @Data private class MySendBuilder implements SendBuilder { private final Object msg; private ActorRef to; private ActorRef replyTo = getSelf(); private FiniteDuration timeout; private boolean replyToSet = false; @Override public SendBuilder to(Object to) { this.to = (ActorRef) to; return this; } @Override public SendBuilder from(Object replyTo) { replyToSet = true; this.replyTo = (ActorRef) replyTo; return this; } @Override public SendBuilder timeout(long timeout, TimeUnit timeUnit) { this.timeout = Duration.create(timeout, timeUnit); return this; } @Override public void fireAndForget() { if ( timeout != null ) throw new IllegalArgumentException("Trying to fire and forget " + "with a non null timeout."); fire(); } private void fire() { if ( to == null ) { if ( replyToSet ) throw new IllegalArgumentException("Trying to publish to " + "event bus with replyTo. Akka does not retain the sender " + "when posting to the event stream."); context().system().eventStream().publish(msg); } else to.tell(msg, replyTo); } @Override public void request(Class<?> response, Object requestInfo) { final Class<? extends Object> javactorClass = JavactorUntypedActor.this.javactor.getClass(); final JavactorInfo javactorInfo = JavactorUntypedActor .javactorInfoByJavactorType.get(javactorClass); if ( getCachedHandleMethodForClass(response, javactorInfo) == null ) { throw new IllegalStateException(javactorClass+" does not have " +"a Handle method for the response "+response); } if ( getCachedHandleMethodForClass(TimeoutMsg.class, javactorInfo) == null ) throw new IllegalStateException(javactorClass+" does not have " +"a Handle method for "+TimeoutMsg.class); fire(); startWaitingFor(response, Objects.firstNonNull(timeout, Duration.create(DEFAULT_REQUEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)), requestInfo); } @Override public SendBuilder replyToSender() { this.to = (ActorRef) AkkaJavactorContext.this.sender(); return this; } } @RequiredArgsConstructor private class MyScheduleBuilder implements ScheduleBuilder { private final Object msg; private Object to; private Object from = AkkaJavactorContext.this.self(); private FiniteDuration delay = Duration.Zero(); private FiniteDuration period; @Override public ScheduleBuilder to(Object to) { this.to = to; return this; } @Override public ScheduleBuilder toSelf() { this.to = AkkaJavactorContext.this.self(); return this; } @Override public ScheduleBuilder delay(long delay, TimeUnit timeUnit) { this.delay = Duration.create(delay, timeUnit); return this; } @Override public ScheduleBuilder period(long period, TimeUnit timeUnit) { this.period = Duration.create(period, timeUnit); return this; } @Override public Cancellable go() { final Object msgToUse = to == null ? new PostMsg(msg) : msg; if ( period == null ) { return new MyCancellable(context().system().scheduler().scheduleOnce(delay, (ActorRef)to, msgToUse, context().dispatcher(), (ActorRef)from)); } return new MyCancellable(context().system().scheduler().schedule( delay, period, (ActorRef)to, msgToUse, context().dispatcher(), (ActorRef)from)); } @Override public ScheduleBuilder from(Object from) { this.from = from; return this; } } private final class MyCancellable implements Cancellable { private final akka.actor.Cancellable cancellable; private MyCancellable(akka.actor.Cancellable cancellable) { this.cancellable = cancellable; } @Override public boolean cancel() { return cancellable.cancel(); } } // @Override // public Cancellable schedule(FiniteDuration delay, FiniteDuration period, // Object to, Object msg, Object from) // { // return new MyCancellable(context().system().scheduler().schedule(delay, period, // (ActorRef)to, msg, context().dispatcher(), (ActorRef)from)); // } @Override public Object self() { return getSelf(); } // @Override // public Cancellable scheduleOnce(FiniteDuration delay, Object to, // Object msg, Object from) // { // return new MyCancellable(context().system().scheduler().scheduleOnce(delay, // (ActorRef)to, msg, context().dispatcher(), (ActorRef)from)); // } @Override public void unhandled(Object msg) { unhandled(msg); } @Override public Object sender() { return getSender(); } @Override public void stop(Object actor) { context().stop((ActorRef) actor); } @Override public SendBuilder msg(Object msg) { return new MySendBuilder(msg); } @Override public void watch(Object actor) { context().watch((ActorRef) actor); } @Override public <T> ActorBuilder<T> actorBuilder(Class<T> javactorClass, String actorName) { return new MyActorBuilder<T>(javactorClass, actorName); } @Override public ScheduleBuilder schedule(Object msg) { return new MyScheduleBuilder(msg); } } @Data static private class JavactorInfo { private final Field javactorContextField; private final ImmutableSortedMap<Class<?>,Method> methodsByMessageClass; private final MySupervisorStrategyInfo supervisorStrategyInfo; } static private ConcurrentHashMap<Class<?>, JavactorInfo> javactorInfoByJavactorType = new ConcurrentHashMap<>(); @Getter//getter for testing private final Object javactor; private final JavactorFactory javactorFactory; private final boolean subscribeToEventStream; private final Map<Class<?>, akka.actor.Cancellable> requests = Maps.newHashMapWithExpectedSize(0);/* Keep it small initially */ // private void setupSupervisorStrategy() // { // if ( supervisorStrategyInfo != null ) // supervisorStrategy = supervisorStrategyInfo.getType().equals(SupervisorStrategyType.ONE_FOR_ONE) ? // new OneForOneStrategy(supervisorStrategyInfo.getMaxNumRetries(), // rangeTimeUnitToDuration(supervisorStrategyInfo.getTimeRange(), // supervisorStrategyInfo.getTimeUnit()), // myDecider(), // supervisorStrategyInfo.isLoggingEnabled() // ) : // new AllForOneStrategy(supervisorStrategyInfo.getMaxNumRetries(), // rangeTimeUnitToDuration(supervisorStrategyInfo.getTimeRange(), // supervisorStrategyInfo.getTimeUnit()), // myDecider(), // supervisorStrategyInfo.isLoggingEnabled()); // } private Function<Throwable, Directive> myDecider() { return new Function<Throwable, Directive>() { @Override public Directive apply(Throwable t) { if ( t instanceof ActorInitializationException || t instanceof ActorKilledException || t instanceof DeathPactException ) { return SupervisorStrategy.stop(); } else if ( t instanceof Exception ) { Class<? extends Throwable> clazz = t.getClass(); ImmutableSet<Entry<Class<?>, Method>> entrySet = javactorInfoByJavactorType .get(javactor.getClass()).getSupervisorStrategyInfo().getOnExceptionMethods() .entrySet(); for (Entry<Class<?>, Method> entry : entrySet) { if (entry.getKey().isAssignableFrom(clazz)) { final Method method = entry.getValue(); try { return map((SupervisorDirective) methodInvoke( method, javactor, t)); } catch (Exception e) { throw new RuntimeException(e); } } } return SupervisorStrategy.restart(); } else { return SupervisorStrategy.escalate(); } } }; } private Directive map(SupervisorDirective supDirective) { return JAVACTOR_DIRECTIVES_TO_AKKA.get(supDirective); } @Override public void preStart() throws Exception { super.preStart(); if ( !javactorInfoByJavactorType.contains(javactor.getClass()) ) { javactorInfoByJavactorType.put(javactor.getClass(), new JavactorInfo(getJavactorContextField(javactor.getClass()), getHandleMethodsByMsgClass(), getMySupervisorStrategyInfo(javactor))); } AkkaJavactorContext javactorContext = createJavactorContext(); setContextOnJavactor(javactorContext); ImmutableMap<Class<?>, Method> handleMethods = javactorInfoByJavactorType.get(javactor.getClass()).getMethodsByMessageClass(); if ( subscribeToEventStream ) { ImmutableSet<Class<?>> keySet = handleMethods.keySet(); for (Class<?> msgClass : keySet) { context().system().eventStream().subscribe(getSelf(), msgClass); } } callAnnotatedMethod(PreStart.class); } private MySupervisorStrategyInfo getMySupervisorStrategyInfo(Object javactor) { return new MySupervisorStrategyInfo(getSupervisorStrategyInfo(javactor), getOnExceptionMethods(javactor.getClass())); } private SupervisorStrategyInfo getSupervisorStrategyInfo(Object javactor) { try { Method[] methods = javactor.getClass().getMethods(); for (Method method : methods) { if ( SupervisorStrategyInfo.class.isAssignableFrom(method.getReturnType()) ) return (SupervisorStrategyInfo) method.invoke(javactor); } return new SupervisorStrategyInfo(); } catch (Throwable e) { throw new RuntimeException(e); } } private ImmutableMap<Class<?>, Method> getOnExceptionMethods( Class<?> javactorClass) { Builder<Class<?>, Method> result = ImmutableMap.builder(); ImmutableSet<Method> methods = getMethodsWithAnnotation(javactorClass, OnException.class); for (Method method : methods) { result.put(method.getParameterTypes()[0], method); } return result.build(); } private ImmutableSet<Method> getMethodsWithAnnotation( Class<?> clazz, Class<OnException> annotClass) { com.google.common.collect.ImmutableSet.Builder<Method> result = ImmutableSet.builder(); Method[] methods = clazz.getMethods(); for (Method method : methods) { Object annot = method.getAnnotation(annotClass); if ( annot != null ) { result.add(method); } } return result.build(); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void callAnnotatedMethod(Class annotClass) throws Exception { Method[] methods = javactor.getClass().getMethods(); for (Method method : methods) { Object prestartAnnot = method.getAnnotation(annotClass); if ( prestartAnnot != null ) { methodInvoke(method, javactor); return; } } } private ImmutableSortedMap<Class<?>, Method> getHandleMethodsByMsgClass() { Method[] methods = javactor.getClass().getMethods(); ImmutableSortedMap.Builder<Class<?>,Method> builder = ImmutableSortedMap.orderedBy(new MostToLeastSpecificComparator()); for (Method method : methods) { Handle handleAnnot = method.getAnnotation(Handle.class); if ( handleAnnot != null ) { Class<?>[] parameterTypes = method.getParameterTypes(); if ( parameterTypes.length <= 0 ) throw new RuntimeException("@Handle method "+method+ " does not have a parameter."); final Class<?> msgClass = parameterTypes[0]; builder.put(msgClass, method); }; } return builder.build(); } private Field getJavactorContextField(Class<?> clazz) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if ( JavactorContext.class.isAssignableFrom(field.getType()) ) { field.setAccessible(true); return field; } } Class<?> superclass = clazz.getSuperclass(); return superclass == null ? null : getJavactorContextField(superclass); } @Override public void onReceive(Object message) throws Exception { doneWaitingFor(message.getClass()); if ( message instanceof PostMsg ) { context().system().eventStream().publish(((PostMsg) message).getPayload()); return; } if ( message instanceof Terminated ) { message = new javactor.msg.Terminated(); } AkkaJavactorContext context = createJavactorContext(); setContextOnJavactor(context); final Class<? extends Object> msgClass = message.getClass(); final Class<? extends Object> javactorClass = javactor.getClass(); Method method = getCachedHandleMethodForClass(msgClass, javactorInfoByJavactorType.get(javactorClass)); if ( method != null ) { methodInvoke(method, javactor, message); return; } unhandled(message); } private Method getCachedHandleMethodForClass( final Class<? extends Object> msgClass, JavactorInfo javactorInfo) { final ImmutableMap<Class<?>, Method> methodsByMessageClass = javactorInfo.getMethodsByMessageClass(); Method method = null; if ( methodsByMessageClass.containsKey(msgClass) ) { method = methodsByMessageClass.get(msgClass); } else { ImmutableSet<Entry<Class<?>, Method>> entrySet = methodsByMessageClass.entrySet(); for (Entry<Class<?>, Method> entry : entrySet) { if ( entry.getKey().isAssignableFrom(msgClass) ) { method = entry.getValue(); break; } } } return method; } private void setContextOnJavactor(AkkaJavactorContext context) { try { Field javactorContextField = javactorInfoByJavactorType.get(javactor.getClass()) .getJavactorContextField(); if ( javactorContextField != null ) javactorContextField.set(javactor, context); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } private AkkaJavactorContext createJavactorContext() { return new AkkaJavactorContext(); } @Override public void postStop() throws Exception { super.postStop(); setContextOnJavactor(createJavactorContext()); Method[] methods = javactor.getClass().getMethods(); for (Method method : methods) { PostStop annot = method.getAnnotation(PostStop.class); if ( annot != null ) { methodInvoke(method, javactor); } } } private Object methodInvoke(Method method, Object target, Object... args) throws Exception { try { return method.invoke(target, args); } catch (InvocationTargetException e) { throw (Exception)e.getCause(); } } @Override public SupervisorStrategy supervisorStrategy() { SupervisorStrategyInfo info = javactorInfoByJavactorType .get(javactor.getClass()).getSupervisorStrategyInfo().getInfo(); Duration withinDuration = toDuration(info.getTimeRange(), info.getTimeUnit()); final int maxNumRetries = info.getMaxNumRetries(); final boolean loggingEnabled = info.isLoggingEnabled(); return info.getType().equals(SupervisorStrategyType.ONE_FOR_ONE) ? new OneForOneStrategy(maxNumRetries, withinDuration, myDecider(), loggingEnabled ) : new AllForOneStrategy(maxNumRetries, withinDuration, myDecider(), loggingEnabled ); } private Duration toDuration(long timeRange, TimeUnit timeUnit) { return Duration.create(timeRange, timeUnit); } @Override public void preRestart(Throwable reason, Option<Object> message) throws Exception { log.severe("restarting for reason: "+reason); setContextOnJavactor(createJavactorContext()); callAnnotatedMethod(PreRestart.class); super.preRestart(reason, message); } @Override public void postRestart(Throwable reason) throws Exception { setContextOnJavactor(createJavactorContext()); callAnnotatedMethod(PostRestart.class); super.postRestart(reason); } public void startWaitingFor(Class<?> response, FiniteDuration timeout, Object taskInfo) { requests.put(response, context().system().scheduler().scheduleOnce(timeout, self(), new TimeoutMsg(taskInfo), context().dispatcher(), self())); } private void doneWaitingFor(Class<? extends Object> class1) { final akka.actor.Cancellable cancellable = requests.remove(class1); if ( cancellable != null ) cancellable.cancel(); } }
apache-2.0
alphadev-net/ntfslib
src/main/java/net/alphadev/ntfslib/structures/MasterFileTable.java
1980
/** * Copyright © 2014 Jan Seeger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.alphadev.ntfslib.structures; import net.alphadev.ntfslib.structures.entries.FileRecord; import net.alphadev.ntfslib.structures.entries.KnownMftEntries; import java.io.IOException; /** * @author Jan Seeger <jan@alphadev.net> */ public class MasterFileTable { private final Volume volume; private final ExtendedBpb parameter; private final long baseOffset; private MasterFileTable(Volume volume, long baseOffset) { this.volume = volume; this.parameter = volume.getParameter(); this.baseOffset = parameter.calculateBytes((int) baseOffset); } public static MasterFileTable read(Volume volume) { final ExtendedBpb parameter = volume.getParameter(); final long mftMainStart = parameter.getMftLogicalCluster(); final long mftMirrorStart = parameter.getMftMirrorLogicalCluster(); final MasterFileTable mainMft = new MasterFileTable(volume, mftMainStart); /* * TODO: check mft integrity here and restore broken entries from mftMirror */ return mainMft; } public FileRecord getEntry(KnownMftEntries entry) throws IOException { return getEntry(entry.getValue() * parameter.getBytesPerMftRecord()); } public FileRecord getEntry(long address) throws IOException { return new FileRecord(volume, baseOffset + address); } }
apache-2.0
IV007/ng-chat
NGChat/app/src/main/java/com/sidelance/ngchat/ForgotPassword.java
4340
package com.sidelance.ngchat; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.RequestPasswordResetCallback; public class ForgotPassword extends AppCompatActivity { protected EditText mEmailEditText; protected Button mResetPasswordButton; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgot_password); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mEmailEditText = (EditText) findViewById(R.id.forgotEmailEditText); mResetPasswordButton = (Button) findViewById(R.id.resetPasswordButton); resetPasswordButtonListener(); } private void resetPasswordButtonListener() { mResetPasswordButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = mEmailEditText.getText().toString(); if (TextUtils.isEmpty(email)){ displayIncompleteFormDialog(); } else { setProgressBarIndeterminateVisibility(true); performReequestPasswordResetInBackground(email); } } }); } private void displayIncompleteFormDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(ForgotPassword.this); builder.setTitle(R.string.SIGN_UP_ERROR_TITLE); builder.setMessage(R.string.FORGOT_PASSWORD_EMPTY_EMAIL); builder.setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } private void performReequestPasswordResetInBackground(String email) { ParseUser.requestPasswordResetInBackground(email, new RequestPasswordResetCallback() { @Override public void done(ParseException e) { if (e == null) { setProgressBarIndeterminateVisibility(false); displayPasswordRequestSuccessDialog(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(ForgotPassword.this); builder.setMessage(e.getMessage() + " " + R.string.FORGOT_PASSWORD_EMPTY_EMAIL) .setTitle(R.string.FORGOT_PASSWORD_ERROR_TITLE) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); } private void displayPasswordRequestSuccessDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(ForgotPassword.this); builder.setTitle(R.string.FORGOT_PASSWORD_RESET_SUCCESS_TITLE); builder.setMessage(R.string.FORGOT_PASSWORD_SUCCESS_MESSAGE); builder.setPositiveButton(R.string.BUTTON_LOGIN, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(ForgotPassword.this, LoginActivity.class); startActivity(intent); } }); AlertDialog dialog = builder.create(); dialog.show(); } }
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/MoveAddressToVpcRequestMarshaller.java
1903
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ec2.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.internal.ListWithAutoConstructFlag; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Move Address To Vpc Request Marshaller */ public class MoveAddressToVpcRequestMarshaller implements Marshaller<Request<MoveAddressToVpcRequest>, MoveAddressToVpcRequest> { public Request<MoveAddressToVpcRequest> marshall(MoveAddressToVpcRequest moveAddressToVpcRequest) { if (moveAddressToVpcRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<MoveAddressToVpcRequest> request = new DefaultRequest<MoveAddressToVpcRequest>(moveAddressToVpcRequest, "AmazonEC2"); request.addParameter("Action", "MoveAddressToVpc"); request.addParameter("Version", "2015-10-01"); if (moveAddressToVpcRequest.getPublicIp() != null) { request.addParameter("PublicIp", StringUtils.fromString(moveAddressToVpcRequest.getPublicIp())); } return request; } }
apache-2.0
Hultron/LifeHelper
app/src/main/java/com/hultron/lifehelper/ui/QrCodeShareActivity.java
1375
package com.hultron.lifehelper.ui; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.annotation.Nullable; import android.widget.ImageView; import com.hultron.lifehelper.R; import com.xys.libzxing.zxing.encoding.EncodingUtils; /** * QrCodeShareActivity * 生成二维码 */ public class QrCodeShareActivity extends BaseActivity { //我的二维码 private ImageView mQrCode; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qrshare); initView(); } private void initView() { mQrCode = (ImageView) findViewById(R.id.qr_code_container); //获取屏幕宽度 int width = getResources().getDisplayMetrics().widthPixels; int height = getResources().getDisplayMetrics().heightPixels; //二维码大小 int qrCodeSize = Math.min(width, height); //根据字符串生成二维码图片并显示在界面上,第二个参数为图片的大小(350*350) Bitmap qrCodeBitmap = EncodingUtils.createQRCode("我是智能管家", qrCodeSize, qrCodeSize, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)); mQrCode.setImageBitmap(qrCodeBitmap); } }
apache-2.0
vvv1559/intellij-community
java/java-tests/testSrc/com/intellij/java/propertyBased/JavaCodeInsightSanityTest.java
2408
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.propertyBased; import com.intellij.openapi.application.PathManager; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.SkipSlowTestLocally; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import com.intellij.testFramework.propertyBased.*; import org.jetbrains.annotations.NotNull; import jetCheck.Generator; import jetCheck.PropertyChecker; import java.util.function.Function; /** * @author peter */ @SkipSlowTestLocally public class JavaCodeInsightSanityTest extends LightCodeInsightFixtureTestCase { @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return JAVA_9; } public void testRandomActivity() { MadTestingUtil.enableAllInspections(getProject(), getTestRootDisposable()); Function<PsiFile, Generator<? extends MadTestingAction>> fileActions = file -> Generator.anyOf(InvokeIntention.randomIntentions(file, new JavaIntentionPolicy()), InvokeCompletion.completions(file, new JavaCompletionPolicy()), Generator.constant(new StripTestDataMarkup(file)), DeleteRange.psiRangeDeletions(file)); PropertyChecker.forAll(actionsOnJavaFiles(fileActions)).shouldHold(FileWithActions::runActions); } @NotNull private Generator<FileWithActions> actionsOnJavaFiles(Function<PsiFile, Generator<? extends MadTestingAction>> fileActions) { return MadTestingUtil.actionsOnFileContents(myFixture, PathManager.getHomePath(), f -> f.getName().endsWith(".java"), fileActions); } public void testReparse() { PropertyChecker.forAll(actionsOnJavaFiles(MadTestingUtil::randomEditsWithReparseChecks)).shouldHold(FileWithActions::runActions); } }
apache-2.0
lafaspot/JsonPath
json-path/src/main/java/com/jayway/jsonpath/internal/path/FunctionPathToken.java
3127
package com.jayway.jsonpath.internal.path; import com.jayway.jsonpath.internal.PathRef; import com.jayway.jsonpath.internal.function.Parameter; import com.jayway.jsonpath.internal.function.PathFunction; import com.jayway.jsonpath.internal.function.PathFunctionFactory; import com.jayway.jsonpath.internal.function.latebinding.JsonLateBindingValue; import com.jayway.jsonpath.internal.function.latebinding.PathLateBindingValue; import java.util.List; /** * Token representing a Function call to one of the functions produced via the FunctionFactory * * @see PathFunctionFactory * * Created by mattg on 6/27/15. */ public class FunctionPathToken extends PathToken { private final String functionName; private final String pathFragment; private List<Parameter> functionParams; public FunctionPathToken(String pathFragment, List<Parameter> parameters) { this.pathFragment = pathFragment + ((parameters != null && parameters.size() > 0) ? "(...)" : "()"); if(null != pathFragment){ functionName = pathFragment; functionParams = parameters; } else { functionName = null; functionParams = null; } } @Override public void evaluate(String currentPath, PathRef parent, Object model, EvaluationContextImpl ctx) { PathFunction pathFunction = PathFunctionFactory.newFunction(functionName); evaluateParameters(currentPath, parent, model, ctx); Object result = pathFunction.invoke(currentPath, parent, model, ctx, functionParams); ctx.addResult(currentPath + "." + functionName, parent, result); if (!isLeaf()) { next().evaluate(currentPath, parent, result, ctx); } } private void evaluateParameters(String currentPath, PathRef parent, Object model, EvaluationContextImpl ctx) { if (null != functionParams) { for (Parameter param : functionParams) { if (!param.hasEvaluated()) { switch (param.getType()) { case PATH: param.setLateBinding(new PathLateBindingValue(param.getPath(), ctx.rootDocument(), ctx.configuration())); param.setEvaluated(true); break; case JSON: param.setLateBinding(new JsonLateBindingValue(ctx.configuration().jsonProvider(), param)); param.setEvaluated(true); break; } } } } } /** * Return the actual value by indicating true. If this return was false then we'd return the value in an array which * isn't what is desired - true indicates the raw value is returned. * * @return */ @Override public boolean isTokenDefinite() { return true; } @Override public String getPathFragment() { return "." + pathFragment; } public void setParameters(List<Parameter> parameters) { this.functionParams = parameters; } }
apache-2.0
Taskana/taskana
rest/taskana-rest-spring/src/test/java/pro/taskana/user/rest/UserControllerRestDocTest.java
2280
package pro.taskana.user.rest; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import pro.taskana.common.rest.RestEndpoints; import pro.taskana.common.test.BaseRestDocTest; import pro.taskana.user.api.UserService; import pro.taskana.user.api.models.User; import pro.taskana.user.rest.assembler.UserRepresentationModelAssembler; import pro.taskana.user.rest.models.UserRepresentationModel; class UserControllerRestDocTest extends BaseRestDocTest { @Autowired UserRepresentationModelAssembler assembler; @Autowired UserService userService; @Test void getUserDocTest() throws Exception { mockMvc .perform(get(RestEndpoints.URL_USERS_ID, "teamlead-1")) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void createUserDocTest() throws Exception { User user = userService.newUser(); user.setId("user-10-2"); user.setFirstName("Hans"); user.setLastName("Georg"); UserRepresentationModel repModel = assembler.toModel(user); mockMvc .perform(post(RestEndpoints.URL_USERS).content(objectMapper.writeValueAsString(repModel))) .andExpect(MockMvcResultMatchers.status().isCreated()); } @Test void updateUserDocTest() throws Exception { User user = userService.getUser("teamlead-1"); user.setFirstName("new name"); UserRepresentationModel repModel = assembler.toModel(user); mockMvc .perform( put(RestEndpoints.URL_USERS_ID, "teamlead-1") .content(objectMapper.writeValueAsString(repModel))) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void deleteUserDocTest() throws Exception { mockMvc .perform(delete(RestEndpoints.URL_USERS_ID, "user-1-1")) .andExpect(MockMvcResultMatchers.status().isNoContent()); } }
apache-2.0
IHTSDO/snow-owl
snomed/com.b2international.snowowl.snomed.datastore.server/src/com/b2international/snowowl/datastore/server/snomed/merge/SnomedMergeConflictRuleProvider.java
2004
/* * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.datastore.server.snomed.merge; import java.util.Collection; import com.b2international.snowowl.datastore.cdo.IMergeConflictRule; import com.b2international.snowowl.datastore.cdo.IMergeConflictRuleProvider; import com.b2international.snowowl.datastore.server.snomed.merge.rules.SnomedInvalidOwlExpressionMergeConflictRule; import com.b2international.snowowl.datastore.server.snomed.merge.rules.SnomedInvalidRelationshipMergeConflictRule; import com.b2international.snowowl.datastore.server.snomed.merge.rules.SnomedRefsetMemberReferencingDetachedComponentRule; import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator; import com.google.common.collect.ImmutableList; /** * @since 4.7 */ public class SnomedMergeConflictRuleProvider implements IMergeConflictRuleProvider { private ImmutableList<IMergeConflictRule> rules; public SnomedMergeConflictRuleProvider() { rules = ImmutableList.<IMergeConflictRule>builder() .add(new SnomedRefsetMemberReferencingDetachedComponentRule()) .add(new SnomedInvalidRelationshipMergeConflictRule()) .add(new SnomedInvalidOwlExpressionMergeConflictRule()) .build(); } @Override public String getRepositoryUUID() { return SnomedDatastoreActivator.REPOSITORY_UUID; } @Override public Collection<IMergeConflictRule> getRules() { return rules; } }
apache-2.0
Axway/ats-framework
agent/core/src/test/java/com/axway/ats/agent/core/ant/component/agenttest/FirstActionClass.java
2877
/* * Copyright 2017 Axway Software * * 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.axway.ats.agent.core.ant.component.agenttest; import org.apache.log4j.Logger; import com.axway.ats.agent.core.ant.component.agenttest.FirstActionClass; import com.axway.ats.agent.core.model.Action; import com.axway.ats.agent.core.model.Parameter; import com.axway.ats.core.validation.ValidationType; public class FirstActionClass { public static int ACTION_VALUE = 0; private static int[] VALID_CONSTANTS = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8 }; @Action(name = "action 1") public void action1( @Parameter(name = "value") int value ) { ACTION_VALUE = value; Logger.getLogger( FirstActionClass.class ).info( ( Object ) "Method action 1 has been executed" ); } @Action(name = "action array") public int action1( @Parameter(name = "value", validation = ValidationType.NUMBER_CONSTANT, args = { "VALID_CONSTANTS" }) int[] values ) { ACTION_VALUE = values[values.length - 1]; Logger.getLogger( FirstActionClass.class ).info( ( Object ) "Method action array has been executed" ); return ACTION_VALUE; } @Action(name = "action long") public long actionLong( @Parameter(name = "value") long value ) { return value; } @Action(name = "action double") public double actionDouble( @Parameter(name = "value") double value ) { return value; } @Action(name = "action float") public float actionFloat( @Parameter(name = "value") float value ) { return value; } @Action(name = "action boolean") public boolean actionBoolean( @Parameter(name = "value") boolean value ) { return value; } @Action(name = "action short") public short actionShort( @Parameter(name = "value") short value ) { return value; } @Action(name = "action byte") public byte actionByte( @Parameter(name = "value") byte value ) { return value; } @Action(name = "action string") public String actionString( @Parameter(name = "value", validation = ValidationType.STRING_NOT_EMPTY) String value ) { return value; } @Action(name = "action wrong type") public FirstActionClass actionString( @Parameter(name = "value") FirstActionClass value ) { return value; } }
apache-2.0
mazlixek/gwt-ol3
gwt-ol3-client/src/main/java/ol/MapEvent.java
1225
/******************************************************************************* * Copyright 2014, 2016 gwt-ol3 * * 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 ol; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import ol.events.Event; /** * Events emitted as map events are instances of this type. See {@link ol.Map} * for which events trigger a map event. * * @author sbaumhekel */ @JsType(isNative = true) public interface MapEvent extends Event { /** * The map where the event occurred. * * @return {@link ol.Map} */ @JsProperty Map getMap(); }
apache-2.0
rma350/jgraphv
JGraphVCore/src/com/github/rma350/jgraphv/core/demo/ArcDemo.java
1557
package com.github.rma350.jgraphv.core.demo; import com.github.rma350.jgraphv.core.engine.Engine; import com.github.rma350.jgraphv.core.shapes.ArcBuffer; import com.github.rma350.jgraphv.core.shapes.ArcBufferBuilder; import com.github.rma350.jgraphv.core.shapes.ArcBuilder; import com.github.rma350.jgraphv.core.shapes.Arcs; import com.github.rma350.jgraphv.core.shapes.Points; import com.github.rma350.jgraphv.core.shapes.PointsBuffer; import com.github.rma350.jgraphv.core.shapes.NativeShapeBuffer.BufferUsage; public class ArcDemo extends Demo { private FloatParam arcWidth; public ArcDemo() { super("Arc demo"); arcWidth = new FloatParam("Arc Width", 3); } @Override protected void setup(Engine engine) { ArcBuilder arcBuilder = new ArcBuilder(engine.getGL().getLinMath()); arcBuilder.iFrom.set(10,20); arcBuilder.iTo.set(100,20); arcBuilder.iArcWidth = arcWidth.getValue(); arcBuilder.computeArc(); ArcBufferBuilder bufferBuilder = new ArcBufferBuilder(1); bufferBuilder.appendArc(arcBuilder); ArcBuffer arcsBuffer = new ArcBuffer(engine.getGL(), bufferBuilder, BufferUsage.STATIC); Arcs arcs = new Arcs(engine.getCamera(), engine.getArcShader(), arcsBuffer, 1, 0, 0, 1); engine.getScene().addToScene(arcs); PointsBuffer points = new PointsBuffer( engine.getGL(), new float[] { 10, 20, 10, 100, 20, 10 }, BufferUsage.STATIC); engine.getScene().addToScene( new Points(engine.getCamera(), engine.getPointsShader(), points, 0, 1, 0, 1)); } }
apache-2.0
Monkeyyingbao/Mobilesafe
phone/app/src/main/java/com/itsafe/phone/utils/Md5Utils.java
2742
package com.itsafe.phone.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by Hello World on 2016/3/10. */ public class Md5Utils { /** * @param filePath 文件路径 * @return 文件的MD5值 */ public static String getFileMd5(String filePath) { StringBuilder mess = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("md5"); // 读取文件 FileInputStream fis = new FileInputStream(new File(filePath)); byte[] buffer = new byte[1024 * 10]; int len = fis.read(buffer); while (len != -1) { md.update(buffer, 0, len);// 不停的读取文件内容 len = fis.read(buffer);// 继续读取 } // 读取文件完毕 byte[] digest = md.digest(); // byte 8bit 4bit 十六进制 2位十六进制 for (byte b : digest) {// 数组 Iterable // 把一个字节转成十六进制 8 >> 2 // 去掉一个int类型前3个字节 0a int d = b & 0x000000ff; String s = Integer.toHexString(d); if (s.length() == 1) { s = "0" + s; } mess.append(s); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return (mess + "").toUpperCase(); } /** * * @param str 需要加密的字符串 * @return 加密后的MD5值 */ public static String encode(String str) { String res = ""; String s = ""; try { MessageDigest md = MessageDigest.getInstance("md5"); //MD5加密后的字节数组 byte[] digest = md.digest(str.getBytes()); //把字节数组转成字符串 // byte 8bit 4bit 十六进制 2位十六进制 for (byte b: digest) {//数组 Iterable //把一个字节转成十六进制 8 >> 2 //去掉一个int类型前3个字节 0a int d = b & 0x000000ff; s = Integer.toHexString(d); if (s.length() == 1) { s = "0" + s; } res = res + s; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return res; } }
apache-2.0
RadioLink/RadioLinkApp
app/src/main/java/jp/tf_web/radiolink/net/udp/service/UDPReceiverListener.java
714
package jp.tf_web.radiolink.net.udp.service; import java.net.InetSocketAddress; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.socket.DatagramPacket; /** UDPからの受信等を取得するリスナー * * Created by furukawanobuyuki on 2015/12/09. */ public interface UDPReceiverListener { /** STUN Binding 結果を通知 * * @param publicSocketAddr パブリックIP,ポート */ void onStunBinding(final InetSocketAddress publicSocketAddr); /** 受信したデータを通知 * * @param ctx * @param packet * @param data */ void onReceive(final ChannelHandlerContext ctx,final DatagramPacket packet,final byte[] data); }
apache-2.0
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/TerminalUtil.java
1901
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.aesh.readline.util; import org.aesh.readline.tty.terminal.TerminalConnection; import org.aesh.terminal.tty.Size; import java.io.IOException; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ public class TerminalUtil { public static int terminalWidth() { return terminalSize().getWidth(); } public static int terminalHeight() { return terminalSize().getHeight(); } public static Size terminalSize() { TerminalConnection connection = terminal(); if(connection != null) return connection.size(); else return new Size(-1,-1); } public static String terminalType() { TerminalConnection connection = terminal(); if(connection != null) return connection.device().type(); else return ""; } private static TerminalConnection terminal() { try { return new TerminalConnection(); } catch (IOException e) { return null; } } }
apache-2.0
rahulsom/grooves
grooves-groovy/src/main/java/com/github/rahulsom/grooves/groovy/transformations/internal/EventASTTransformation.java
1822
package com.github.rahulsom.grooves.groovy.transformations.internal; import com.github.rahulsom.grooves.groovy.transformations.Event; import com.github.rahulsom.grooves.groovy.transformations.Query; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.transform.AbstractASTTransformation; import org.codehaus.groovy.transform.GroovyASTTransformation; import java.text.MessageFormat; import java.util.logging.Logger; /** * Adds methods corresponding to the {@link Event} into the list of methods that a {@link Query} * must handle. * * @author Rahul Somasunderam */ @GroovyASTTransformation public class EventASTTransformation extends AbstractASTTransformation { private static final Class<Event> MY_CLASS = Event.class; private static final ClassNode MY_TYPE = ClassHelper.make(MY_CLASS); private final Logger log = Logger.getLogger(getClass().getName()); @Override public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotatedNode annotatedNode = (AnnotatedNode) nodes[1]; AnnotationNode annotationNode = (AnnotationNode) nodes[0]; if (MY_TYPE.equals(annotationNode.getClassNode()) && annotatedNode instanceof ClassNode) { final Expression theAggregate = annotationNode.getMember("value"); final ClassNode theClassNode = (ClassNode) annotatedNode; final String aggregateClassName = theAggregate.getType().getName(); log.fine(() -> MessageFormat.format("Adding event {0} to aggregate {1}", theClassNode.getNameWithoutPackage(), aggregateClassName)); AggregateASTTransformation.addEventToAggregate(aggregateClassName, theClassNode); } } }
apache-2.0
tpb1908/AndroidProjectsClient
markdowntextview/src/main/java/com/tpb/mdtext/views/spans/ClickableImageSpan.java
1138
package com.tpb.mdtext.views.spans; import android.graphics.drawable.Drawable; import android.text.style.ImageSpan; import com.tpb.mdtext.handlers.ImageClickHandler; import com.tpb.mdtext.imagegetter.HttpImageGetter; import java.lang.ref.WeakReference; /** * Created by theo on 22/04/17. */ public class ClickableImageSpan extends ImageSpan implements WrappingClickableSpan.WrappedClickableSpan { private WeakReference<ImageClickHandler> mImageClickHandler; public ClickableImageSpan(Drawable d, ImageClickHandler handler) { super(d); mImageClickHandler = new WeakReference<>(handler); } @Override public Drawable getDrawable() { if(super.getDrawable() instanceof HttpImageGetter.URLDrawable && ((HttpImageGetter.URLDrawable) super.getDrawable()).getDrawable() != null) { return ((HttpImageGetter.URLDrawable) super.getDrawable()).getDrawable(); } return super.getDrawable(); } @Override public void onClick() { if(mImageClickHandler.get() != null) { mImageClickHandler.get().imageClicked(getDrawable()); } } }
apache-2.0
CoderTang/Itheima72
开源中国客户端T/src/com/itheima/oschina/ui/dialog/CommonToast.java
3991
package com.itheima.oschina.ui.dialog; import com.itheima.oschina.R; import com.itheima.oschina.util.TDevice; import com.itheima.oschina.util.TLog; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class CommonToast { public static final long DURATION_LONG = 5000L; public static final long DURATION_MEDIUM = 3500L; public static final long DURATION_SHORT = 2500L; private long _duration = 3500l; private ToastView _toastVw; public CommonToast(Activity activity) { init(activity); } public CommonToast(Activity activity, String message, int icon, String action, int actionIcon, long l) { _duration = l; init(activity); setMessage(message); setMessageIc(icon); setAction(action); setActionIc(actionIcon); } private void init(Activity activity) { _toastVw = new ToastView(activity); setLayoutGravity(81); } public long getDuration() { return _duration; } public void setAction(String s) { _toastVw.actionTv.setText(s); } public void setActionIc(int i) { _toastVw.actionIv.setImageResource(i); } public void setDuration(long l) { _duration = l; } public void setLayoutGravity(int i) { if (i != 0) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(-2, -2); params.gravity = i; int j = (int) TDevice.dpToPixel(16F); params.setMargins(j, j, j, j); _toastVw.setLayoutParams(params); } } public void setMessage(String s) { _toastVw.messageTv.setText(s); } public void setMessageIc(int i) { _toastVw.messageIc.setImageResource(i); } public void show() { final ViewGroup content = (ViewGroup) ((Activity) _toastVw.getContext()) .findViewById(android.R.id.content); if (content != null) { ObjectAnimator.ofFloat(_toastVw, "alpha", 0.0F).setDuration(0L) .start(); content.addView(_toastVw); ObjectAnimator.ofFloat(_toastVw, "alpha", 0.0F, 1.0F) .setDuration(167L).start(); _toastVw.postDelayed(new Runnable() { @Override public void run() { ObjectAnimator animator = ObjectAnimator.ofFloat(_toastVw, "alpha", 1.0F, 0.0F); animator.setDuration(100L); animator.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator animation) { content.removeView(_toastVw); } @Override public void onAnimationCancel(Animator animation) { } }); animator.start(); } }, _duration); } else { TLog.error("Toast not shown! Content view is null!"); } } private class ToastView extends FrameLayout { public ImageView actionIv; public TextView actionTv; public ImageView messageIc; public TextView messageTv; public ToastView(Context context) { this(context, null); } public ToastView(Context context, AttributeSet attributeset) { this(context, attributeset, 0); } public ToastView(Context context, AttributeSet attributeset, int i) { super(context, attributeset, i); init(); } private void init() { LayoutInflater.from(getContext()).inflate( R.layout.view_base_toast, this, true); messageTv = (TextView) findViewById(R.id.title_tv); messageIc = (ImageView) findViewById(R.id.icon_iv); actionTv = (TextView) findViewById(R.id.title_tv); actionIv = (ImageView) findViewById(R.id.icon_iv); } } }
apache-2.0
ow2-chameleon/fuchsia
bases/knx/calimero/src/main/java/tuwien/auto/calimero/knxnetip/servicetype/SearchRequest.java
5426
/* * #%L * OW2 Chameleon - Fuchsia Framework * %% * Copyright (C) 2009 - 2014 OW2 Chameleon * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /* Calimero - A library for KNX network access Copyright (C) 2005 Bernhard Erb Copyright (C) 2006-2008 B. Malinowsky 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. 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 GNU General Public License cover the whole combination. As a special 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 this 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 tuwien.auto.calimero.knxnetip.servicetype; import java.io.ByteArrayOutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import tuwien.auto.calimero.exception.KNXFormatException; import tuwien.auto.calimero.knxnetip.util.HPAI; /** * Represents a KNXnet/IP search request. * <p> * Such request is sent during KNXnet/IP device discovery destined to the discovery * endpoint of listening servers. The communication is done multicast, i.e. using the UDP * transport protocol.<br> * The counterpart sent in reply to the request are search responses. * <p> * Objects of this type are immutable. * * @author Bernhard Erb * @author B. Malinowsky * @see tuwien.auto.calimero.knxnetip.servicetype.SearchResponse * @see tuwien.auto.calimero.knxnetip.Discoverer */ public class SearchRequest extends ServiceType { private final HPAI endpoint; /** * Creates a search request out of a byte array. * <p> * * @param data byte array containing a search request structure * @param offset start offset of request in <code>data</code> * @throws KNXFormatException if no valid host protocol address information was found */ public SearchRequest(byte[] data, int offset) throws KNXFormatException { super(KNXnetIPHeader.SEARCH_REQ); endpoint = new HPAI(data, offset); } /** * Creates a new search request with the given client response address. * <p> * * @param responseAddr address of the client discovery endpoint used for the response, * use <code>null</code> to create a NAT aware search request */ public SearchRequest(InetSocketAddress responseAddr) { super(KNXnetIPHeader.SEARCH_REQ); endpoint = new HPAI(HPAI.IPV4_UDP, responseAddr); } /** * Convenience constructor to create a new search request using the system default * local host with the given client port. * <p> * * @param responsePort port number of the client control endpoint used for the * response, 0 &lt;= port &lt;= 0xFFFF */ public SearchRequest(int responsePort) { super(KNXnetIPHeader.SEARCH_REQ); endpoint = new HPAI((InetAddress) null, responsePort); } /** * Returns the client discovery endpoint. * <p> * * @return discovery endpoint in a HPAI */ public final HPAI getEndpoint() { return endpoint; } /* (non-Javadoc) * @see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#getStructLength() */ short getStructLength() { return endpoint.getStructLength(); } /* (non-Javadoc) * @see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#toByteArray * (java.io.ByteArrayOutputStream) */ byte[] toByteArray(ByteArrayOutputStream os) { final byte[] buf = endpoint.toByteArray(); os.write(buf, 0, buf.length); return os.toByteArray(); } }
apache-2.0
pumpadump/sweble-wikitext
swc-engine/src/test/java/org/sweble/wikitext/engine/output/HtmlRendererTest.java
3805
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * 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.sweble.wikitext.engine.output; import java.io.File; import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import org.sweble.wikitext.engine.ExpansionCallback; import org.sweble.wikitext.engine.PageId; import org.sweble.wikitext.engine.PageTitle; import org.sweble.wikitext.engine.config.WikiConfig; import org.sweble.wikitext.engine.nodes.EngProcessedPage; import org.sweble.wikitext.engine.utils.EngineIntegrationTestBase; import de.fau.cs.osr.utils.FileCompare; import de.fau.cs.osr.utils.FileContent; import de.fau.cs.osr.utils.NamedParametrized; import de.fau.cs.osr.utils.TestResourcesFixture; @RunWith(value = NamedParametrized.class) public class HtmlRendererTest extends EngineIntegrationTestBase { private static final String FILTER_RX = ".*?\\.wikitext"; private static final String INPUT_SUB_DIR = "engine/output/wikitext"; private static final String EXPECTED_AST_SUB_DIR = "engine/output/rendered"; // ========================================================================= @Parameters public static List<Object[]> enumerateInputs() throws Exception { TestResourcesFixture resources = getTestResourcesFixture(); return resources.gatherAsParameters(INPUT_SUB_DIR, FILTER_RX, false); } // ========================================================================= private final File inputFile; // ========================================================================= public HtmlRendererTest( String title, TestResourcesFixture resources, File inputFile) { super(resources); this.inputFile = inputFile; } // ========================================================================= @Test @Ignore public void testRenderHtml() throws Exception { FileContent inputFileContent = new FileContent(inputFile); WikiConfig wikiConfig = getConfig(); PageTitle pageTitle = PageTitle.make(wikiConfig, inputFile.getName()); PageId pageId = new PageId(pageTitle, -1); String wikitext = inputFileContent.getContent(); ExpansionCallback expCallback = null; EngProcessedPage ast = getEngine().postprocess(pageId, wikitext, expCallback); TestCallback rendererCallback = new TestCallback(); String actual = HtmlRenderer.print(rendererCallback, wikiConfig, pageTitle, ast); File expectedFile = TestResourcesFixture.rebase( inputFile, INPUT_SUB_DIR, EXPECTED_AST_SUB_DIR, "html", true /* don't throw if file doesn't exist */); FileCompare cmp = new FileCompare(getResources()); cmp.compareWithExpectedOrGenerateExpectedFromActual(expectedFile, actual); } // ========================================================================= private static final class TestCallback implements HtmlRendererCallback { @Override public boolean resourceExists(PageTitle target) { // TODO: Add proper check return false; } @Override public MediaInfo getMediaInfo(String title, int width, int height) throws Exception { // TODO: Return proper media info return null; } } }
apache-2.0
svenruppert/20150901_proxy_deep_dive
modules/part02/src/main/java/org/rapidpm/event/opench2015/v002/p06/AddAdapterBWL.java
256
package org.rapidpm.event.opench2015.v002.p06; import org.rapidpm.event.opench2015.v002.*; /** * Created by svenruppert on 01.09.15. */ public class AddAdapterBWL { public Integer add(final Integer a, final Integer b) { return a + b + 120; } }
apache-2.0
spincast/spincast-framework
spincast-core-parent/spincast-core-tests/src/test/java/org/spincast/tests/json/JsonPathsSelectTest.java
19925
package org.spincast.tests.json; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.Arrays; import java.util.Date; import org.junit.Test; import org.spincast.core.json.JsonArray; import org.spincast.core.json.JsonManager; import org.spincast.core.json.JsonObject; import org.spincast.shaded.org.apache.commons.lang3.time.DateUtils; import org.spincast.testing.defaults.NoAppTestingBase; import com.google.inject.Inject; public class JsonPathsSelectTest extends NoAppTestingBase { @Inject protected JsonManager jsonManager; protected JsonManager getJsonManager() { return this.jsonManager; } @Test public void directString() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", "value1"); String result = obj.getString("key1"); assertEquals("value1", result); result = obj.getString(".key1"); assertEquals("value1", result); result = obj.getString("['key1']"); assertEquals("value1", result); result = obj.getString("[\"key1\"]"); assertEquals("value1", result); result = obj.getString("nope", "defaultVal"); assertEquals("defaultVal", result); } @Test public void directInteger() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", 123); Integer result = obj.getInteger("key1"); assertEquals(new Integer(123), result); result = obj.getInteger("['key1']"); assertEquals(new Integer(123), result); result = obj.getInteger("[\"key1\"]"); assertEquals(new Integer(123), result); result = obj.getInteger("nope", 456); assertEquals(new Integer(456), result); } @Test public void directLong() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", 123L); Long result = obj.getLong("key1"); assertEquals(new Long(123), result); result = obj.getLong("['key1']"); assertEquals(new Long(123), result); result = obj.getLong("[\"key1\"]"); assertEquals(new Long(123), result); result = obj.getLong("nope", 456L); assertEquals(new Long(456), result); } @Test public void directFloat() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", 12.34F); Float result = obj.getFloat("key1"); assertEquals(new Float(12.34), result); result = obj.getFloat("['key1']"); assertEquals(new Float(12.34), result); result = obj.getFloat("[\"key1\"]"); assertEquals(new Float(12.34), result); result = obj.getFloat("nope", 56.78F); assertEquals(new Float(56.78), result); } @Test public void directDouble() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", 12.34); Double result = obj.getDouble("key1"); assertEquals(new Double(12.34), result); result = obj.getDouble("['key1']"); assertEquals(new Double(12.34), result); result = obj.getDouble("[\"key1\"]"); assertEquals(new Double(12.34), result); result = obj.getDouble("nope", 56.78); assertEquals(new Double(56.78), result); } @Test public void directBoolean() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", true); Boolean result = obj.getBoolean("key1"); assertEquals(true, result); result = obj.getBoolean("['key1']"); assertEquals(true, result); result = obj.getBoolean("[\"key1\"]"); assertEquals(true, result); result = obj.getBoolean("nope", true); assertEquals(true, result); } @Test public void directBigDecimal() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", new BigDecimal("1234")); BigDecimal result = obj.getBigDecimal("key1"); assertEquals(new BigDecimal("1234"), result); result = obj.getBigDecimal("['key1']"); assertEquals(new BigDecimal("1234"), result); result = obj.getBigDecimal("[\"key1\"]"); assertEquals(new BigDecimal("1234"), result); result = obj.getBigDecimal("nope", new BigDecimal("567")); assertEquals(new BigDecimal("567"), result); } @Test public void directBytes() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("key1", "test".getBytes("UTF-8")); byte[] result = obj.getBytesFromBase64String("key1"); assertTrue(Arrays.equals("test".getBytes("UTF-8"), result)); result = obj.getBytesFromBase64String("['key1']"); assertTrue(Arrays.equals("test".getBytes("UTF-8"), result)); result = obj.getBytesFromBase64String("[\"key1\"]"); assertTrue(Arrays.equals("test".getBytes("UTF-8"), result)); result = obj.getBytesFromBase64String("nope", "test2".getBytes("UTF-8")); assertTrue(Arrays.equals("test2".getBytes("UTF-8"), result)); } @Test public void directDate() throws Exception { Date date = new Date(); JsonObject obj = getJsonManager().create(); obj.set("key1", date); Date result = obj.getDate("key1"); assertEquals(date, result); result = obj.getDate("['key1']"); assertEquals(date, result); result = obj.getDate("[\"key1\"]"); assertEquals(date, result); Date newDate = DateUtils.addHours(date, 1); result = obj.getDate("nope", newDate); assertEquals(newDate, result); } @Test public void obj() throws Exception { JsonObject inner = getJsonManager().create(); inner.set("key1", "value1"); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); JsonObject result = obj.getJsonObject("inner"); assertNotNull(result); assertEquals("value1", result.getString("key1")); result = obj.getJsonObject("nope"); assertNull(result); result = obj.getJsonObjectOrEmpty("nope"); assertNotNull(result); JsonObject defaultObj = getJsonManager().create(); defaultObj.set("key2", "value2"); result = obj.getJsonObject("nope", defaultObj); assertNotNull(result); assertEquals("value2", result.getString("key2")); } @Test public void array() throws Exception { JsonArray inner = getJsonManager().createArray(); inner.add("value1"); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); JsonArray result = obj.getJsonArray("inner"); assertNotNull(result); assertEquals("value1", result.getString(0)); result = obj.getJsonArray("nope"); assertNull(result); result = obj.getJsonArrayOrEmpty("nope"); assertNotNull(result); JsonArray defaultArray = getJsonManager().createArray(); defaultArray.add("value2"); result = obj.getJsonArray("nope", defaultArray); assertNotNull(result); assertEquals("value2", result.getString(0)); } @Test public void objString() throws Exception { JsonObject inner = getJsonManager().create(); inner.set("key1", "value1"); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); String result = obj.getString("inner.key1"); assertEquals("value1", result); result = obj.getString("nope", "defaultVal"); assertEquals("defaultVal", result); result = obj.getString("inner.nope", "defaultVal"); assertEquals("defaultVal", result); } @Test public void objInteger() throws Exception { JsonObject inner = getJsonManager().create(); inner.set("key1", 123); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); Integer result = obj.getInteger("inner.key1"); assertEquals(new Integer(123), result); result = obj.getInteger("nope", 456); assertEquals(new Integer(456), result); result = obj.getInteger("inner.nope", 456); assertEquals(new Integer(456), result); } @Test public void objObjString() throws Exception { JsonObject inner2 = getJsonManager().create(); inner2.set("key1", "value1"); JsonObject inner = getJsonManager().create(); inner.set("inner2", inner2); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); String result = obj.getString("inner.inner2.key1"); assertEquals("value1", result); result = obj.getString("inner.nope.key1"); assertEquals(null, result); result = obj.getString("inner.nope.key1", "defaultVal"); assertEquals("defaultVal", result); result = obj.getString("nope", "defaultVal"); assertEquals("defaultVal", result); result = obj.getString("inner.nope", "defaultVal"); assertEquals("defaultVal", result); } @Test public void arrayString() throws Exception { JsonArray inner = getJsonManager().createArray(); inner.add("value1"); inner.add("value2"); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); String result = obj.getString("inner[0]"); assertEquals("value1", result); result = obj.getString("inner[1]"); assertEquals("value2", result); result = obj.getString("inner[2]"); assertEquals(null, result); result = obj.getString("inner[2]", "defaultVal"); assertEquals("defaultVal", result); } @Test public void arrayArrayString() throws Exception { JsonArray inner2 = getJsonManager().createArray(); inner2.add("value1"); inner2.add("value2"); JsonArray inner = getJsonManager().createArray(); inner.add("value3"); inner.add(inner2); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); String result = obj.getString("inner[0]"); assertEquals("value3", result); result = obj.getString("inner[1][0]"); assertEquals("value1", result); result = obj.getString("inner[1][1]"); assertEquals("value2", result); result = obj.getString("inner[1][2]"); assertEquals(null, result); result = obj.getString("inner[1][2]", "defaultVal"); assertEquals("defaultVal", result); } @Test public void objArrayString() throws Exception { JsonArray inner2 = getJsonManager().createArray(); inner2.add("value1"); inner2.add("value2"); JsonObject inner = getJsonManager().create(); inner.set("inner2", inner2); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); String result = obj.getString("inner.inner2[0]"); assertEquals("value1", result); result = obj.getString("inner.inner2[1]"); assertEquals("value2", result); result = obj.getString("inner.inner2[2]"); assertEquals(null, result); result = obj.getString("inner.inner2[2]", "defaultVal"); assertEquals("defaultVal", result); } @Test public void arrayObjString() throws Exception { JsonObject inner2 = getJsonManager().create(); inner2.set("key1", "value1"); JsonArray inner = getJsonManager().createArray(); inner.add("value3"); inner.add(inner2); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); String result = obj.getString("inner[0]"); assertEquals("value3", result); result = obj.getString("inner[1].key1"); assertEquals("value1", result); result = obj.getString("inner[1].nope"); assertEquals(null, result); result = obj.getString("inner[1].nope", "defaultVal"); assertEquals("defaultVal", result); } @Test public void lots() throws Exception { Date date = new Date(); JsonArray inner7 = getJsonManager().createArray(); inner7.add("value7"); inner7.add(123); inner7.add(12.34); inner7.add(true); inner7.add(date); JsonObject inner6 = getJsonManager().create(); inner6.set("key5", inner7); inner6.set("key6", "value6"); JsonObject inner5 = getJsonManager().create(); inner5.set("key3", "value3"); inner5.set("key4", inner6); JsonArray inner4 = getJsonManager().createArray(); inner4.add("value2"); inner4.add(inner5); JsonArray inner3 = getJsonManager().createArray(); inner3.add(inner4); JsonObject inner2 = getJsonManager().create(); inner2.set("key1", "value1"); inner2.set("key2", inner3); JsonArray inner = getJsonManager().createArray(); inner.add("value0"); inner.add(inner2); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); String result = obj.getString("inner[0]"); assertEquals("value0", result); result = obj.getString("inner[1].key1"); assertEquals("value1", result); result = obj.getString("inner[1].key2[0][0]"); assertEquals("value2", result); result = obj.getString("inner[1].key2[0][1].key3"); assertEquals("value3", result); result = obj.getString("inner[1].key2[0][1].key4.key6"); assertEquals("value6", result); result = obj.getString("inner[1].key2[0][1].key4.key5[0]"); assertEquals("value7", result); result = obj.getString("inner[1]['key2'][0][1]['key4']['key5'][0]"); assertEquals("value7", result); result = obj.getString("inner[1][\"key2\"][0][1][\"key4\"][\"key5\"][0]"); assertEquals("value7", result); Integer resultInt = obj.getInteger("inner[1].key2[0][1].key4.key5[1]"); assertEquals(new Integer(123), resultInt); Double resultDouble = obj.getDouble("inner[1].key2[0][1].key4.key5[2]"); assertEquals(new Double(12.34), resultDouble); Boolean resultBoolean = obj.getBoolean("inner[1].key2[0][1].key4.key5[3]"); assertEquals(true, resultBoolean); Date resultDate = obj.getDate("inner[1].key2[0][1].key4.key5[4]"); assertEquals(date, resultDate); } @Test public void fromArrayString() throws Exception { JsonArray array = getJsonManager().createArray(); array.add("value1"); String result = array.getString("[0]"); assertEquals("value1", result); result = array.getString("[1]", "defaultVal"); assertEquals("defaultVal", result); } @Test public void fromArrayArrayString() throws Exception { JsonArray inner = getJsonManager().createArray(); inner.add("value2"); JsonArray array = getJsonManager().createArray(); array.add("value1"); array.add(inner); String result = array.getString("[0]"); assertEquals("value1", result); result = array.getString("[1][0]"); assertEquals("value2", result); result = array.getString("[1][1]"); assertEquals(null, result); result = array.getString("[1][1]", "defaultVal"); assertEquals("defaultVal", result); } @Test public void fromArrayObjectString() throws Exception { JsonObject inner = getJsonManager().create(); inner.set("key2", "value2"); JsonArray array = getJsonManager().createArray(); array.add("value1"); array.add(inner); String result = array.getString("[0]"); assertEquals("value1", result); result = array.getString("[1].key2"); assertEquals("value2", result); result = array.getString("[1]['key2']"); assertEquals("value2", result); result = array.getString("[1][\"key2\"]"); assertEquals("value2", result); } @Test public void fromArrayLots() throws Exception { JsonArray inner7 = getJsonManager().createArray(); inner7.add("value7"); JsonObject inner6 = getJsonManager().create(); inner6.set("key5", inner7); inner6.set("key6", "value6"); JsonObject inner5 = getJsonManager().create(); inner5.set("key3", "value3"); inner5.set("key4", inner6); JsonArray inner4 = getJsonManager().createArray(); inner4.add("value2"); inner4.add(inner5); JsonArray inner3 = getJsonManager().createArray(); inner3.add(inner4); JsonObject inner2 = getJsonManager().create(); inner2.set("key1", "value1"); inner2.set("key2", inner3); JsonArray inner = getJsonManager().createArray(); inner.add("value0"); inner.add(inner2); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); JsonArray array = getJsonManager().createArray(); array.add("toto"); array.add(obj); String result = array.getString("[0]"); assertEquals("toto", result); result = array.getString("[1].inner[1].key2[0][1]['key4'].key5[0]"); assertEquals("value7", result); } @Test public void invalidUnclosedBrackets() throws Exception { JsonArray inner = getJsonManager().createArray(); inner.add("value1"); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); try { obj.getString("inner[2", "defaultVal"); fail(); } catch (Exception ex) { } } @Test public void invalidEmptyKey() throws Exception { JsonObject inner = getJsonManager().create(); inner.set("key1", "value1"); JsonObject obj = getJsonManager().create(); obj.set("inner", inner); try { obj.getString("inner..inner", "defaultVal"); fail(); } catch (Exception ex) { System.out.println(ex); } } @Test public void jsonPathIsUsedAsIsWithBracketsAndQuotesAndCorrectEscaping() throws Exception { JsonObject obj = getJsonManager().create(); obj.setNoKeyParsing("this'.\"is[\\a.key[x", "value1", false); String result = obj.getString("[\"this'.\\\"is[\\\\a.key[x\"]", "defaultVal"); assertEquals("value1", result); result = obj.getString("['this\\'.\"is[\\\\a.key[x']", "defaultVal"); assertEquals("value1", result); result = obj.getString("this'.\"is[\\a.key[x", "defaultVal"); assertEquals("defaultVal", result); } @Test public void jsonPathOnImmutableObjets() throws Exception { JsonObject obj = getJsonManager().create(); obj.set("aaa.bbb[2].ccc", "Stromgol"); obj = obj.clone(false); assertFalse(obj.isMutable()); assertEquals("Stromgol", obj.getString("aaa.bbb[2].ccc")); JsonArray array = obj.getJsonArray("aaa.bbb"); assertNotNull(array); assertFalse(array.isMutable()); obj = obj.getJsonObject("aaa.bbb[2]"); assertNotNull(obj); assertFalse(obj.isMutable()); assertEquals("Stromgol", obj.getString(".ccc")); assertEquals("Stromgol", obj.getString("ccc")); assertEquals("Stromgol", obj.getString("['ccc']")); assertEquals("Stromgol", obj.getString("[\"ccc\"]")); } }
apache-2.0
jossjacobo/conductor-mobile
src/test/java/com/joss/conductor/mobile/LocomotiveTest.java
43409
package com.joss.conductor.mobile; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.TouchAction; import io.appium.java_client.remote.AndroidMobileCapabilityType; import io.appium.java_client.remote.MobileCapabilityType; import org.assertj.swing.assertions.Assertions; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.openqa.selenium.*; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.SessionId; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.Map; import static com.joss.conductor.mobile.MockTestUtil.matchesEntriesIn; import static com.joss.conductor.mobile.SwipeElementDirection.DOWN; import static io.appium.java_client.touch.WaitOptions.waitOptions; import static io.appium.java_client.touch.offset.PointOption.point; import static java.time.Duration.ofMillis; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; /** * Created on 9/14/16. */ public class LocomotiveTest { private AppiumDriver mockDriver; private ConductorConfig androidConfig; private ConductorConfig iosConfig; @BeforeMethod public void setup() { androidConfig = new ConductorConfig("/test_yaml/android_full.yaml"); iosConfig = new ConductorConfig("/test_yaml/ios_full.yaml"); mockDriver = mock(AppiumDriver.class); when(mockDriver.getSessionId()).thenReturn(new SessionId("123456789")); } @Test public void test_building_android_capabilities() { String nul = null; DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.UDID, "qwerty"); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Pixelated Nexus"); capabilities.setCapability(MobileCapabilityType.APP, "/full/path/to/android.apk"); capabilities.setCapability(MobileCapabilityType.ORIENTATION, "PORTRAIT"); capabilities.setCapability("autoGrantPermissions", true); capabilities.setCapability(MobileCapabilityType.NO_RESET, false); capabilities.setCapability(MobileCapabilityType.FULL_RESET, true); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "6.0"); capabilities.setCapability(AndroidMobileCapabilityType.AVD, "Nexus 13"); capabilities.setCapability(AndroidMobileCapabilityType.AVD_ARGS, "-no-window"); capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "LaunchActivity"); capabilities.setCapability(AndroidMobileCapabilityType.APP_WAIT_ACTIVITY, "HomeActivity"); capabilities.setCapability(AndroidMobileCapabilityType.INTENT_CATEGORY, "android.intent.category.LEANBACK_LAUNCHER"); capabilities.setCapability("xcodeOrgId", nul); capabilities.setCapability("xcodeSigningId", nul); capabilities.setCapability("waitForQuiescence", nul); capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "600"); capabilities.setCapability("idleTimeout", "600"); capabilities.setCapability("simpleIsVisibleCheck", true); capabilities.setCapability(MobileCapabilityType.APPIUM_VERSION, "1.13.0"); Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); Assertions.assertThat(locomotive.buildCapabilities(androidConfig)) .isEqualToComparingFieldByField(capabilities); } @Test public void test_building_ios_capabilities_no_devices() { iosConfig.setUdid("qwerty"); String nul = null; DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.UDID, "qwerty"); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Bravest Auxless Phone"); capabilities.setCapability(MobileCapabilityType.APP, "/full/path/to/ios.ipa"); capabilities.setCapability(MobileCapabilityType.ORIENTATION, "vertical"); capabilities.setCapability("autoGrantPermissions", false); capabilities.setCapability(MobileCapabilityType.NO_RESET, false); capabilities.setCapability(MobileCapabilityType.FULL_RESET, false); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "11.0"); capabilities.setCapability(AndroidMobileCapabilityType.AVD, nul); capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, nul); capabilities.setCapability(AndroidMobileCapabilityType.APP_WAIT_ACTIVITY, nul); capabilities.setCapability(AndroidMobileCapabilityType.INTENT_CATEGORY, nul); capabilities.setCapability("xcodeOrgId", "orgId"); capabilities.setCapability("xcodeSigningId", "signingId"); capabilities.setCapability("waitForQuiescence", true); capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "600"); capabilities.setCapability("idleTimeout", "600"); capabilities.setCapability("simpleIsVisibleCheck", true); Locomotive locomotive = new Locomotive() .setConfiguration(iosConfig) .setAppiumDriver(mockDriver); Assertions.assertThat(locomotive.buildCapabilities(iosConfig)) .isEqualToIgnoringNullFields(capabilities); } @Test public void test_custom_capabilities() { ConductorConfig config = new ConductorConfig("/test_yaml/android_defaults_custom_caps.yaml"); Locomotive locomotive = new Locomotive() .setConfiguration(config) .setAppiumDriver(mockDriver); DesiredCapabilities caps = locomotive.buildCapabilities(config); Assertions.assertThat(caps.getCapability("foo")) .isEqualTo("bar"); Assertions.assertThat(caps.getCapability("fizz")) .isEqualTo("buzz"); Assertions.assertThat(caps.getCapability(AndroidMobileCapabilityType.APP_ACTIVITY)) .isEqualTo("com.android.activity"); Assertions.assertThat(caps.getCapability(MobileCapabilityType.NO_RESET)) .isEqualTo(false); } @Test public void test_get_center_web_element() { MobileElement element = mock(MobileElement.class); when(element.getLocation()).thenReturn(new Point(50, 0)); when(element.getSize()).thenReturn(new Dimension(10, 10)); Point center = new Point(55, 5); Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); Assertions.assertThat(locomotive.getCenter(element)) .isEqualToComparingFieldByField(center); } @Test public void test_get_center_window() { WebDriver.Window window = mock(WebDriver.Window.class); when(window.getSize()).thenReturn(new Dimension(100, 50)); WebDriver.Options options = mock(WebDriver.Options.class); when(options.window()).thenReturn(window); when(mockDriver.manage()).thenReturn(options); Point center = new Point(50, 25); Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); Assertions.assertThat(locomotive.getCenter(/*webElement=*/null)) .isEqualToComparingFieldByField(center); } private Map<String, List<Object>> getTouchActionParameters(TouchAction action) { try { Method method = TouchAction.class.getDeclaredMethod("getParameters"); method.setAccessible(true); return (Map) method.invoke(action); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } return null; } private void assertThatActionMatches(TouchAction actual, TouchAction expected) { Map<String, List<Object>> actualParameters = getTouchActionParameters(actual); Map<String, List<Object>> expectedParameters = getTouchActionParameters(expected); assertThat(actualParameters, matchesEntriesIn(expectedParameters)); } private void initMockDriverSizes() { initMockDriverSizes(null); } private void initMockDriverSizes(WebElement mockElement) { if (mockElement != null) { when(mockElement.getLocation()).thenReturn(new Point(0, 0)); when(mockElement.getSize()).thenReturn(new Dimension(10, 10)); } WebDriver.Window window = mock(WebDriver.Window.class); when(window.getSize()).thenReturn(new Dimension(100, 100)); WebDriver.Options options = mock(WebDriver.Options.class); when(options.window()).thenReturn(window); when(mockDriver.manage()).thenReturn(options); } @Test public void test_perform_swipe_center_down() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(50, 75), new Point(0, 25)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenter(DOWN); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_long_press_swipe_center_down() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(50, 75), new Point(0, 25)}; for (int i = 0; i < configs.length; i++) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.longPressSwipeCenter(DOWN); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).longPress(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_with_custom_coordinates() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(20, 20), new Point(19, 19)}; for (int i = 0; i < configs.length; i++) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipe(new Point(1, 1), new Point(20, 20)); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(1, 1)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void startAppiumSessionCounter() { ConductorConfig customConfig = new ConductorConfig("/test_yaml/android_full.yaml"); // cause startAppiumSession to retry 4 times customConfig.setStartSessionRetries(4); // spy on the config to count invocations ConductorConfig spy = Mockito.spy(customConfig); final Locomotive locomotive = new Locomotive() .setConfiguration(spy); // run the method under test try { locomotive.startAppiumSession(1); assertThat("Expected startAppiumSession() has failed", false); } catch (WebDriverException e) { assertThat("Verify startAppiumSession() has failed", true); } // expected 4 retries, verified by making sure the spy has been called 4 times. verify(spy, times(4)).isLocal(); } @Test public void test_perform_swipe_center_down_long() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(50, 99), new Point(0, 49)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenterLong(DOWN); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_center_left() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(37, 50), new Point(-13, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenter(SwipeElementDirection.LEFT); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_center_left_long() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(25, 50), new Point(-25, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenterLong(SwipeElementDirection.LEFT); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_center_up() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(50, 37), new Point(0, -13)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenter(SwipeElementDirection.UP); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_center_up_long() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(50, 25), new Point(0, -25)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenterLong(SwipeElementDirection.UP); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_center_right() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(75, 50), new Point(25, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenter(SwipeElementDirection.RIGHT); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_center_right_long() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(99, 50), new Point(49, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCenterLong(SwipeElementDirection.RIGHT); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(50, 50)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_none_asserts() { initMockDriverSizes(); final Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); Assertions.assertThatThrownBy(() -> locomotive.swipeCenter(SwipeElementDirection.NONE)).isInstanceOf(IllegalArgumentException.class); Assertions.assertThatThrownBy(() -> locomotive.swipeCenterLong(SwipeElementDirection.NONE)).isInstanceOf(IllegalArgumentException.class); // Swipe @null Assertions.assertThatThrownBy(() -> locomotive.swipeCenter(null)).isInstanceOf(IllegalArgumentException.class); Assertions.assertThatThrownBy(() -> locomotive.swipeCenterLong(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void test_perform_corner_swipe_bottom_right() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(90, 40), new Point(0, -50)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerLong(ScreenCorner.BOTTOM_RIGHT, SwipeElementDirection.UP, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(90, 90)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_long_bottom_right() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(90, 1), new Point(0, -89)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerSuperLong(ScreenCorner.BOTTOM_RIGHT, SwipeElementDirection.UP, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(90, 90)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_bottom_left() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(10, 40), new Point(0, -50)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerLong(ScreenCorner.BOTTOM_LEFT, SwipeElementDirection.UP, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(10, 90)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_long_bottom_left() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(10, 1), new Point(0, -89)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerSuperLong(ScreenCorner.BOTTOM_LEFT, SwipeElementDirection.UP, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(10, 90)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_top_right() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(90, 60), new Point(0, 50)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerLong(ScreenCorner.TOP_RIGHT, DOWN, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(90, 10)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_long_top_right() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(90, 99), new Point(0, 89)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerSuperLong(ScreenCorner.TOP_RIGHT, DOWN, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(90, 10)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_top_left() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(10, 60), new Point(0, 50)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerLong(ScreenCorner.TOP_LEFT, DOWN, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(10, 10)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_long_top_left() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(10, 99), new Point(0, 89)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerSuperLong(ScreenCorner.TOP_LEFT, DOWN, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(10, 10)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_right_top_left() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(60, 10), new Point(50, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerLong(ScreenCorner.TOP_LEFT, SwipeElementDirection.RIGHT, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(10, 10)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_corner_swipe_left_top_right() { initMockDriverSizes(); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(40, 10), new Point(-50, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeCornerLong(ScreenCorner.TOP_RIGHT, SwipeElementDirection.LEFT, 100); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(90, 10)) .waitAction(waitOptions(ofMillis(100))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_down() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(5, 30), new Point(0, 25)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipe(DOWN, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_down_long() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(5, 55), new Point(0, 50)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeLong(DOWN, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_left() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(3, 5), new Point(-2, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipe(SwipeElementDirection.LEFT, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_left_long() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(2, 5), new Point(-3, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeLong(SwipeElementDirection.LEFT, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_up() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(5, 3), new Point(0, -2)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipe(SwipeElementDirection.UP, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_up_long() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(5, 2), new Point(0, -3)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeLong(SwipeElementDirection.UP, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_right() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(30, 5), new Point(25, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipe(SwipeElementDirection.RIGHT, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_perform_swipe_on_element_right_long() { final MobileElement element = mock(MobileElement.class); initMockDriverSizes(element); ConductorConfig[] configs = {androidConfig, iosConfig}; Point[] moveTo = {new Point(55, 5), new Point(50, 0)}; for (int i = 0; i < 2; ++i) { final Locomotive locomotive = new Locomotive() .setConfiguration(configs[i]) .setAppiumDriver(mockDriver); locomotive.swipeLong(SwipeElementDirection.RIGHT, element); ArgumentCaptor<TouchAction> touchCapture = ArgumentCaptor.forClass(TouchAction.class); verify(mockDriver, times(i + 1)) .performTouchAction(touchCapture.capture()); assertThatActionMatches(touchCapture.getValue(), new TouchAction(mockDriver).press(point(5, 5)) .waitAction(waitOptions(ofMillis(2000))) .moveTo(point(moveTo[i].x, moveTo[i].y)) .release()); } } @Test public void test_getText_returns_element_text() { final MobileElement element = mock(MobileElement.class); final Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); when(element.getText()).thenReturn("string"); assertThat("Expected element text to return \"ElementText\" but it does not.", locomotive.getText(element).equals("string")); } @Test(expectedExceptions = NoSuchElementException.class, expectedExceptionsMessageRegExp = "Error: Unable to find element: .*" ) public void test_getText_returns_exception() { final MobileElement element = mock(MobileElement.class); final Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); when(element.getText()).thenThrow(NoSuchElementException.class); locomotive.getText(element); } @Test(expectedExceptions = NoSuchElementException.class, expectedExceptionsMessageRegExp = "Error: Unable to find element: .*") public void test_setText_returns_exception() { final MobileElement element = mock(MobileElement.class); final Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); doThrow(NoSuchElementException.class).when(element).setValue(anyString()); locomotive.setText(element, "text"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Element should be defined") public void test_click_returns_exception() { final MobileElement element = mock(MobileElement.class); final Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); doThrow(IllegalArgumentException.class).when(element).click(); locomotive.click(element); } @Test public void test_getAttribute_returns_attribute() { final MobileElement element = mock(MobileElement.class); final Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); when(element.getAttribute(anyString())).thenReturn("true"); assertThat("Error: Expected element attribute of \"visible\" to return \"true\", but it did not.", locomotive.getAttribute(element, "visible").equals("true")); } @Test(expectedExceptions = NoSuchElementException.class, expectedExceptionsMessageRegExp = "Error: Unable to find element: .*") public void test_getAttribute_returns_exception() { final MobileElement element = mock(MobileElement.class); final Locomotive locomotive = new Locomotive() .setConfiguration(androidConfig) .setAppiumDriver(mockDriver); when(element.getAttribute(anyString())).thenThrow(NoSuchElementException.class); locomotive.getAttribute(element, anyString()); } }
apache-2.0
leonarduk/stockmarketview
alphavantage4j/src/main/java/org/patriques/output/digitalcurrencies/Monthly.java
2795
package org.patriques.output.digitalcurrencies; import org.patriques.input.digitalcurrencies.Market; import org.patriques.output.JsonParser; import org.patriques.output.digitalcurrencies.data.DigitalCurrencyData; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Representation of monthly response from api. * * @see DigitalCurrencyResponse */ public class Monthly extends DigitalCurrencyResponse<DigitalCurrencyData> { public Monthly(final Map<String, String> metaData, final List<DigitalCurrencyData> digitalData) { super(metaData, digitalData); } /** * Creates {@code Monthly} instance from json. * * @param market parameter used to parse json correctly * @param json string to parse * @return Monthly instance */ public static Monthly from(Market market, String json) { Parser parser = new Parser(market); return parser.parseJson(json); } /** * Helper class for parsing json to {@code Monthly}. * * @see DigitalCurrencyParser * @see JsonParser */ private static class Parser extends DigitalCurrencyParser<Monthly> { /** * Used to find correct key values in json */ private final Market market; public Parser(Market market) { this.market = market; } @Override String getDigitalCurrencyDataKey() { return "Time Series (Digital Currency Monthly)"; } @Override Monthly resolve(Map<String, String> metaData, Map<String, Map<String, String>> digitalCurrencyData) { List<DigitalCurrencyData> currencyDataList = new ArrayList<>(); digitalCurrencyData.forEach((key, values) -> { currencyDataList.add( new DigitalCurrencyData( LocalDate.parse(key, SIMPLE_DATE_FORMAT).atStartOfDay(), Double.parseDouble(values.get("1a. open (" + market.getValue() + ")")), Double.parseDouble(values.get("1b. open (USD)")), Double.parseDouble(values.get("2a. high (" + market.getValue() + ")")), Double.parseDouble(values.get("2b. high (USD)")), Double.parseDouble(values.get("3a. low (" + market.getValue() + ")")), Double.parseDouble(values.get("3b. low (USD)")), Double.parseDouble(values.get("4a. close (" + market.getValue() + ")")), Double.parseDouble(values.get("4b. close (USD)")), Double.parseDouble(values.get("5. volume")), Double.parseDouble(values.get("6. market cap (USD)")) ) ); }); return new Monthly(metaData, currencyDataList); } } }
apache-2.0
xfmysql/xfwdata
xfweb/src/com/jdon/jivejdon/model/message/output/shield/Profanity.java
6007
/* * Copyright 2003-2005 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.jdon.jivejdon.model.message.output.shield; import java.util.StringTokenizer; import com.jdon.jivejdon.model.ForumMessage; import com.jdon.jivejdon.model.message.MessageRendering; /** * A ForumMessageFilter that filters out user-specified profanity. */ public class Profanity extends MessageRendering { /** * Array of all the bad words to filter. */ private String [] words = null; /** * Comma delimited list of words to filter. */ private String wordList = null; /** * Indicates if case of words should be ignored. */ private boolean ignoringCase = true; /** * Clones a new filter that will have the same properties and that * will wrap around the specified message. * * @param message the ForumMessage to wrap the new filter around. */ public MessageRendering clone(ForumMessage message){ Profanity filter = new Profanity(); // Set all properties on the new filter. filter.wordList = wordList; filter.ignoringCase = ignoringCase; filter.applyProperties(); filter.message = message; return filter; } /** * Returns ture if the filter will ignore case when filtering out * profanity. For example, when "ignore case" is turned on and "dog" is * in your word filter list, then "Dog" and "DOG" will also be filtered. * * @return true if case will be ignored when filtering words. */ public boolean isIgnoringCase() { return ignoringCase; } /** * Toggles the filter to ignore case when filtering words or not. For * example, when "ignore case" is turned on and "dog" is in your word * filter list, then "Dog" and "DOG" will also be filtered. * * @param ignoringCase true if case should be ignored when filtering. */ public void setIgnoringCase(boolean ignoringCase) { this.ignoringCase = ignoringCase; } /** * Returns the comma delimited list of words that will be filtered. * * @return the list of words to be filtered. */ public String getWordList() { return wordList; } /** * Sets the list of words to be filtered. Each word must seperated by a * comma. * * @param the comma delimited list of words to filter. */ public void setWordList(String wordList) { this.wordList = wordList; } //FROM THE FORUMMESSAGE INTERFACE// /** * <b>Overloaded</b> to return the subject of the message with profanity * filtered out. */ public String applyFilteredSubject() { return filterProfanity(message.getFilteredSubject()); } /** * <b>Overloaded</b> to return the body of the message with profanity * filtered out. */ public String applyFilteredBody() { return filterProfanity(message.getFilteredBody()); } /** * Applies new property values so the filter is ready for futher processing. */ private void applyProperties() { if (wordList == null || wordList.equals("")) { words = null; return; } StringTokenizer tokens = new StringTokenizer(wordList,","); String [] newWords = new String[tokens.countTokens()]; for (int i=0; i<newWords.length; i++) { if (ignoringCase) { newWords[i] = tokens.nextToken().toLowerCase().trim(); } else { newWords[i] = tokens.nextToken().trim(); } } words = newWords; } /** * Filters out bad words. */ private String filterProfanity(String str) { // Check to see if the string is null or zero-length if (str == null || "".equals(str) || wordList == null) { return str; } String lower; if (ignoringCase) { lower = str.toLowerCase(); } else { lower = str; } for (int i=0; i<words.length; i++) { str = replace(str, lower, words[i], cleanWord(words[i].length())); } return str; } /** * Generates a string of characters of specified length. For example: * !@%$ or %!@$%!@@ or ***** */ private String cleanWord(int length) { char[] newWord = new char[length]; for (int i=0; i<newWord.length; i++) { newWord[i] = '*'; } return new String(newWord); } /** * Replaces all instances of oldString with newString in the String line. */ private String replace(String line, String lowerCaseLine, String oldString, String newString ) { int i=0; if ( ( i=lowerCaseLine.indexOf( oldString, i ) ) >= 0 ) { int oLength = oldString.length(); int nLength = newString.length(); StringBuffer buf = new StringBuffer(line.length()+15); buf.append(line.substring(0,i)).append(newString); i += oLength; int j = i; while( ( i=lowerCaseLine.indexOf( oldString, i ) ) > 0 ) { buf.append(line.substring(j,i)).append(newString); i += oLength; j = i; } buf.append(line.substring(j)); return buf.toString(); } return line; } }
apache-2.0
masaki-yamakawa/geode
geode-connectors/src/main/java/org/apache/geode/connectors/jdbc/internal/ConnectorsDistributedSystemService.java
1749
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.connectors.jdbc.internal; import java.io.IOException; import java.net.URL; import java.util.Collection; import org.apache.geode.distributed.internal.DistributedSystemService; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.classloader.ClassPathLoader; public class ConnectorsDistributedSystemService implements DistributedSystemService { @Override public void init(InternalDistributedSystem internalDistributedSystem) { } @Override public Class getInterface() { return getClass(); } @Override public Collection<String> getSerializationAcceptlist() throws IOException { URL sanctionedSerializables = ClassPathLoader.getLatest().getResource(getClass(), "sanctioned-geode-connectors-serializables.txt"); return InternalDataSerializer.loadClassNames(sanctionedSerializables); } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v10/src/test/java/com/google/ads/googleads/v10/services/CustomInterestServiceClientTest.java
4447
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v10.services; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.api.gax.grpc.testing.MockGrpcService; import com.google.api.gax.grpc.testing.MockServiceHelper; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.protobuf.AbstractMessage; import io.grpc.StatusRuntimeException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.annotation.Generated; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @Generated("by gapic-generator-java") public class CustomInterestServiceClientTest { private static MockCustomInterestService mockCustomInterestService; private static MockServiceHelper mockServiceHelper; private LocalChannelProvider channelProvider; private CustomInterestServiceClient client; @BeforeClass public static void startStaticServer() { mockCustomInterestService = new MockCustomInterestService(); mockServiceHelper = new MockServiceHelper( UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockCustomInterestService)); mockServiceHelper.start(); } @AfterClass public static void stopServer() { mockServiceHelper.stop(); } @Before public void setUp() throws IOException { mockServiceHelper.reset(); channelProvider = mockServiceHelper.createChannelProvider(); CustomInterestServiceSettings settings = CustomInterestServiceSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(NoCredentialsProvider.create()) .build(); client = CustomInterestServiceClient.create(settings); } @After public void tearDown() throws Exception { client.close(); } @Test public void mutateCustomInterestsTest() throws Exception { MutateCustomInterestsResponse expectedResponse = MutateCustomInterestsResponse.newBuilder() .addAllResults(new ArrayList<MutateCustomInterestResult>()) .build(); mockCustomInterestService.addResponse(expectedResponse); String customerId = "customerId-1581184615"; List<CustomInterestOperation> operations = new ArrayList<>(); MutateCustomInterestsResponse actualResponse = client.mutateCustomInterests(customerId, operations); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockCustomInterestService.getRequests(); Assert.assertEquals(1, actualRequests.size()); MutateCustomInterestsRequest actualRequest = ((MutateCustomInterestsRequest) actualRequests.get(0)); Assert.assertEquals(customerId, actualRequest.getCustomerId()); Assert.assertEquals(operations, actualRequest.getOperationsList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void mutateCustomInterestsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockCustomInterestService.addException(exception); try { String customerId = "customerId-1581184615"; List<CustomInterestOperation> operations = new ArrayList<>(); client.mutateCustomInterests(customerId, operations); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } }
apache-2.0
WellframeInc/hellocharts-android
hellocharts-library/src/lecho/lib/hellocharts/provider/ColumnChartDataProvider.java
235
package lecho.lib.hellocharts.provider; import lecho.lib.hellocharts.model.ColumnChartData; public interface ColumnChartDataProvider { ColumnChartData getColumnChartData(); void setColumnChartData(ColumnChartData data); }
apache-2.0
raoofm/etcd-viewer
src/main/java/org/github/etcd/service/rest/impl/EtcdProxyImpl.java
9095
package org.github.etcd.service.rest.impl; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.ws.rs.NotFoundException; import javax.ws.rs.RedirectionException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.github.etcd.service.rest.EtcdError; import org.github.etcd.service.rest.EtcdException; import org.github.etcd.service.rest.EtcdMember; import org.github.etcd.service.rest.EtcdMembers; import org.github.etcd.service.rest.EtcdNode; import org.github.etcd.service.rest.EtcdProxy; import org.github.etcd.service.rest.EtcdResponse; import org.github.etcd.service.rest.EtcdSelfStats; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; public class EtcdProxyImpl implements EtcdProxy { private static final Logger LOG = LoggerFactory.getLogger(EtcdProxy.class); private final String targetUrl; private final String authenticationToken; private Client client; public EtcdProxyImpl(String targetUrl, String authenticationToken) { this.targetUrl = targetUrl; this.authenticationToken = authenticationToken; } public EtcdProxyImpl(String targetUrl) { this(targetUrl, null); } private WebTarget getWebTarget() { if (client == null) { client = ClientBuilder.newClient(); client.register(JacksonJsonProvider.class); // register the basic authentication filter if authentication information is provided if (authenticationToken != null) { client.register(new ClientRequestFilter() { @Override public void filter(ClientRequestContext requestContext) throws IOException { requestContext.getHeaders().add("Authorization", "Basic " + authenticationToken); } }); } } WebTarget target = client.target(targetUrl); return target; } @Override public void close() { if (client != null) { client.close(); client = null; } } @Override public String getVersion() { return getWebTarget() .path("/version") .request(MediaType.TEXT_PLAIN) .get(String.class); } @Override public Boolean isAuthEnabled() { try { Map<String, Object> result = getWebTarget().path("/v2/auth/enable").request(MediaType.APPLICATION_JSON).get(new GenericType<Map<String, Object>>() {}); return (Boolean) result.get("enabled"); } catch (NotFoundException e) { // LOG.warn(e.toString(), e); return false; } } @Override public EtcdSelfStats getSelfStats() { return new ExceptionHandlingProcessor<>(EtcdSelfStats.class).process(getWebTarget().path("/v2/stats/self").request(MediaType.APPLICATION_JSON).buildGet()); } @Override public List<EtcdMember> getMembers() { String version = getVersion(); LOG.info("Using version: '{}' to detect cluster members", version); LOG.info("Authentication is: " + (isAuthEnabled() ? "enabled" : "disabled")); if (version.contains("etcd 0.4")) { // alternatively we could use the key-value to retrieve the nodes contained at /v2/keys/_etcd/machines URI raftUri = UriBuilder.fromUri(targetUrl).port(7001).build(); List<Map<String, String>> items = client.target(raftUri).path("/v2/admin/machines").request(MediaType.APPLICATION_JSON).get(new GenericType<List<Map<String, String>>>() {}); System.out.println("Retrieved: " + items); List<EtcdMember> members = new ArrayList<>(items.size()); for (Map<String, String> item : items) { EtcdMember member = new EtcdMember(); member.setId(item.get("name")); member.setName(member.getId()); member.setState(item.get("state")); member.setClientURLs(Arrays.asList(item.get("clientURL"))); member.setPeerURLs(Arrays.asList(item.get("peerURL"))); members.add(member); } return members; } else { EtcdMembers members = new ExceptionHandlingProcessor<>(EtcdMembers.class).process(getWebTarget().path("/v2/members").request(MediaType.APPLICATION_JSON).buildGet()); return members.getMembers(); } } @Override public EtcdNode getNode(final String key) { Invocation getNode = getWebTarget() .path("/v2/keys/{key}") .resolveTemplate("key", normalizeKey(key), false) .request(MediaType.APPLICATION_JSON) .buildGet(); return new ExceptionHandlingProcessor<>(EtcdResponse.class).process(getNode).getNode(); } @Override public void saveNode(EtcdNode node) { EtcdResponse response = saveOrUpdateNode(node, false); LOG.debug("Created Node: " + response); } @Override public EtcdNode updateNode(EtcdNode node) { EtcdResponse response = saveOrUpdateNode(node, true); LOG.debug("Updated Node: " + response); return response.getPrevNode(); } @Override public EtcdNode deleteNode(EtcdNode node) { return deleteNode(node, false); } @Override public EtcdNode deleteNode(EtcdNode node, boolean recursive) { WebTarget target = getWebTarget().path("/v2/keys/{key}").resolveTemplate("key", normalizeKey(node.getKey()), false); if (node.isDir()) { if (recursive) { target = target.queryParam("recursive", recursive); } else { target = target.queryParam("dir", node.isDir()); } } Invocation deleteInvocation = target.request(MediaType.APPLICATION_JSON).buildDelete(); return new ExceptionHandlingProcessor<>(EtcdResponse.class).process(deleteInvocation).getNode(); } private String normalizeKey(final String key) { if (key == null) { return "/"; } return key.startsWith("/") ? key.substring(1) + "/" : key + "/"; } protected EtcdResponse saveOrUpdateNode(EtcdNode node, Boolean update) { if (node.isDir() && update && node.getTtl() == null) { LOG.warn("Remove directory TTL is not supported by etcd version 0.4.9"); } Form form = new Form(); if (node.isDir()) { form.param("dir", Boolean.TRUE.toString()); } else { form.param("value", node.getValue()); } if (update) { form.param("ttl", node.getTtl() == null ? "" : node.getTtl().toString()); } else if (node.getTtl() != null) { form.param("ttl", node.getTtl().toString()); } // we include prevExist parameter within all requests for safety form.param("prevExist", update.toString()); Invocation invocation = getWebTarget() .path("/v2/keys/{key}") .resolveTemplate("key", normalizeKey(node.getKey()), false) .request(MediaType.APPLICATION_JSON) .buildPut(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED)); return new ExceptionHandlingProcessor<>(EtcdResponse.class).process(invocation); } private static class ExceptionHandlingProcessor<T> { private final Class<T> responseType; public ExceptionHandlingProcessor(Class<T> responseType) { this.responseType = responseType; } public T process(Invocation invocation) { try { return invocation.invoke(responseType); } catch (RedirectionException e) { // TODO: maybe create another invocation and start over ??? throw new EtcdException(e); } catch (WebApplicationException e) { try { // try to read the contained api error if it exists EtcdError error = e.getResponse().readEntity(EtcdError.class); throw new EtcdException(e, error); } catch (EtcdException e1) { throw e1; } catch (Exception e1) { // just ignore this one and wrap the original LOG.debug(e1.getLocalizedMessage(), e1); throw new EtcdException(e); } } } } }
apache-2.0
SmileMx/Screen_Launcher
Launcher/src/com/tcl/simpletv/launcher2/Launcher.java
214778
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tcl.simpletv.launcher2; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.app.Activity; import android.app.ActivityOptions; import android.app.Dialog; import android.app.SearchManager; import android.app.WallpaperManager; import android.appwidget.AppWidgetHostView; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentCallbacks2; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources; import android.database.ContentObserver; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StrictMode; import android.os.SystemClock; import android.provider.Settings; import android.speech.RecognizerIntent; import android.text.Selection; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.method.TextKeyListener; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.ScaleAnimation; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Advanceable; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.tcl.simpletv.launcher2.DropTarget.DragObject; import com.tcl.simpletv.launcher2.localwidget.LocalWidgetInfo; import com.tcl.simpletv.launcher2.localwidget.LocalWidgetManager; import com.tcl.simpletv.launcher2.localwidget.LocalWidgetView; import com.tcl.simpletv.launcher2.popupswitch.ActionItem; import com.tcl.simpletv.launcher2.popupswitch.Curtain; import com.tcl.simpletv.launcher2.popupswitch.LampCord; import com.tcl.simpletv.launcher2.popupswitch.QuickAction; import com.tcl.simpletv.launcher2.screenmanager.ScreenManager; import com.tcl.simpletv.launcher2.submenu.LauncherMenuDialog; import com.tcl.simpletv.launcher2.submenu.AllAppMenuDialog; import com.tcl.simpletv.launcher2.submenu.AppSortModeDialog; import com.tcl.simpletv.launcher2.toolbar.ToolbarUtilities; import com.tcl.simpletv.launcher2.utils.ConstantUtil; import com.tcl.simpletv.launcher2.utils.FlatwiseListener; import com.tcl.simpletv.launcher2.wallpaper.HorizontalListView; import com.tcl.simpletv.launcher2.wallpaper.ImageAdapter; import com.tcl.simpletv.launcher2.wallpaper.WallpaperData; /** * Default launcher application. */ public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, View.OnTouchListener { static final String TAG = "Launcher"; static final boolean LOGD = false; /* * add by ljianwei; * date:2013-8-15 */ private final int DELETE_ITEM = 0; private final int UNINSTALL_ITEM = 1; private final int COLLECT_ITEM = 2; private final int UNCOLLECT_ITEM = 3; private final int SHARE_TTEM = 4; private Context mContext; private final int SHARE_MSG = 2; private static String ITEM_PATH = "/mnt/sdcard/launcherTemp/item.png"; static final boolean PROFILE_STARTUP = false; static final boolean DEBUG_WIDGETS = false; static final boolean DEBUG_STRICT_MODE = false; //Custom menu:local wallPaper/Add/Screen Manager private static final int MENU_GROUP_WALLPAPER = 1; private static final int REQUEST_CREATE_SHORTCUT = 1; private static final int REQUEST_CREATE_APPWIDGET = 5; private static final int REQUEST_PICK_APPLICATION = 6; private static final int REQUEST_PICK_SHORTCUT = 7; private static final int REQUEST_PICK_APPWIDGET = 9; private static final int REQUEST_PICK_WALLPAPER = 10; private static final int REQUEST_BIND_APPWIDGET = 11; static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate"; static final int SCREEN_COUNT = 0;//5; static final int DEFAULT_SCREEN = 0;//2; private static final String PREFERENCES = "launcher.preferences"; static final String FORCE_ENABLE_ROTATION_PROPERTY = "debug.force_enable_rotation"; static final String DUMP_STATE_PROPERTY = "debug.dumpstate"; // The Intent extra that defines whether to ignore the launch animation static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION = "com.android.launcher.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION"; // Type: int private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen"; // Type: int private static final String RUNTIME_STATE = "launcher.state"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y"; // Type: boolean private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder"; // Type: long private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y"; // Type: parcelable private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info"; private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon"; private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME = "com.android.launcher.toolbar_search_icon"; private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME = "com.android.launcher.toolbar_voice_search_icon"; /* private static final String SETWALLPAPER_ACTION = "com.tcl.simpletv.launcher2.SETWALLPAPER_ACTION";*/ /** The different states that Launcher can be in. */ private enum State { NONE, WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED,EDIT_STATE }; private static State mState = State.WORKSPACE; private AnimatorSet mStateAnimation; private AnimatorSet mDividerAnimator; static final int APPWIDGET_HOST_ID = 1024; private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300; private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600; private static final int SHOW_CLING_DURATION = 550; private static final int DISMISS_CLING_DURATION = 250; private static final Object sLock = new Object(); private static int sScreen = DEFAULT_SCREEN; // How long to wait before the new-shortcut animation automatically pans the workspace private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10; private final BroadcastReceiver mCloseSystemDialogsReceiver = new CloseSystemDialogsIntentReceiver(); private final ContentObserver mWidgetObserver = new AppWidgetResetObserver(); private LayoutInflater mInflater; public Workspace mWorkspace; //hide divider by xiangss 201308014 // private View mQsbDivider; // private View mDockDivider; public DragLayer mDragLayer; private DragController mDragController; public ScreenManager mScreenManager; private AppWidgetManager mAppWidgetManager; private LauncherAppWidgetHost mAppWidgetHost; private ItemInfo mPendingAddInfo = new ItemInfo(); private AppWidgetProviderInfo mPendingAddWidgetInfo; private int[] mTmpAddItemCellCoordinates = new int[2]; private FolderInfo mFolderInfo; private Hotseat mHotseat; private View mAllAppsButton; private SearchDropTargetBar mSearchDropTargetBar; private AppsCustomizeTabHost mAppsCustomizeTabHost; public AppsCustomizePagedView mAppsCustomizeContent; /* * add by leixp 2013-07-29 * Edit state show App and widget content * */ private AppsWidgetCustomizeTabHost mAppsEditCustomizeTabHost; private AppsCustomizePagedView mAppsEditCustomizeContent; private boolean mAutoAdvanceRunning = false; private Bundle mSavedState; // We set the state in both onCreate and then onNewIntent in some cases, which causes both // scroll issues (because the workspace may not have been measured yet) and extra work. // Instead, just save the state that we need to restore Launcher to, and commit it in onResume. private State mOnResumeState = State.NONE; private SpannableStringBuilder mDefaultKeySsb = null; private boolean mWorkspaceLoading = true; private boolean mHomeDestroyed = false; private boolean mPaused = true; private boolean mRestoring; private boolean mWaitingForResult; private boolean mOnResumeNeedsLoad; // Keep track of whether the user has left launcher private static boolean sPausedFromUserAction = false; private Bundle mSavedInstanceState; private LauncherModel mModel; private IconCache mIconCache; private boolean mUserPresent = true; private boolean mVisible = false; private boolean mAttached = false; private static LocaleConfiguration sLocaleConfiguration = null; private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>(); private Intent mAppMarketIntent = null; // Related to the auto-advancing of widgets private final int ADVANCE_MSG = 1; private final int mAdvanceInterval = 20000; private final int mAdvanceStagger = 250; private long mAutoAdvanceSentTime; private long mAutoAdvanceTimeLeft = -1; private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance = new HashMap<View, AppWidgetProviderInfo>(); // Determines how long to wait after a rotation before restoring the screen orientation to // match the sensor state. private final int mRestoreScreenOrientationDelay = 500; // External icons saved in case of resource changes, orientation, etc. private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2]; private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2]; private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2]; private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>(); static final ArrayList<String> sDumpLogs = new ArrayList<String>(); // We only want to get the SharedPreferences once since it does an FS stat each time we get // it from the context. private SharedPreferences mSharedPrefs; // Holds the page that we need to animate to, and the icon views that we need to animate up // when we scroll to that page on resume. private int mNewShortcutAnimatePage = -1; private ArrayList<View> mNewShortcutAnimateViews = new ArrayList<View>(); private ImageView mFolderIconImageView; private Bitmap mFolderIconBitmap; private Canvas mFolderIconCanvas; private Rect mRectForFolderAnimation = new Rect(); private LampCord lampCordView; private Curtain curtain; private BubbleTextView mWaitingForResume; private FlatwiseListener mFlatwiseListener; //平放状态监�? /** * 壁纸相关变量 */ //get the related values of wallpaper setting private ArrayList<Integer> mThumbs = new ArrayList<Integer>(); private ArrayList<Integer> mImages = new ArrayList<Integer>(); private WallpaperData wallpaperData; //the current wallpaper index private int curWallpaperIndex = 0; private LinearLayout wallpaer_layout; //壁纸是否显示 private boolean wallpaperShow = false; private HideFromAccessibilityHelper mHideFromAccessibilityHelper = new HideFromAccessibilityHelper(); private Runnable mBuildLayersRunnable = new Runnable() { public void run() { if (mWorkspace != null) { mWorkspace.buildPageHardwareLayers(); } } }; private static ArrayList<PendingAddArguments> sPendingAddList = new ArrayList<PendingAddArguments>(); private static class PendingAddArguments { int requestCode; Intent intent; long container; int screen; int cellX; int cellY; } private boolean doesFileExist(String filename) { FileInputStream fis = null; try { fis = openFileInput(filename); fis.close(); return true; } catch (java.io.FileNotFoundException e) { return false; } catch (java.io.IOException e) { return true; } } @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "---------onCreate-----"); if (DEBUG_STRICT_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(savedInstanceState); mContext = this; LauncherApplication app = ((LauncherApplication)getApplication()); LauncherApplication.setLauncherInstance(this); // mSharedPrefs = getSharedPreferences(LauncherApplication.getSharedPreferencesKey(), // Context.MODE_PRIVATE); mSharedPrefs = LauncherApplication.getPreferenceUtils().getsSharedPreferences(); //开机向导自己判断启动 // firstStartup(); LauncherApplication.setLocalWidgetManager(new LocalWidgetManager(this)); mModel = app.setLauncher(this); mIconCache = app.getIconCache(); mDragController = new DragController(this); mInflater = getLayoutInflater(); mAppWidgetManager = AppWidgetManager.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here, // this also ensures that any synchronous binding below doesn't re-trigger another // LauncherModel load. mPaused = false; if (PROFILE_STARTUP) { android.os.Debug.startMethodTracing( Environment.getExternalStorageDirectory() + "/launcher"); } wallpaperData = new WallpaperData(this); wallpaperData.findWallpapers(); mThumbs = wallpaperData.getmThumbs(); mImages = wallpaperData.getmImages(); checkForLocaleChange(); setContentView(R.layout.launcher); setupViews(); //显示状态栏子菜单图�? // getWindow().setFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY, // WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY); getWindow().setFlags(0x08000000, 0x08000000); // hide cling by xiangss 20130821 // showFirstRunWorkspaceCling(); registerContentObservers(); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); // Update customization drawer _after_ restoring the states if (mAppsCustomizeContent != null) { mAppsCustomizeContent.onPackagesUpdated(); } // Update Edit state customization drawer _after_ restoring the states if (mAppsEditCustomizeContent != null) { mAppsEditCustomizeContent.onPackagesUpdated(); } if (PROFILE_STARTUP) { android.os.Debug.stopMethodTracing(); } if (!mRestoring) { if (sPausedFromUserAction) { // If the user leaves launcher, then we should just load items asynchronously when // they return. mModel.startLoader(true, -1); } else { // We only load the page synchronously if the user rotates (or triggers a // configuration change) while launcher is in the foreground mModel.startLoader(true, mWorkspace.getCurrentPage()); } } if (!mModel.isAllAppsLoaded()) { ViewGroup appsCustomizeContentParent = (ViewGroup) mAppsCustomizeContent.getParent(); mInflater.inflate(R.layout.apps_customize_progressbar, appsCustomizeContentParent); } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mCloseSystemDialogsReceiver, filter); updateGlobalIcons(); // On large interfaces, we want the screen to auto-rotate based on the current orientation unlockScreenOrientation(true); DisplayMetrics dm = new DisplayMetrics(); // 获取屏幕信息 getWindowManager().getDefaultDisplay().getMetrics(dm); curtain = new Curtain(this,dm.widthPixels); // curtain.setViewVisible(true); lampCordView = new LampCord(this,dm.widthPixels); // lampCordView.setViewVisible(true); lampCordView.setCurtain(curtain); mFlatwiseListener = new FlatwiseListener(this); //add for systembar button goto all app page. by xssdmx 2013-07-24 if(getIntent().getBooleanExtra("goto_all_APP", false) == true){ Log.d(TAG, "onCreate-----goto_all_APP"); getIntent().putExtra("goto_all_APP", false); //clean goto app flag,否则转屏会有影�? showAllApps(false); } } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); if(mState == State.WORKSPACE){ curtain.setViewVisible(true); lampCordView.setViewVisible(true); } } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); curtain.setViewVisible(false); lampCordView.setViewVisible(false); } protected void onUserLeaveHint() { super.onUserLeaveHint(); sPausedFromUserAction = true; } private void updateGlobalIcons() { boolean searchVisible = false; boolean voiceVisible = false; // If we have a saved version of these external icons, we load them up immediately int coi = getCurrentOrientationIndexForGlobalIcons(); if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null || sAppMarketIcon[coi] == null) { // updateAppMarketIcon(); searchVisible = updateGlobalSearchIcon(); voiceVisible = updateVoiceSearchIcon(searchVisible); } if (sGlobalSearchIcon[coi] != null) { updateGlobalSearchIcon(sGlobalSearchIcon[coi]); searchVisible = true; } if (sVoiceSearchIcon[coi] != null) { updateVoiceSearchIcon(sVoiceSearchIcon[coi]); voiceVisible = true; } if (sAppMarketIcon[coi] != null) { updateAppMarketIcon(sAppMarketIcon[coi]); } if (mSearchDropTargetBar != null) { mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible); } } private void checkForLocaleChange() { if (sLocaleConfiguration == null) { new AsyncTask<Void, Void, LocaleConfiguration>() { @Override protected LocaleConfiguration doInBackground(Void... unused) { LocaleConfiguration localeConfiguration = new LocaleConfiguration(); readConfiguration(Launcher.this, localeConfiguration); return localeConfiguration; } @Override protected void onPostExecute(LocaleConfiguration result) { sLocaleConfiguration = result; checkForLocaleChange(); // recursive, but now with a locale configuration } }.execute(); return; } final Configuration configuration = getResources().getConfiguration(); final String previousLocale = sLocaleConfiguration.locale; final String locale = configuration.locale.toString(); final int previousMcc = sLocaleConfiguration.mcc; final int mcc = configuration.mcc; final int previousMnc = sLocaleConfiguration.mnc; final int mnc = configuration.mnc; boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc; if (localeChanged) { sLocaleConfiguration.locale = locale; sLocaleConfiguration.mcc = mcc; sLocaleConfiguration.mnc = mnc; mIconCache.flush(); final LocaleConfiguration localeConfiguration = sLocaleConfiguration; new Thread("WriteLocaleConfiguration") { @Override public void run() { writeConfiguration(Launcher.this, localeConfiguration); } }.start(); } } private static class LocaleConfiguration { public String locale; public int mcc = -1; public int mnc = -1; } private static void readConfiguration(Context context, LocaleConfiguration configuration) { DataInputStream in = null; try { in = new DataInputStream(context.openFileInput(PREFERENCES)); configuration.locale = in.readUTF(); configuration.mcc = in.readInt(); configuration.mnc = in.readInt(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { // Ignore } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Ignore } } } } private static void writeConfiguration(Context context, LocaleConfiguration configuration) { DataOutputStream out = null; try { out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); out.writeUTF(configuration.locale); out.writeInt(configuration.mcc); out.writeInt(configuration.mnc); out.flush(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { //noinspection ResultOfMethodCallIgnored context.getFileStreamPath(PREFERENCES).delete(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } } public DragLayer getDragLayer() { return mDragLayer; } boolean isDraggingEnabled() { // We prevent dragging when we are loading the workspace as it is possible to pick up a view // that is subsequently removed from the workspace in startBinding(). return !mModel.isLoadingWorkspace(); } static int getScreen() { synchronized (sLock) { return sScreen; } } static void setScreen(int screen) { synchronized (sLock) { sScreen = screen; } } /** * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have * a configuration step, this allows the proper animations to run after other transitions. */ private boolean completeAdd(PendingAddArguments args) { boolean result = false; switch (args.requestCode) { case REQUEST_PICK_APPLICATION: completeAddApplication(args.intent, args.container, args.screen, args.cellX, args.cellY); break; case REQUEST_PICK_SHORTCUT: processShortcut(args.intent); break; case REQUEST_CREATE_SHORTCUT: completeAddShortcut(args.intent, args.container, args.screen, args.cellX, args.cellY); result = true; break; case REQUEST_CREATE_APPWIDGET: int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); completeAddAppWidget(appWidgetId, args.container, args.screen, null, null); result = true; break; case REQUEST_PICK_WALLPAPER: // We just wanted the activity result here so we can clear mWaitingForResult break; } // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen, // if you turned the screen off and then back while in All Apps, Launcher would not // return to the workspace. Clearing mAddInfo.container here fixes this issue resetAddInfo(); return result; } @Override protected void onActivityResult( final int requestCode, final int resultCode, final Intent data) { if (requestCode == REQUEST_BIND_APPWIDGET) { int appWidgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1; if (resultCode == RESULT_CANCELED) { completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId); } else if (resultCode == RESULT_OK) { addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo); } return; } boolean delayExitSpringLoadedMode = false; boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET || requestCode == REQUEST_CREATE_APPWIDGET); mWaitingForResult = false; // We have special handling for widgets if (isWidgetDrop) { int appWidgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1; if (appWidgetId < 0) { Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" + "widget configuration activity."); completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId); } else { completeTwoStageWidgetDrop(resultCode, appWidgetId); } return; } // The pattern used here is that a user PICKs a specific application, // which, depending on the target, might need to CREATE the actual target. // For example, the user would PICK_SHORTCUT for "Music playlist", and we // launch over to the Music app to actually CREATE_SHORTCUT. if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) { final PendingAddArguments args = new PendingAddArguments(); args.requestCode = requestCode; args.intent = data; args.container = mPendingAddInfo.container; args.screen = mPendingAddInfo.screen; args.cellX = mPendingAddInfo.cellX; args.cellY = mPendingAddInfo.cellY; if (isWorkspaceLocked()) { sPendingAddList.add(args); } else { delayExitSpringLoadedMode = completeAdd(args); } } mDragLayer.clearAnimatedView(); // Exit spring loaded mode if necessary after cancelling the configuration of a widget exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode, null); } private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) { CellLayout cellLayout = (CellLayout) mWorkspace.getChildAt(mPendingAddInfo.screen); Runnable onCompleteRunnable = null; int animationType = 0; AppWidgetHostView boundWidget = null; if (resultCode == RESULT_OK) { animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION; final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId, mPendingAddWidgetInfo); boundWidget = layout; onCompleteRunnable = new Runnable() { @Override public void run() { completeAddAppWidget(appWidgetId, mPendingAddInfo.container, mPendingAddInfo.screen, layout, null); exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false, null); } }; } else if (resultCode == RESULT_CANCELED) { animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION; onCompleteRunnable = new Runnable() { @Override public void run() { exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false, null); } }; } if (mDragLayer.getAnimatedView() != null) { mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout, (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable, animationType, boundWidget, true); } else { // The animated view may be null in the case of a rotation during widget configuration onCompleteRunnable.run(); } } @Override protected void onResume() { super.onResume(); mFlatwiseListener.registerGSensorListener(); // Restore the previous launcher state if (mOnResumeState == State.WORKSPACE) { showWorkspace(false); } else if (mOnResumeState == State.APPS_CUSTOMIZE) { showAllApps(false); } mOnResumeState = State.NONE; // Process any items that were added while Launcher was away InstallShortcutReceiver.flushInstallQueue(this); mPaused = false; sPausedFromUserAction = false; if (mRestoring || mOnResumeNeedsLoad) { mWorkspaceLoading = true; mModel.startLoader(true, -1); mRestoring = false; mOnResumeNeedsLoad = false; } // Reset the pressed state of icons that were locked in the press state while activities // were launching if (mWaitingForResume != null) { // Resets the previous workspace icon press state mWaitingForResume.setStayPressed(false); } if (mAppsCustomizeContent != null) { // Resets the previous all apps icon press state mAppsCustomizeContent.resetDrawableState(); } if (mAppsEditCustomizeContent != null) { // Resets the previous all apps icon press state Edit state mAppsEditCustomizeContent.resetDrawableState(); } // It is possible that widgets can receive updates while launcher is not in the foreground. // Consequently, the widgets will be inflated in the orientation of the foreground activity // (framework issue). On resuming, we ensure that any widgets are inflated for the current // orientation. getWorkspace().reinflateWidgetsIfNecessary(); // Again, as with the above scenario, it's possible that one or more of the global icons // were updated in the wrong orientation. updateGlobalIcons(); } @Override protected void onPause() { // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled // to be consistent. So re-enable the flag here, and we will re-disable it as necessary // when Launcher resumes and we are still in AllApps. updateWallpaperVisibility(true); super.onPause(); mPaused = true; mDragController.cancelDrag(); mDragController.resetLastGestureUpTime(); mFlatwiseListener.unregisterGSensorListener(); } @Override public Object onRetainNonConfigurationInstance() { // Flag the loader to stop early before switching mModel.stopLoader(); if (mAppsCustomizeContent != null) { mAppsCustomizeContent.surrender(); } if (mAppsEditCustomizeContent != null) { mAppsEditCustomizeContent.surrender(); } return Boolean.TRUE; } // We can't hide the IME if it was forced open. So don't bother /* @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); WindowManager.LayoutParams lp = getWindow().getAttributes(); inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new android.os.Handler()) { protected void onReceiveResult(int resultCode, Bundle resultData) { Log.d(TAG, "ResultReceiver got resultCode=" + resultCode); } }); Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged"); } } */ private boolean acceptFilter() { final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); return !inputManager.isFullscreenMode(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //在出现壁纸浏览界面时,按任何键可以隐藏快捷壁纸浏�? if(wallpaperShow){ wallpaperShow = false; wallpaer_layout.setVisibility(View.GONE); } final int uniChar = event.getUnicodeChar(); final boolean handled = super.onKeyDown(keyCode, event); final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar); if (!handled && acceptFilter() && isKeyNotWhitespace) { boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb, keyCode, event); if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) { // something usable has been typed - start a search // the typed text will be retrieved and cleared by // showSearchDialog() // If there are multiple keystrokes before the search dialog takes focus, // onSearchRequested() will be called for every keystroke, // but it is idempotent, so it's fine. return onSearchRequested(); } } // Eat the long press event so the keyboard doesn't come up. if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) { return true; } return handled; } private String getTypedText() { return mDefaultKeySsb.toString(); } private void clearTypedText() { mDefaultKeySsb.clear(); mDefaultKeySsb.clearSpans(); Selection.setSelection(mDefaultKeySsb, 0); } /** * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type * State */ private static State intToState(int stateOrdinal) { State state = State.WORKSPACE; final State[] stateValues = State.values(); for (int i = 0; i < stateValues.length; i++) { if (stateValues[i].ordinal() == stateOrdinal) { state = stateValues[i]; break; } } return state; } /** * Restores the previous state, if it exists. * * @param savedState The previous state. */ private void restoreState(Bundle savedState) { if (savedState == null) { return; } State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal())); if (state == State.APPS_CUSTOMIZE) { mOnResumeState = State.APPS_CUSTOMIZE; } int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1); if (currentScreen > -1) { mWorkspace.setCurrentPage(currentScreen); } final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1); final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1); if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) { mPendingAddInfo.container = pendingAddContainer; mPendingAddInfo.screen = pendingAddScreen; mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X); mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y); mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X); mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y); mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO); mWaitingForResult = true; mRestoring = true; } boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false); if (renameFolder) { long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID); mFolderInfo = mModel.getFolderById(this, sFolders, id); mRestoring = true; } // Restore the AppsCustomize tab if (mAppsCustomizeTabHost != null) { String curTab = savedState.getString("apps_customize_currentTab"); if (curTab != null) { mAppsCustomizeTabHost.setContentTypeImmediate( mAppsCustomizeTabHost.getContentTypeForTabTag(curTab)); mAppsCustomizeContent.loadAssociatedPages( mAppsCustomizeContent.getCurrentPage()); } int currentIndex = savedState.getInt("apps_customize_currentIndex"); mAppsCustomizeContent.restorePageForIndex(currentIndex); } // Restore the AppsEditCustomize tab if (mAppsEditCustomizeTabHost != null) { String curTab = savedState.getString("apps_edit_customize_currentTab"); if (curTab != null) { mAppsEditCustomizeTabHost.setContentTypeImmediate( mAppsEditCustomizeTabHost.getContentTypeForTabTag(curTab)); mAppsEditCustomizeContent.loadAssociatedPages( mAppsEditCustomizeContent.getCurrentPage()); } int currentIndex = savedState.getInt("apps_edit_customize_currentIndex"); mAppsEditCustomizeContent.restorePageForIndex(currentIndex); } } ImageAdapter adapter,pull_wallpaper_adapter; TextView local_wallpaper_text,pull_wallpaper_text; HorizontalListView listview,pull_wallpaper_listview; /** * Finds all the views we need and configure them properly. */ private void setupViews() { final DragController dragController = mDragController; mDragLayer = (DragLayer) findViewById(R.id.drag_layer); mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace); //hide divider by xiangss 201308014 // mQsbDivider = (ImageView) findViewById(R.id.qsb_divider); // mDockDivider = (ImageView) findViewById(R.id.dock_divider); // Setup the drag layer mDragLayer.setup(this, dragController); mDragLayer.setOnClickListener(this); // hide hotseat by xiangss 20130805 // // Setup the hotseat // mHotseat = (Hotseat) findViewById(R.id.hotseat); // if (mHotseat != null) { // mHotseat.setup(this); // } // Setup the workspace mWorkspace.setHapticFeedbackEnabled(false); mWorkspace.setOnLongClickListener(this); mWorkspace.setup(dragController); dragController.addDragListener(mWorkspace); LauncherApplication.setWorkspace(mWorkspace); // Get the search/delete bar mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar); // Setup AppsCustomize mAppsCustomizeTabHost = (AppsCustomizeTabHost) findViewById(R.id.apps_customize_pane); mAppsCustomizeContent = (AppsCustomizePagedView) mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content); mAppsCustomizeContent.setup(this, dragController); /* SharedPreferences mSharedPrefs = LauncherApplication.getPreferenceUtils().getsSharedPreferences(); int cur_sort_index = mSharedPrefs.getInt(ConstantUtil.APP_SORT_MODE, 0); mAppsCustomizeContent.AppsCustomizeSort(cur_sort_index);*/ /* * add by leixp 2013-07-29 * Setup */ mAppsEditCustomizeTabHost = (AppsWidgetCustomizeTabHost) findViewById(R.id.apps_widget_customize_pane); mAppsEditCustomizeContent = (AppsCustomizePagedView) mAppsEditCustomizeTabHost.findViewById(R.id.apps_tcl_customize_pane_content); mAppsEditCustomizeContent.setup(this, dragController); // Setup the drag controller (drop targets have to be added in reverse order in priority) dragController.setDragScoller(mWorkspace); dragController.setScrollView(mDragLayer); dragController.setMoveTarget(mWorkspace); dragController.addDropTarget(mWorkspace); if (mSearchDropTargetBar != null) { mSearchDropTargetBar.setup(this, dragController); } mScreenManager = (ScreenManager)mDragLayer.findViewById(R.id.screen_manager); mScreenManager.setDragController(dragController); // dragController.addDropTarget(mScreenManager); initWallpaper(); if(!wallpaperShow){ //modified by luoss date:2013/8/26 //隐藏前去掉刚进去的默认焦�? adapter.setCurItem(-1); wallpaer_layout.setVisibility(View.GONE); } } private void initWallpaper(){ //setup the wallpaper_layout add by luoss wallpaer_layout = (LinearLayout)findViewById(R.id.wallpaper_chooser_launcher); local_wallpaper_text = (TextView)wallpaer_layout.findViewById(R.id.local_wallpaper_text); pull_wallpaper_text = (TextView)wallpaer_layout.findViewById(R.id.pull_wallpaper_text); local_wallpaper_text.setBackgroundResource(R.drawable.tab_selected_holo); // pull_wallpaper_text.setBackgroundResource(R.drawable.list_item_clear); listview = (HorizontalListView) wallpaer_layout.findViewById(R.id.listview); adapter = new ImageAdapter(this); adapter.setThumbs(mThumbs); //modified by luoss date:2013/8/26 //去掉刚进去的默认焦点 // curWallpaperIndex = mSharedPrefs.getInt(ConstantUtil.CURRENT_WALLPAPER_ITEM, 0); adapter.setCurItem(-1); listview.setAdapter(adapter); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) { // TODO Auto-generated method stub adapter.setCurItem(position); SharedPreferences.Editor editor = mSharedPrefs.edit(); editor.putInt(ConstantUtil.CURRENT_WALLPAPER_ITEM, position); editor.commit(); selectWallpaper(position); // Toast.makeText(Launcher.this, position + " click!", Toast.LENGTH_SHORT).show(); } }); pull_wallpaper_listview = (HorizontalListView) wallpaer_layout.findViewById(R.id.pull_wallpaper_listview); pull_wallpaper_adapter = new ImageAdapter(this); pull_wallpaper_adapter.setThumbs(mThumbs); //modified by luoss date:2013/8/26 //去掉刚进去的默认焦点 // curWallpaperIndex = mSharedPrefs.getInt(ConstantUtil.CURRENT_WALLPAPER_ITEM, 0); pull_wallpaper_adapter.setCurItem(-1); pull_wallpaper_listview.setAdapter(pull_wallpaper_adapter); pull_wallpaper_listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) { // TODO Auto-generated method stub pull_wallpaper_adapter.setCurItem(position); SharedPreferences.Editor editor = mSharedPrefs.edit(); editor.putInt(ConstantUtil.CURRENT_WALLPAPER_ITEM, position); editor.commit(); selectWallpaper(position); // Toast.makeText(Launcher.this, position + " click!", Toast.LENGTH_SHORT).show(); } }); //修改两个壁纸textView按下/弹起效果 by luoss local_wallpaper_text.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()) { case KeyEvent.ACTION_UP: local_wallpaper_text.setBackgroundResource(R.drawable.tab_selected_holo); /*pull_wallpaper_text.setBackgroundResource(R.drawable.list_item_clear); pull_wallpaper_listview.setVisibility(View.GONE); */ //暂时屏蔽 listview.setVisibility(View.VISIBLE); break; case KeyEvent.ACTION_DOWN: local_wallpaper_text.setBackgroundResource(R.drawable.tab_selected_pressed_holo); break; default: break; } return false; } }); //以下为下拉壁纸textView变化按钮,暂时屏蔽 /*pull_wallpaper_text.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()) { case KeyEvent.ACTION_UP: pull_wallpaper_text.setBackgroundResource(R.drawable.tab_selected_holo); local_wallpaper_text.setBackgroundResource(R.drawable.list_item_clear); pull_wallpaper_listview.setVisibility(View.VISIBLE); listview.setVisibility(View.GONE); break; case KeyEvent.ACTION_DOWN: pull_wallpaper_text.setBackgroundResource(R.drawable.tab_selected_pressed_holo); break; default: break; } return false; } }); */ } //调用系统设置壁纸服务设置壁纸 private void selectWallpaper(int position) { try { WallpaperManager wpm = (WallpaperManager) getSystemService( Context.WALLPAPER_SERVICE); wpm.setResource(mImages.get(position)); } catch (IOException e) { Log.e(TAG, "Failed to set wallpaper: " + e); } } /** * Creates a view representing a shortcut. * * @param info The data structure describing the shortcut. * * @return A View inflated from R.layout.application. */ View createShortcut(ShortcutInfo info) { return createShortcut(R.layout.application, (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info); } /** * Creates a view representing a shortcut inflated from the specified resource. * * @param layoutResId The id of the XML layout used to create the shortcut. * @param parent The group the shortcut belongs to. * @param info The data structure describing the shortcut. * * @return A View inflated from layoutResId. */ View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) { BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false); favorite.applyFromShortcutInfo(info, mIconCache); favorite.setOnClickListener(this); return favorite; } /** * Add an application shortcut to the workspace. * * @param data The intent describing the application. * @param cellInfo The position on screen where to create the shortcut. */ void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) { final int[] cellXY = mTmpAddItemCellCoordinates; final CellLayout layout = getCellLayout(container, screen); // First we check if we already know the exact location where we want to add this item. if (cellX >= 0 && cellY >= 0) { cellXY[0] = cellX; cellXY[1] = cellY; } else if (!layout.findCellForSpan(cellXY, 1, 1)) { showOutOfSpaceMessage(isHotseatLayout(layout)); return; } final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this); if (info != null) { info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); info.container = ItemInfo.NO_ID; mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1], isWorkspaceLocked(), cellX, cellY); } else { Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data); } } /** * Add a shortcut to the workspace. * * @param data The intent describing the shortcut. * @param cellInfo The position on screen where to create the shortcut. */ private void completeAddShortcut(Intent data, long container, int screen, int cellX, int cellY) { int[] cellXY = mTmpAddItemCellCoordinates; int[] touchXY = mPendingAddInfo.dropPos; CellLayout layout = getCellLayout(container, screen); boolean foundCellSpan = false; ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null); if (info == null) { return; } final View view = createShortcut(info); // First we check if we already know the exact location where we want to add this item. if (cellX >= 0 && cellY >= 0) { cellXY[0] = cellX; cellXY[1] = cellY; foundCellSpan = true; // If appropriate, either create a folder or add to an existing folder if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0, true, null,null)) { return; } DragObject dragObject = new DragObject(); dragObject.dragInfo = info; if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject, true)) { return; } } else if (touchXY != null) { // when dragging and dropping, just find the closest free spot int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY); foundCellSpan = (result != null); } else { foundCellSpan = layout.findCellForSpan(cellXY, 1, 1); } if (!foundCellSpan) { showOutOfSpaceMessage(isHotseatLayout(layout)); return; } LauncherModel.addItemToDatabase(this, info, container, screen, cellXY[0], cellXY[1], false); if (!mRestoring) { mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, isWorkspaceLocked()); } } static int[] getSpanForWidget(Context context, int minWidth, int minHeight) { // We want to account for the extra amount of padding that we are adding to the widget // to ensure that it gets the full amount of space that it has requested int requiredWidth = minWidth; int requiredHeight = minHeight; return CellLayout.rectToCell(context.getResources(), requiredWidth, requiredHeight, null); } static int[] getSpanForWidget(Context context, ComponentName component, int minWidth, int minHeight) { Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null); // We want to account for the extra amount of padding that we are adding to the widget // to ensure that it gets the full amount of space that it has requested int requiredWidth = minWidth + padding.left + padding.right; int requiredHeight = minHeight + padding.top + padding.bottom; return CellLayout.rectToCell(context.getResources(), requiredWidth, requiredHeight, null); } static int[] getSpanForWidget(Context context, LocalWidgetInfo info) { return getSpanForWidget(context, info.minWidth, info.minHeight); } static int[] getMinSpanForWidget(Context context, LocalWidgetInfo info) { return getSpanForWidget(context, info.minResizeWidth, info.minResizeHeight); } static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) { return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight); } static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) { return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight); } static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) { return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight); } static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) { return getSpanForWidget(context, info.componentName, info.minResizeWidth, info.minResizeHeight); } /** * Add a widget to the workspace. * * @param appWidgetId The app widget id * @param cellInfo The position on screen where to create the widget. */ private void completeAddAppWidget(final int appWidgetId, long container, int screen, AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) { if (appWidgetInfo == null) { appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); } // Calculate the grid spans needed to fit this widget CellLayout layout = getCellLayout(container, screen); int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo); int[] spanXY = getSpanForWidget(this, appWidgetInfo); // Try finding open space on Launcher screen // We have saved the position to which the widget was dragged-- this really only matters // if we are placing widgets on a "spring-loaded" screen int[] cellXY = mTmpAddItemCellCoordinates; int[] touchXY = mPendingAddInfo.dropPos; int[] finalSpan = new int[2]; boolean foundCellSpan = false; if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) { cellXY[0] = mPendingAddInfo.cellX; cellXY[1] = mPendingAddInfo.cellY; spanXY[0] = mPendingAddInfo.spanX; spanXY[1] = mPendingAddInfo.spanY; foundCellSpan = true; } else if (touchXY != null) { // when dragging and dropping, just find the closest free spot int[] result = layout.findNearestVacantArea( touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0], spanXY[1], cellXY, finalSpan); spanXY[0] = finalSpan[0]; spanXY[1] = finalSpan[1]; foundCellSpan = (result != null); } else { foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]); } if (!foundCellSpan) { if (appWidgetId != -1) { // Deleting an app widget ID is a void call but writes to disk before returning // to the caller... new Thread("deleteAppWidgetId") { public void run() { mAppWidgetHost.deleteAppWidgetId(appWidgetId); } }.start(); } showOutOfSpaceMessage(isHotseatLayout(layout)); return; } // Build Launcher-specific widget info and save to database LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId, appWidgetInfo.provider); launcherInfo.spanX = spanXY[0]; launcherInfo.spanY = spanXY[1]; launcherInfo.minSpanX = mPendingAddInfo.minSpanX; launcherInfo.minSpanY = mPendingAddInfo.minSpanY; LauncherModel.addItemToDatabase(this, launcherInfo, container, screen, cellXY[0], cellXY[1], false); if (!mRestoring) { if (hostView == null) { // Perform actual inflation because we're live launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo); } else { // The AppWidgetHostView has already been inflated and instantiated launcherInfo.hostView = hostView; } launcherInfo.hostView.setTag(launcherInfo); launcherInfo.hostView.setVisibility(View.VISIBLE); launcherInfo.notifyWidgetSizeChanged(this); mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1], launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked()); addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo); } resetAddInfo(); } private void completeAddLocalWidget(final int appWidgetId, long container, int screen, LocalWidgetView hostView, LocalWidgetInfo appWidgetInfo) { // Calculate the grid spans needed to fit this widget CellLayout layout = getCellLayout(container, screen); int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo); int[] spanXY = getSpanForWidget(this, appWidgetInfo); // Try finding open space on Launcher screen // We have saved the position to which the widget was dragged-- this really only matters // if we are placing widgets on a "spring-loaded" screen int[] cellXY = mTmpAddItemCellCoordinates; int[] touchXY = mPendingAddInfo.dropPos; int[] finalSpan = new int[2]; boolean foundCellSpan = false; if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) { cellXY[0] = mPendingAddInfo.cellX; cellXY[1] = mPendingAddInfo.cellY; spanXY[0] = mPendingAddInfo.spanX; spanXY[1] = mPendingAddInfo.spanY; foundCellSpan = true; } else if (touchXY != null) { // when dragging and dropping, just find the closest free spot int[] result = layout.findNearestVacantArea( touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0], spanXY[1], cellXY, finalSpan); spanXY[0] = finalSpan[0]; spanXY[1] = finalSpan[1]; foundCellSpan = (result != null); } else { foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]); } if (!foundCellSpan) { showOutOfSpaceMessage(isHotseatLayout(layout)); return; } // Build Launcher-specific widget info and save to database LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId, appWidgetInfo.provider); launcherInfo.spanX = spanXY[0]; launcherInfo.spanY = spanXY[1]; launcherInfo.minSpanX = mPendingAddInfo.minSpanX; launcherInfo.minSpanY = mPendingAddInfo.minSpanY; LauncherModel.addItemToDatabase(this, launcherInfo, container, screen, cellXY[0], cellXY[1], false); if (!mRestoring) { if (hostView != null) { // The AppWidgetHostView has already been inflated and instantiated launcherInfo.localWidgetView = hostView; Log.e(TAG, "@@@@@@@@@@@@@@@@@" + hostView.getParent().getClass()); mDragLayer.removeView(hostView); } launcherInfo.localWidgetView.setTag(launcherInfo); launcherInfo.localWidgetView.setVisibility(View.VISIBLE); // launcherInfo.notifyWidgetSizeChanged(this); launcherInfo.localWidgetView.show(); mWorkspace.addInScreen(launcherInfo.localWidgetView, container, screen, cellXY[0], cellXY[1], launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked()); } resetAddInfo(); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { mUserPresent = false; mDragLayer.clearAllResizeFrames(); updateRunning(); // Reset AllApps to its initial state only if we are not in the middle of // processing a multi-step drop if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) { mAppsCustomizeTabHost.reset(); showWorkspace(false); } } else if (Intent.ACTION_USER_PRESENT.equals(action)) { mUserPresent = true; updateRunning(); } } }; @Override public void onAttachedToWindow() { super.onAttachedToWindow(); // Listen for broadcasts related to user-presence final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); registerReceiver(mReceiver, filter); mAttached = true; mVisible = true; } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); mVisible = false; if (mAttached) { unregisterReceiver(mReceiver); mAttached = false; } updateRunning(); } public void onWindowVisibilityChanged(int visibility) { mVisible = visibility == View.VISIBLE; updateRunning(); // The following code used to be in onResume, but it turns out onResume is called when // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged // is a more appropriate event to handle if (mVisible) { if(isAllAppsVisible()){ mAppsCustomizeTabHost.onWindowVisible(); } if(isEditState()){ mAppsEditCustomizeTabHost.onWindowVisible(); } if (!mWorkspaceLoading) { final ViewTreeObserver observer = mWorkspace.getViewTreeObserver(); // We want to let Launcher draw itself at least once before we force it to build // layers on all the workspace pages, so that transitioning to Launcher from other // apps is nice and speedy. Usually the first call to preDraw doesn't correspond to // a true draw so we wait until the second preDraw call to be safe observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { // We delay the layer building a bit in order to give // other message processing a time to run. In particular // this avoids a delay in hiding the IME if it was // currently shown, because doing that may involve // some communication back with the app. mWorkspace.postDelayed(mBuildLayersRunnable, 500); observer.removeOnPreDrawListener(this); return true; } }); } // When Launcher comes back to foreground, a different Activity might be responsible for // the app market intent, so refresh the icon // updateAppMarketIcon(); clearTypedText(); } } private void sendAdvanceMessage(long delay) { mHandler.removeMessages(ADVANCE_MSG); Message msg = mHandler.obtainMessage(ADVANCE_MSG); mHandler.sendMessageDelayed(msg, delay); mAutoAdvanceSentTime = System.currentTimeMillis(); } private void updateRunning() { boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty(); if (autoAdvanceRunning != mAutoAdvanceRunning) { mAutoAdvanceRunning = autoAdvanceRunning; if (autoAdvanceRunning) { long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft; sendAdvanceMessage(delay); } else { if (!mWidgetsToAdvance.isEmpty()) { mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval - (System.currentTimeMillis() - mAutoAdvanceSentTime)); } mHandler.removeMessages(ADVANCE_MSG); mHandler.removeMessages(0); // Remove messages sent using postDelayed() } } } private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == ADVANCE_MSG) { int i = 0; for (View key: mWidgetsToAdvance.keySet()) { final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId); final int delay = mAdvanceStagger * i; if (v instanceof Advanceable) { postDelayed(new Runnable() { public void run() { ((Advanceable) v).advance(); } }, delay); } i++; } sendAdvanceMessage(mAdvanceInterval); }else if(msg.what == SHARE_MSG){ Intent shareIntent = new Intent(Intent.ACTION_SEND); File file = new File(ITEM_PATH); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); shareIntent.setType("image/*"); shareIntent.putExtra( Intent.EXTRA_SUBJECT, getResources().getString( R.string.share_item)); shareIntent.putExtra(Intent.EXTRA_TEXT, "I would like to share this with you..."); startActivity(Intent.createChooser(shareIntent, getTitle())); } } }; void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) { if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return; View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId); if (v instanceof Advanceable) { mWidgetsToAdvance.put(hostView, appWidgetInfo); ((Advanceable) v).fyiWillBeAdvancedByHostKThx(); updateRunning(); } } void removeWidgetToAutoAdvance(View hostView) { if (mWidgetsToAdvance.containsKey(hostView)) { mWidgetsToAdvance.remove(hostView); updateRunning(); } } public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) { removeWidgetToAutoAdvance(launcherInfo.hostView); launcherInfo.hostView = null; } void showOutOfSpaceMessage(boolean isHotseatLayout) { int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space); Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show(); } public LauncherAppWidgetHost getAppWidgetHost() { return mAppWidgetHost; } public LauncherModel getModel() { return mModel; } void closeSystemDialogs() { getWindow().closeAllPanels(); // Whatever we were doing is hereby canceled. mWaitingForResult = false; } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent);//must store the new intent unless getIntent() will return the old one Log.d(TAG, "onNewIntent --- goto_all_APP = " + getIntent().getBooleanExtra("goto_all_APP", false)); // Close the menu if (Intent.ACTION_MAIN.equals(intent.getAction())) { // also will cancel mWaitingForResult. closeSystemDialogs(); //退出卸载模式 if(mAppsCustomizeContent.isUninstallMode() == true){ mAppsCustomizeContent.exitUninstallMode(); } //退出屏幕管理模式 if(isScreenManagerMode() == true){ closeScreenManager(-1); } //add for systembar button goto all app page. by xssdmx 2013-07-24 if(getIntent().getBooleanExtra("goto_all_APP", false) == true){ Log.d(TAG, "onNewIntent-----goto_all_APP"); getIntent().putExtra("goto_all_APP", false); //clean goto app flag,否则转屏会有影�? showAllApps(true); return; } //判断是否进入平放UI if(getIntent().getBooleanExtra("goto_normal_launcher", false) == true){ Log.d(TAG, "onNewIntent-----goto_normal_launcher is true."); getIntent().putExtra("goto_normal_launcher", false); //clean flag mFlatwiseListener.setCircledeskState(false); }else{ if(mFlatwiseListener.isCircledeskState() == true){ mFlatwiseListener.startCircledeskAction(); return; } } final boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); Runnable processIntent = new Runnable() { public void run() { Folder openFolder = mWorkspace.getOpenFolder(); // In all these cases, only animate if we're already on home mWorkspace.exitWidgetResizeMode(); if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() && openFolder == null) { mWorkspace.moveToDefaultScreen(true); } closeFolder(); exitSpringLoadedDragMode(); // If we are already on home, then just animate back to the workspace, // otherwise, just wait until onResume to set the state back to Workspace if (alreadyOnHome) { showWorkspace(true); } else { mOnResumeState = State.WORKSPACE; } final View v = getWindow().peekDecorView(); if (v != null && v.getWindowToken() != null) { InputMethodManager imm = (InputMethodManager)getSystemService( INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } // Reset AllApps to its initial state if (!alreadyOnHome && mAppsCustomizeTabHost != null) { mAppsCustomizeTabHost.reset(); } } }; if (alreadyOnHome && !mWorkspace.hasWindowFocus()) { // Delay processing of the intent to allow the status bar animation to finish // first in order to avoid janky animations. mWorkspace.postDelayed(processIntent, 350); } else { // Process the intent immediately. processIntent.run(); } } } @Override public void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); for (int page: mSynchronouslyBoundPages) { mWorkspace.restoreInstanceStateForChild(page); } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage()); super.onSaveInstanceState(outState); outState.putInt(RUNTIME_STATE, mState.ordinal()); // We close any open folder since it will not be re-opened, and we need to make sure // this state is reflected. closeFolder(); if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 && mWaitingForResult) { outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container); outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen); outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX); outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY); outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX); outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY); outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo); } if (mFolderInfo != null && mWaitingForResult) { outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true); outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id); } // Save the current AppsCustomize tab if (mAppsCustomizeTabHost != null) { String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag(); if (currentTabTag != null) { outState.putString("apps_customize_currentTab", currentTabTag); } int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex(); outState.putInt("apps_customize_currentIndex", currentIndex); } if(mAppsEditCustomizeTabHost != null){ String currentTabTag = mAppsEditCustomizeTabHost.getCurrentTabTag(); if (currentTabTag != null) { outState.putString("apps_edit_customize_currentTab", currentTabTag); } int currentIndex = mAppsEditCustomizeContent.getSaveInstanceStateIndex(); outState.putInt("apps_edit_customize_currentIndex", currentIndex); } } @Override public void onDestroy() { super.onDestroy(); mHomeDestroyed = true; // Remove all pending runnables mHandler.removeMessages(ADVANCE_MSG); mHandler.removeMessages(0); mWorkspace.removeCallbacks(mBuildLayersRunnable); // Stop callbacks from LauncherModel LauncherApplication app = ((LauncherApplication) getApplication()); mModel.stopLoader(); app.setLauncher(null); try { mAppWidgetHost.stopListening(); } catch (NullPointerException ex) { Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex); } mAppWidgetHost = null; mWidgetsToAdvance.clear(); TextKeyListener.getInstance().release(); // Disconnect any of the callbacks and drawables associated with ItemInfos on the workspace // to prevent leaking Launcher activities on orientation change. if (mModel != null) { mModel.unbindItemInfosAndClearQueuedBindRunnables(); } getContentResolver().unregisterContentObserver(mWidgetObserver); unregisterReceiver(mCloseSystemDialogsReceiver); mDragLayer.clearAllResizeFrames(); ((ViewGroup) mWorkspace.getParent()).removeAllViews(); mWorkspace.removeAllViews(); mWorkspace = null; mDragController = null; LauncherAnimUtils.onDestroyActivity(); } public DragController getDragController() { return mDragController; } @Override public void startActivityForResult(Intent intent, int requestCode) { if (requestCode >= 0) mWaitingForResult = true; super.startActivityForResult(intent, requestCode); } /** * Indicates that we want global search for this activity by setting the globalSearch * argument for {@link #startSearch} to true. */ @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { showWorkspace(true); if (initialQuery == null) { // Use any text typed in the launcher as the initial query initialQuery = getTypedText(); } if (appSearchData == null) { appSearchData = new Bundle(); // appSearchData.putString(Search.SOURCE, "launcher-search"); } Rect sourceBounds = new Rect(); if (mSearchDropTargetBar != null) { sourceBounds = mSearchDropTargetBar.getSearchBarBounds(); } startGlobalSearch(initialQuery, selectInitialQuery, appSearchData, sourceBounds); } /** * Starts the global search activity. This code is a copied from SearchManager */ public void startGlobalSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) { final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity(); if (globalSearchActivity == null) { Log.w(TAG, "No global search activity found."); return; } Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setComponent(globalSearchActivity); // Make sure that we have a Bundle to put source in if (appSearchData == null) { appSearchData = new Bundle(); } else { appSearchData = new Bundle(appSearchData); } // Set source to package name of app that starts global search, if not set already. if (!appSearchData.containsKey("source")) { appSearchData.putString("source", getPackageName()); } intent.putExtra(SearchManager.APP_DATA, appSearchData); if (!TextUtils.isEmpty(initialQuery)) { intent.putExtra(SearchManager.QUERY, initialQuery); } if (selectInitialQuery) { intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery); } intent.setSourceBounds(sourceBounds); try { startActivity(intent); } catch (ActivityNotFoundException ex) { Log.e(TAG, "Global search activity not found: " + globalSearchActivity); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (isWorkspaceLocked()) { return false; } super.onCreateOptionsMenu(menu); menu.add("menu"); // you should add at least one item ,otherwise it will called NullPointException return super.onCreateOptionsMenu(menu); } private Dialog launcher_Menudialog; //launcher页面弹出的menu对话框 private Dialog allapp_Menudialog; //所有应用页面弹出的menu对话框 /** * 拦截menu事件,在适当页面显示自己的菜单 */ @Override public boolean onMenuOpened(int featureId, Menu menu) { // TODO Auto-generated method stub //return super.onMenuOpened(featureId, menu); String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag(); Log.e(TAG, "currentTabTag = " + currentTabTag); // boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE); if(isAllAppsVisible() == true){ if(currentTabTag.equals("APPS") && !mAppsCustomizeContent.isUninstallMode()){ //dispaly only under apps Tabs if (allapp_Menudialog == null) { allapp_Menudialog = new AllAppMenuDialog(this); allapp_Menudialog.show(); } else { allapp_Menudialog.show(); } } }else{ //record the state of desktop editing or screen managerment mode in order not to dispaly the menu if(isEditState()){ Log.e(TAG, "isEditState = " + isEditState()); }else if(isScreenManagerMode()){ Log.e(TAG, "isScreenManagerMode = " + isScreenManagerMode()); }else{ if (launcher_Menudialog == null) { launcher_Menudialog = new LauncherMenuDialog(this); launcher_Menudialog.show(); } else { launcher_Menudialog.show(); } } } return false;//返回true,则显示系统menu } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (mAppsCustomizeTabHost.isTransitioning()) { return false; } boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE); menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } @Override public boolean onSearchRequested() { startSearch(null, false, null, true); // Use a custom animation for launching search return true; } public boolean isWorkspaceLocked() { return mWorkspaceLoading || mWaitingForResult; } private void resetAddInfo() { mPendingAddInfo.container = ItemInfo.NO_ID; mPendingAddInfo.screen = -1; mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1; mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1; mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1; mPendingAddInfo.dropPos = null; } void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget, AppWidgetProviderInfo appWidgetInfo) { if (appWidgetInfo.configure != null) { mPendingAddWidgetInfo = appWidgetInfo; // Launch over to configure widget, if needed Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); intent.setComponent(appWidgetInfo.configure); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET); } else { // Otherwise just add it completeAddAppWidget(appWidgetId, info.container, info.screen, boundWidget, appWidgetInfo); // Exit spring loaded mode if necessary after adding the widget exitSpringLoadedDragModeDelayed(true, false, null); } } void addLocalWidgetImpl(final int appWidgetId, ItemInfo info, LocalWidgetView boundWidget, LocalWidgetInfo widgetInfo) { // Otherwise just add it completeAddLocalWidget(appWidgetId, info.container, info.screen, boundWidget, widgetInfo); // Exit spring loaded mode if necessary after adding the widget exitSpringLoadedDragModeDelayed(true, false, null); } /** * Process a shortcut drop. * * @param componentName The name of the component * @param screen The screen where it should be added * @param cell The cell it should be added to, optional * @param position The location on the screen where it was dropped, optional */ void processShortcutFromDrop(ComponentName componentName, long container, int screen, int[] cell, int[] loc) { resetAddInfo(); mPendingAddInfo.container = container; mPendingAddInfo.screen = screen; mPendingAddInfo.dropPos = loc; if (cell != null) { mPendingAddInfo.cellX = cell[0]; mPendingAddInfo.cellY = cell[1]; } Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); createShortcutIntent.setComponent(componentName); processShortcut(createShortcutIntent); } /** * Process a widget drop. * * @param info The PendingAppWidgetInfo of the widget being added. * @param screen The screen where it should be added * @param cell The cell it should be added to, optional * @param position The location on the screen where it was dropped, optional */ void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen, int[] cell, int[] span, int[] loc) { resetAddInfo(); mPendingAddInfo.container = info.container = container; mPendingAddInfo.screen = info.screen = screen; mPendingAddInfo.dropPos = loc; mPendingAddInfo.minSpanX = info.minSpanX; mPendingAddInfo.minSpanY = info.minSpanY; if (cell != null) { mPendingAddInfo.cellX = cell[0]; mPendingAddInfo.cellY = cell[1]; } if (span != null) { mPendingAddInfo.spanX = span[0]; mPendingAddInfo.spanY = span[1]; } if(info.isLocalWidget == true){ addLocalWidgetImpl(info.localWidgetInfo.localWidgetId, info, info.localWidgetView, info.localWidgetInfo); return; } AppWidgetHostView hostView = info.boundWidget; int appWidgetId; if (hostView != null) { appWidgetId = hostView.getAppWidgetId(); addAppWidgetImpl(appWidgetId, info, hostView, info.info); } else { // In this case, we either need to start an activity to get permission to bind // the widget, or we need to start an activity to configure the widget, or both. appWidgetId = getAppWidgetHost().allocateAppWidgetId(); Bundle options = info.bindOptions; boolean success = false; if (options != null) { success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.componentName, options); } else { success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.componentName); } if (success) { addAppWidgetImpl(appWidgetId, info, null, info.info); } else { mPendingAddWidgetInfo = info.info; Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName); // TODO: we need to make sure that this accounts for the options bundle. // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options); startActivityForResult(intent, REQUEST_BIND_APPWIDGET); } } } void processShortcut(Intent intent) { // Handle case where user selected "Applications" String applicationName = getResources().getString(R.string.group_applications); String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); if (applicationName != null && applicationName.equals(shortcutName)) { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent); pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application)); startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION); } else { startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT); } } void processWallpaper(Intent intent) { startActivityForResult(intent, REQUEST_PICK_WALLPAPER); } FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX, int cellY) { final FolderInfo folderInfo = new FolderInfo(); folderInfo.title = getText(R.string.folder_name); // Update the model LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY, false); sFolders.put(folderInfo.id, folderInfo); // Create the view FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache); mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1, isWorkspaceLocked()); return newFolder; } void removeFolder(FolderInfo folder) { sFolders.remove(folder.id); } private void startWallpaper() { showWorkspace(true); final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER); // final Intent pickWallpaper = new Intent(Launcher.ACTION_SET_WALLPAPER); Intent chooser = Intent.createChooser(pickWallpaper, getText(R.string.chooser_wallpaper)); // NOTE: Adds a configure option to the chooser if the wallpaper supports it // Removed in Eclair MR1 // WallpaperManager wm = (WallpaperManager) // getSystemService(Context.WALLPAPER_SERVICE); // WallpaperInfo wi = wm.getWallpaperInfo(); // if (wi != null && wi.getSettingsActivity() != null) { // LabeledIntent li = new LabeledIntent(getPackageName(), // R.string.configure_wallpaper, 0); // li.setClassName(wi.getPackageName(), wi.getSettingsActivity()); // chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li }); // } startActivityForResult(chooser, REQUEST_PICK_WALLPAPER); overridePendingTransition(R.anim.activity_enter, 0); //改变activity切换时飞入动画为淡入动画 } /** * Registers various content observers. The current implementation registers * only a favorites observer to keep track of the favorites applications. */ private void registerContentObservers() { ContentResolver resolver = getContentResolver(); resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI, true, mWidgetObserver); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_HOME: return true; case KeyEvent.KEYCODE_VOLUME_DOWN: if (doesFileExist(DUMP_STATE_PROPERTY)) { dumpState(); return true; } break; } } else if (event.getAction() == KeyEvent.ACTION_UP) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_HOME: return true; } } return super.dispatchKeyEvent(event); } @Override public void onBackPressed() { Log.d(TAG, "----onBackPressed----"); //�˳�ж��ģ?? if(mAppsCustomizeContent.isUninstallMode() == true){ mAppsCustomizeContent.exitUninstallMode(); return; } if (isAllAppsVisible()) { showWorkspace(true); }else if(isEditState()){ mAppsCustomizeTabHost.setVisibility(View.GONE); showWorkspace(true); } else if (mWorkspace.getOpenFolder() != null) { Folder openFolder = mWorkspace.getOpenFolder(); if (openFolder.isEditingName()) { openFolder.dismissEditingName(); } else { closeFolder(); } } else if (mScreenManager.isShown() == true) { closeScreenManager(-1); } else { mWorkspace.exitWidgetResizeMode(); // Back button is a no-op here, but give at least some feedback for the button press mWorkspace.showOutlinesTemporarily(); } } /** * Re-listen when widgets are reset. */ private void onAppWidgetReset() { if (mAppWidgetHost != null) { mAppWidgetHost.startListening(); } } /** * Launches the intent referred by the clicked shortcut. * * @param v The view representing the clicked shortcut. */ public void onClick(View v) { // Make sure that rogue clicks don't get through while allapps is launching, or after the // view has detached (it's possible for this to happen if the view is removed mid touch). Log.d(TAG, "onClick------v.id = " + v.getId()); Log.d(TAG, "onClick------v.getTag = " + v.getTag()); if(wallpaperShow){ wallpaperShow = false; adapter.setCurItem(-1); wallpaer_layout.setVisibility(View.GONE); }else{ if (v.getWindowToken() == null) { return; } if (!mWorkspace.isFinishedSwitchingState()) { return; } Object tag = v.getTag(); if (mState == State. EDIT_STATE) { if (tag instanceof FolderInfo) { if (v instanceof FolderIcon) { FolderIcon fi = (FolderIcon) v; handleFolderClick(fi); } } else if(tag instanceof ShortcutInfo){ } else{ onBackPressed(); } }else if (tag instanceof ShortcutInfo) { // Open shortcut final Intent intent = ((ShortcutInfo) tag).intent; int[] pos = new int[2]; v.getLocationOnScreen(pos); intent.setSourceBounds(new Rect(pos[0], pos[1], pos[0] + v.getWidth(), pos[1] + v.getHeight())); boolean success = startActivitySafely(v, intent, tag); if (success && v instanceof BubbleTextView) { mWaitingForResume = (BubbleTextView) v; mWaitingForResume.setStayPressed(true); } } else if (tag instanceof FolderInfo) { if (v instanceof FolderIcon) { FolderIcon fi = (FolderIcon) v; handleFolderClick(fi); } } else if (v == mAllAppsButton) { if (isAllAppsVisible()) { showWorkspace(true); } else { onClickAllAppsButton(v); } } } } public boolean onTouch(View v, MotionEvent event) { // this is an intercepted event being forwarded from mWorkspace; // clicking anywhere on the workspace causes the customization drawer to slide down Log.d(TAG, "----onTouch-----"); showWorkspace(true); return false; } /** * Event handler for the search button * * @param v The view that was clicked. */ public void onClickSearchButton(View v) { v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); onSearchRequested(); } /** * Event handler for the voice button * * @param v The view that was clicked. */ public void onClickVoiceButton(View v) { v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); try { final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName activityName = searchManager.getGlobalSearchActivity(); Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (activityName != null) { intent.setPackage(activityName.getPackageName()); } startActivity(null, intent, "onClickVoiceButton"); } catch (ActivityNotFoundException e) { Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivitySafely(null, intent, "onClickVoiceButton"); } } /** * Event handler for the "grid" button that appears on the home screen, which * enters all apps mode. * * @param v The view that was clicked. */ public void onClickAllAppsButton(View v) { Log.d(TAG, "-----onClickAllAppsButton-----"); showAllApps(true); } public void onTouchDownAllAppsButton(View v) { // Provide the same haptic feedback that the system offers for virtual keys. Log.d(TAG, "-----onTouchDownAllAppsButton-----"); v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); } public void onClickAppMarketButton(View v) { if (mAppMarketIntent != null) { startActivitySafely(v, mAppMarketIntent, "app market"); } else { Log.e(TAG, "Invalid app market intent."); } } /** * 卸载按钮事件监听 * @param v */ public void onClickUninstallButton(View v) { if (mAppsCustomizeContent != null) { mAppsCustomizeContent.onClickUninstallButton(v); } } /** * 商店按钮事件监听 (点击弹出已安装的商店) * @param v */ public void onClickStoreButton(View v){ //Using IntentChooser to open installed market list final Intent pickMarket = new Intent("android.intent.action.MAIN"); pickMarket.addCategory("android.intent.category.APP_MARKET"); Intent market_chooser = Intent.createChooser(pickMarket,getText(R.string.chooser_market)); startActivity(market_chooser); } void startApplicationDetailsActivity(ComponentName componentName) { String packageName = componentName.getPackageName(); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivitySafely(null, intent, "startApplicationDetailsActivity"); } void startApplicationUninstallActivity(ApplicationInfo appInfo) { if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) { // System applications cannot be installed. For now, show a toast explaining that. // We may give them the option of disabling apps this way. int messageId = R.string.uninstall_system_app_text; Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); } else { String packageName = appInfo.componentName.getPackageName(); String className = appInfo.componentName.getClassName(); Log.d("test", "packageName = "+packageName+" className = "+className); Intent intent = new Intent( Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(intent); } } boolean startActivity(View v, Intent intent, Object tag) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { // Only launch using the new animation if the shortcut has not opted out (this is a // private contract between launcher and may be ignored in the future). boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION); if (useLaunchAnimation) { ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); startActivity(intent, opts.toBundle()); } else { startActivity(intent); } return true; } catch (SecurityException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity. " + "tag="+ tag + " intent=" + intent, e); } return false; } boolean startActivitySafely(View v, Intent intent, Object tag) { boolean success = false; try { success = startActivity(v, intent, tag); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e); } return success; } void startActivityForResultSafely(Intent intent, int requestCode) { try { startActivityForResult(intent, requestCode); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity.", e); } } private void handleFolderClick(FolderIcon folderIcon) { final FolderInfo info = folderIcon.getFolderInfo(); Folder openFolder = mWorkspace.getFolderForTag(info); // If the folder info reports that the associated folder is open, then verify that // it is actually opened. There have been a few instances where this gets out of sync. if (info.opened && openFolder == null) { Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: " + info.screen + " (" + info.cellX + ", " + info.cellY + ")"); info.opened = false; } if (!info.opened && !folderIcon.getFolder().isDestroyed()) { // Close any open folder closeFolder(); // Open the requested folder openFolder(folderIcon); } else { // Find the open folder... int folderScreen; if (openFolder != null) { folderScreen = mWorkspace.getPageForView(openFolder); // .. and close it closeFolder(openFolder); if (folderScreen != mWorkspace.getCurrentPage()) { // Close any folder open on the current screen closeFolder(); // Pull the folder onto this screen openFolder(folderIcon); } } } } /** * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView * in the DragLayer in the exact absolute location of the original FolderIcon. */ private void copyFolderIconToImage(FolderIcon fi) { final int width = fi.getMeasuredWidth(); final int height = fi.getMeasuredHeight(); // Lazy load ImageView, Bitmap and Canvas if (mFolderIconImageView == null) { mFolderIconImageView = new ImageView(this); } if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width || mFolderIconBitmap.getHeight() != height) { mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mFolderIconCanvas = new Canvas(mFolderIconBitmap); } DragLayer.LayoutParams lp; if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) { lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams(); } else { lp = new DragLayer.LayoutParams(width, height); } // The layout from which the folder is being opened may be scaled, adjust the starting // view size by this scale factor. float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation); lp.customPosition = true; lp.x = mRectForFolderAnimation.left; lp.y = mRectForFolderAnimation.top; lp.width = (int) (scale * width); lp.height = (int) (scale * height); mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR); fi.draw(mFolderIconCanvas); mFolderIconImageView.setImageBitmap(mFolderIconBitmap); if (fi.getFolder() != null) { mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation()); mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation()); } // Just in case this image view is still in the drag layer from a previous animation, // we remove it and re-add it. if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) { mDragLayer.removeView(mFolderIconImageView); } mDragLayer.addView(mFolderIconImageView, lp); if (fi.getFolder() != null) { fi.getFolder().bringToFront(); } } private void growAndFadeOutFolderIcon(FolderIcon fi) { if (fi == null) return; PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f); PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f); FolderInfo info = (FolderInfo) fi.getTag(); if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { CellLayout cl = (CellLayout) fi.getParent().getParent(); CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams(); cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY); } // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original copyFolderIconToImage(fi); fi.setVisibility(View.INVISIBLE); ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha, scaleX, scaleY); oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration)); oa.start(); } private void shrinkAndFadeInFolderIcon(final FolderIcon fi) { if (fi == null) return; PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f); PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f); final CellLayout cl = (CellLayout) fi.getParent().getParent(); // We remove and re-draw the FolderIcon in-case it has changed mDragLayer.removeView(mFolderIconImageView); copyFolderIconToImage(fi); ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha, scaleX, scaleY); oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration)); oa.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (cl != null) { cl.clearFolderLeaveBehind(); // Remove the ImageView copy of the FolderIcon and make the original visible. mDragLayer.removeView(mFolderIconImageView); fi.setVisibility(View.VISIBLE); } } }); oa.start(); } /** * Opens the user folder described by the specified tag. The opening of the folder * is animated relative to the specified View. If the View is null, no animation * is played. * * @param folderInfo The FolderInfo describing the folder to open. */ public void openFolder(FolderIcon folderIcon) { Folder folder = folderIcon.getFolder(); FolderInfo info = folder.mInfo; info.opened = true; // Just verify that the folder hasn't already been added to the DragLayer. // There was a one-off crash where the folder had a parent already. if (folder.getParent() == null) { mDragLayer.addView(folder); mDragController.addDropTarget((DropTarget) folder); } else { Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" + folder.getParent() + ")."); } folder.animateOpen(); growAndFadeOutFolderIcon(folderIcon); } public void closeFolder() { Folder folder = mWorkspace.getOpenFolder(); if (folder != null) { if (folder.isEditingName()) { folder.dismissEditingName(); } closeFolder(folder); // Dismiss the folder cling // hide cling by xiangss 20130821 // dismissFolderCling(null); } } void closeFolder(Folder folder) { folder.getInfo().opened = false; ViewGroup parent = (ViewGroup) folder.getParent().getParent(); if (parent != null) { FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo); shrinkAndFadeInFolderIcon(fi); } folder.animateClosed(); } public boolean onLongClick(View v) { Log.i(TAG,"----in onLongClick--v-->"+v); if (!isDraggingEnabled()) return false; if (isWorkspaceLocked()) return false; if ((mState != State.WORKSPACE) && (mState !=State.EDIT_STATE)) return false; if (!(v instanceof CellLayout)) { v = (View) v.getParent().getParent(); } resetAddInfo(); CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag(); // This happens when long clicking an item with the dpad/trackball if (longClickCellInfo == null) { return true; } // The hotseat touch handling does not go through Workspace, and we always allow long press // on hotseat items. final View itemUnderLongClick = longClickCellInfo.cell; boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress(); if (allowLongPress && !mDragController.isDragging()) { if (itemUnderLongClick == null) { // User long pressed on empty space mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); // startWallpaper(); //取消长按单独弹出壁纸设置,出现三个菜单项(本地壁纸、添加、屏幕) /* if (launcher_Menudialog == null) { launcher_Menudialog = new AlertDialog.Builder(this).setView(menuView11).show(); } else { launcher_Menudialog.show(); }*/ // if (launcher_Menudialog == null) { // launcher_Menudialog = new MenuDialog(this); // launcher_Menudialog.show(); // } else { // launcher_Menudialog.show(); // } if(!isEditState()){ EditState(); } } else { if (!(itemUnderLongClick instanceof Folder)) { // User long pressed on an item mWorkspace.startDrag(longClickCellInfo); popupDialog(itemUnderLongClick); } } } return true; } /* * modidied by ljianwei; * note:get the corresponding ApplicationInfo from the packagename; * date:2013-8-26; */ private ApplicationInfo findApplicationInfo(String packageName) { Log.d("ljianwei", "packageName = "+packageName); ArrayList<ApplicationInfo> data = mModel.getAllAppList().data; for (ApplicationInfo info: data) { final ComponentName component = info.intent.getComponent(); if (packageName.equals(component.getPackageName())) { return info; } } return null; } /* * add by ljianwei; * note:achieve the popupDialog when long press the shortcut or widget or folder; * date:2013-8-22; */ QuickAction popDialog; public void popupDialog(final View itemUnderLongClick) { ActionItem deleteItem = new ActionItem(DELETE_ITEM, getResources() .getString(R.string.delete_item), getResources().getDrawable( R.drawable.icon_del)); ActionItem uninstallItem = new ActionItem(UNINSTALL_ITEM, getResources().getString(R.string.unistall_item), getResources().getDrawable(R.drawable.icon_uninstall)); ActionItem collectItem = new ActionItem(COLLECT_ITEM, getResources() .getString(R.string.collect_item), getResources().getDrawable( R.drawable.icon_collect)); ActionItem unCollectItem = new ActionItem(UNCOLLECT_ITEM, getResources() .getString(R.string.uncollect_item), getResources().getDrawable( R.drawable.icon_collect)); ActionItem shareItem = new ActionItem(SHARE_TTEM, getResources() .getString(R.string.share_item), getResources().getDrawable( R.drawable.icon_share)); popDialog = new QuickAction(this); popDialog.addPopuItem(deleteItem); if (itemUnderLongClick instanceof BubbleTextView) { ShortcutInfo appInfo = (ShortcutInfo) itemUnderLongClick.getTag(); Log.d("ljianwei", "appInfo = "+appInfo); Log.d("ljianwei", " appInfo.intent = "+ appInfo.intent); ApplicationInfo info = findApplicationInfo(appInfo.getPackageName()); Log.d("ljianwei", " info = "+ info); if (info != null) { if ((info.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) { } else { popDialog.addPopuItem(uninstallItem); } boolean collected = false; for (int i = 0; i < ToolbarUtilities.favoriateList.size(); i++) { if (appInfo.getPackageName().equals( ToolbarUtilities.favoriateList.get(i))) { collected = true; break; } } if (collected) { popDialog.addPopuItem(unCollectItem); } else { popDialog.addPopuItem(collectItem); } popDialog.addPopuItem(shareItem); } } else if (itemUnderLongClick instanceof FolderIcon) { } else if (itemUnderLongClick instanceof AppWidgetHostView) { } popDialog.setOnPopuItemClickListener(new QuickAction.OnPopuItemClickListener() { @Override public void onItemClick(QuickAction source, int pos, int actionId) { if (actionId == DELETE_ITEM) { mSearchDropTargetBar.getDeleteDropTarget().deleteItem(mDragController.getDragObject()); mWorkspace.getParentCellLayoutForView( itemUnderLongClick).removeView( itemUnderLongClick); if (itemUnderLongClick instanceof DropTarget) { mDragController .removeDropTarget((DropTarget) itemUnderLongClick); } } else if (actionId == UNINSTALL_ITEM) { ShortcutInfo appInfo = (ShortcutInfo) itemUnderLongClick .getTag(); ComponentName componentName = appInfo.intent .getComponent(); String packageName = componentName.getPackageName(); String className = componentName.getClassName(); Intent intent = new Intent(Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(intent); } else if (actionId == SHARE_TTEM) { new CreateWidgetTask().execute(itemUnderLongClick); }else if(actionId == COLLECT_ITEM){ ShortcutInfo appInfo = (ShortcutInfo) itemUnderLongClick .getTag(); ToolbarUtilities.addFavorites(mContext, appInfo.getPackageName()); }else if(actionId == UNCOLLECT_ITEM){ ShortcutInfo appInfo = (ShortcutInfo) itemUnderLongClick .getTag(); ToolbarUtilities.delFavorites(mContext, appInfo.getPackageName()); } popDialog.dismiss(); popDialog = null; } }); popDialog.show(itemUnderLongClick); } /* * 异步任务生成item图片 */ class CreateWidgetTask extends AsyncTask<Object, Void, Boolean> { View itemView; protected Boolean doInBackground(Object... params) { itemView = (View) params[0]; String filePath = ITEM_PATH; File itemFile = new File(filePath); if (itemView != null) { itemView.destroyDrawingCache(); itemView.setDrawingCacheEnabled(true); itemView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); Bitmap bit = itemView.getDrawingCache(); Bitmap bitmap = null; int size; try { bitmap = Bitmap.createBitmap(bit); bit.recycle(); bit = null; itemView.setDrawingCacheEnabled(false); if (itemFile.exists()) { Log.i("ljianwei", "doInBackground------file is exists. delete!"); itemFile.delete(); } saveItemBitmap(bitmap, filePath); } catch (Exception e) { Log.d("ljianwei", "Exception info ========" + e.toString()); return false; } return true; } return false; } protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub super.onPostExecute(result); Log.i("ljianwei", "GetDataTask result=" + result); if (result == true) { mHandler.sendEmptyMessage(SHARE_MSG); } } } /** * 保存图片 * * @param bitName * @param mBitmap * @throws IOException */ public void saveItemBitmap(Bitmap mBitmap, String bitName) throws IOException { // File f = new File("/data/data/launcherTemp/" + bitName + ".png"); File f = new File(bitName); Log.d("ljianwei", "f.getParentFile() = "+f.getParentFile().getAbsolutePath()); if(!f.getParentFile().exists()){ f.getParentFile().mkdirs(); } f.createNewFile(); FileOutputStream fOut = null; try { fOut = new FileOutputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut); try { fOut.flush(); } catch (IOException e) { e.printStackTrace(); } try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } mBitmap.recycle(); mBitmap = null; } public void disPopupDialog(){ if(popDialog!=null){ popDialog.dismiss(); popDialog = null; } } public void EditState(){ hideAllOverlayWindow(); showEditAllAppWidget(true); } //display the wallpaper layout public void ShowWallpaper(){ curWallpaperIndex = mSharedPrefs.getInt(ConstantUtil.CURRENT_WALLPAPER_ITEM, 0); /*adapter.setCurItem(curWallpaperIndex);*/ wallpaer_layout.setVisibility(View.VISIBLE); wallpaperShow = true; } private AppSortModeDialog appSortDialog; public void showSortDialog(){ appSortDialog = new AppSortModeDialog(this); appSortDialog.show(); } boolean isHotseatLayout(View layout) { // hide hotseat by xiangss 20130805 return false; // return mHotseat != null && layout != null && // (layout instanceof CellLayout) && (layout == mHotseat.getLayout()); } Hotseat getHotseat() { return mHotseat; } AppsWidgetCustomizeTabHost getEditAppsWidgetCustomizeTabHost(){ return mAppsEditCustomizeTabHost; } SearchDropTargetBar getSearchBar() { return mSearchDropTargetBar; } /** * Returns the CellLayout of the specified container at the specified screen. */ CellLayout getCellLayout(long container, int screen) { if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (mHotseat != null) { return mHotseat.getLayout(); } else { return null; } } else { return (CellLayout) mWorkspace.getChildAt(screen); } } Workspace getWorkspace() { return mWorkspace; } // Now a part of LauncherModel.Callbacks. Used to reorder loading steps. public boolean isAllAppsVisible() { return (mState == State.APPS_CUSTOMIZE) || (mOnResumeState == State.APPS_CUSTOMIZE); } public boolean isAllAppsButtonRank(int rank) { // hide hotseat by xiangss 20130805 return false; // return mHotseat.isAllAppsButtonRank(rank); } // is Edit state add by leixp 2013-07-29 public static boolean isEditState(){ return (mState == State.EDIT_STATE); } /** * Helper method for the cameraZoomIn/cameraZoomOut animations * @param view The view being animated * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE) * @param scaleFactor The scale factor used for the zoom */ private void setPivotsForZoom(View view, float scaleFactor) { view.setPivotX(view.getWidth() / 2.0f); view.setPivotY(view.getHeight() / 2.0f); } void disableWallpaperIfInAllApps() { // Only disable it if we are in all apps if (isAllAppsVisible()) { if (mAppsCustomizeTabHost != null && !mAppsCustomizeTabHost.isTransitioning()) { //need show wallpaper xiangss 20130821 // updateWallpaperVisibility(false); updateWallpaperVisibility(true); } } if(isEditState()){ if(mAppsEditCustomizeTabHost != null && !mAppsEditCustomizeTabHost.isTransitioning()){ updateWallpaperVisibility(true); } } } /* * 是否设置壁纸可见,壁纸可见的条件之一是窗口属性中的WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER位设置为1 */ void updateWallpaperVisibility(boolean visible) { int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0; int curflags = getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER; if (wpflags != curflags) { getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER); } } private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) { if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace); } } private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) { if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace); } // Update the workspace transition step as well dispatchOnLauncherTransitionStep(v, 0f); } private void dispatchOnLauncherTransitionStep(View v, float t) { if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionStep(this, t); } } private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) { if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace); } // Update the workspace transition step as well dispatchOnLauncherTransitionStep(v, 1f); } /** * Things to test when changing the following seven functions. * - Home from workspace * - from center screen * - from other screens * - Home from all apps * - from center screen * - from other screens * - Back from all apps * - from center screen * - from other screens * - Launch app from workspace and quit * - with back * - with home * - Launch app from all apps and quit * - with back * - with home * - Go to a screen that's not the default, then all * apps, and launch and app, and go back * - with back * -with home * - On workspace, long press power and go back * - with back * - with home * - On all apps, long press power and go back * - with back * - with home * - On workspace, power off * - On all apps, power off * - Launch an app and turn off the screen while in that app * - Go back with home key * - Go back with back key TODO: make this not go to workspace * - From all apps * - From workspace * - Enter and exit car mode (becuase it causes an extra configuration changed) * - From all apps * - From the center workspace * - From another workspace */ /** * Zoom the camera out from the workspace to reveal 'toView'. * Assumes that the view to show is anchored at either the very top or very bottom * of the screen. */ private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) { if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } final Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime); final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime); final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mWorkspace; final AppsCustomizeTabHost toView = mAppsCustomizeTabHost; final int startDelay = res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger); setPivotsForZoom(toView, scale); // Shrink workspaces away if going to AppsCustomize from workspace Animator workspaceAnim = mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated); if (animated) { toView.setScaleX(scale); toView.setScaleY(scale); final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView); scaleAnim. scaleX(1f).scaleY(1f). setDuration(duration). setInterpolator(new Workspace.ZoomOutInterpolator()); toView.setVisibility(View.VISIBLE); toView.setAlpha(0f); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(toView, "alpha", 0f, 1f) .setDuration(fadeDuration); alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { if (animation == null) { throw new RuntimeException("animation is null"); } float t = (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(fromView, t); dispatchOnLauncherTransitionStep(toView, t); } }); // toView should appear right at the end of the workspace shrink // animation mStateAnimation = LauncherAnimUtils.createAnimatorSet(); mStateAnimation.play(scaleAnim).after(startDelay); mStateAnimation.play(alphaAnim).after(startDelay); mStateAnimation.addListener(new AnimatorListenerAdapter() { boolean animationCancelled = false; @Override public void onAnimationStart(Animator animation) { updateWallpaperVisibility(true); // Prepare the position toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); } @Override public void onAnimationEnd(Animator animation) { dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); if (mWorkspace != null && !springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); } //need show wallpaper xiangss 20130821 // if (!animationCancelled) { // updateWallpaperVisibility(false); // } // Hide the search bar if (mSearchDropTargetBar != null) { mSearchDropTargetBar.hideSearchBar(false); } } @Override public void onAnimationCancel(Animator animation) { animationCancelled = true; } }); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } boolean delayAnim = false; final ViewTreeObserver observer; dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); // If any of the objects being animated haven't been measured/laid out // yet, delay the animation until we get a layout pass if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) || (mWorkspace.getMeasuredWidth() == 0) || (toView.getMeasuredWidth() == 0)) { observer = mWorkspace.getViewTreeObserver(); delayAnim = true; } else { observer = null; } if(observer == null){ Log.d(TAG, "showAppsCustomizeHelper---observer is null!"); }else{ Log.d(TAG, "showAppsCustomizeHelper---observer.isAlive() = " + observer.isAlive()); } final AnimatorSet stateAnimation = mStateAnimation; final Runnable startAnimRunnable = new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; setPivotsForZoom(toView, scale); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); toView.post(new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; mStateAnimation.start(); } }); } }; if (delayAnim) { final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() { public void onGlobalLayout() { toView.post(startAnimRunnable); if(observer.isAlive() == true){ observer.removeOnGlobalLayoutListener(this); } } }; if(observer.isAlive() == true){ observer.addOnGlobalLayoutListener(delayedStart); } } else { startAnimRunnable.run(); } } else { toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setScaleX(1.0f); toView.setScaleY(1.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); // Hide the search bar if (mSearchDropTargetBar != null) { mSearchDropTargetBar.hideSearchBar(false); } } dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); //need show wallpaper xiangss 20130821 // updateWallpaperVisibility(false); } } /** * add by leixp 2013--7-29 * Things to test when changing the following one functions. * - Home from Edit State * - from center screen * - from other screens * * - On workspace, power off * - On Edit State, power off * - Launch an app and turn off the screen while in that app * - Go back with home key * - Go back with back key TODO: make this not go to workspace * - From Edit State * - From workspace * - Enter and exit car mode (becuase it causes an extra configuration changed) * - From Edit State * - From the center workspace * - From another workspace */ /** * Zoom the camera out from the workspace to reveal 'toView'. * Assumes that the view to show is anchored at either the very top or very bottom * of the screen. */ private void showAppsEditCustomizeHelper(final boolean animated, final boolean springLoaded){ if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } final Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime); final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime); final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final AppsWidgetCustomizeTabHost toView = mAppsEditCustomizeTabHost; final int startDelay = res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger); setPivotsForZoom(toView, scale); // Shrink workspaces away if going to AppsCustomize from workspace Animator workspaceAnim = mWorkspace.getChangeStateAnimation(Workspace.State.EDIT, animated); // hide hotseat by xiangss 20130805 // hideHotseat(animated); hideDockDivider(); mWorkspace.hideScrollingIndicator(true); mWorkspace.showOutlines(); mWorkspace.showBackagroundCell(animated); if (animated) { toView.setScaleX(scale); toView.setScaleY(scale); final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView); scaleAnim. scaleX(1f).scaleY(1f). setDuration(duration). setInterpolator(new Workspace.ZoomOutInterpolator()); toView.setVisibility(View.VISIBLE); toView.setAlpha(0f); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(toView, "alpha", 0f, 1f) .setDuration(fadeDuration); alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { if (animation == null) { throw new RuntimeException("animation is null"); } float t = (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(toView, t); } }); // toView should appear right at the end of the workspace shrink // animation mStateAnimation = LauncherAnimUtils.createAnimatorSet(); mStateAnimation.play(scaleAnim).after(startDelay); mStateAnimation.play(alphaAnim).after(startDelay); mStateAnimation.addListener(new AnimatorListenerAdapter() { boolean animationCancelled = false; @Override public void onAnimationStart(Animator animation) { updateWallpaperVisibility(true); // Prepare the position toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); } @Override public void onAnimationEnd(Animator animation) { // dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); //if (mWorkspace != null && !springLoaded && !LauncherApplication.isScreenLarge()) { if (mWorkspace != null && !springLoaded ) { // Hide the workspace scrollbar // mWorkspace.hideScrollingIndicator(true); hideDockDivider(); mWorkspace.showOutlines(); mWorkspace.showOutlinesTemporarily(); } if (!animationCancelled) { updateWallpaperVisibility(true); } // Hide the search bar if (mSearchDropTargetBar != null) { mSearchDropTargetBar.hideSearchBar(true); } if( mSearchDropTargetBar != null){ mSearchDropTargetBar.showEditHelpInfo(true); } } @Override public void onAnimationCancel(Animator animation) { animationCancelled = true; } }); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } boolean delayAnim = false; final ViewTreeObserver observer; // dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); // If any of the objects being animated haven't been measured/laid out // yet, delay the animation until we get a layout pass if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) || (mWorkspace.getMeasuredWidth() == 0) || (toView.getMeasuredWidth() == 0)) { observer = mWorkspace.getViewTreeObserver(); delayAnim = true; } else { observer = null; } final AnimatorSet stateAnimation = mStateAnimation; final Runnable startAnimRunnable = new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; setPivotsForZoom(toView, scale); // dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); toView.post(new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; mStateAnimation.start(); } }); } }; if (delayAnim) { final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() { public void onGlobalLayout() { toView.post(startAnimRunnable); observer.removeOnGlobalLayoutListener(this); } }; observer.addOnGlobalLayoutListener(delayedStart); } else { startAnimRunnable.run(); } } else { toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setScaleX(1.0f); toView.setScaleY(1.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); // Hide the search bar if (mSearchDropTargetBar != null) { mSearchDropTargetBar.hideSearchBar(false); } if( mSearchDropTargetBar != null){ mSearchDropTargetBar.showEditHelpInfo(false); } } // dispatchOnLauncherTransitionPrepare(fromView, animated, false); // dispatchOnLauncherTransitionStart(fromView, animated, false); // dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); updateWallpaperVisibility(true); } } /** * Zoom the camera back into the workspace, hiding 'fromView'. * This is the opposite of showAppsCustomizeHelper. * @param animated If true, the transition will be animated. */ private void hideAppsCustomizeHelper(State toState, final boolean animated, final boolean springLoaded, final Runnable onCompleteRunnable) { if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime); final int fadeOutDuration = res.getInteger(R.integer.config_appsCustomizeFadeOutTime); final float scaleFactor = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mAppsCustomizeTabHost; final View toView = mWorkspace; Animator workspaceAnim = null; if (toState == State.WORKSPACE) { int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger); workspaceAnim = mWorkspace.getChangeStateAnimation( Workspace.State.NORMAL, animated, stagger); } else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) { workspaceAnim = mWorkspace.getChangeStateAnimation( Workspace.State.SPRING_LOADED, animated); } setPivotsForZoom(fromView, scaleFactor); updateWallpaperVisibility(true); // hide hotseat by xiangss 20130805 // showHotseat(animated); if (animated) { final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(fromView); scaleAnim. scaleX(scaleFactor).scaleY(scaleFactor). setDuration(duration). setInterpolator(new Workspace.ZoomInInterpolator()); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(fromView, "alpha", 1f, 0f) .setDuration(fadeOutDuration); alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator()); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = 1f - (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(fromView, t); dispatchOnLauncherTransitionStep(toView, t); } }); mStateAnimation = LauncherAnimUtils.createAnimatorSet(); dispatchOnLauncherTransitionPrepare(fromView, animated, true); dispatchOnLauncherTransitionPrepare(toView, animated, true); mAppsCustomizeContent.pauseScrolling(); mStateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { updateWallpaperVisibility(true); fromView.setVisibility(View.GONE); dispatchOnLauncherTransitionEnd(fromView, animated, true); dispatchOnLauncherTransitionEnd(toView, animated, true); if (mWorkspace != null) { mWorkspace.hideScrollingIndicator(false); } if (onCompleteRunnable != null) { onCompleteRunnable.run(); } mAppsCustomizeContent.updateCurrentPageScroll(); mAppsCustomizeContent.resumeScrolling(); } }); mStateAnimation.playTogether(scaleAnim, alphaAnim); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } dispatchOnLauncherTransitionStart(fromView, animated, true); dispatchOnLauncherTransitionStart(toView, animated, true); final Animator stateAnimation = mStateAnimation; mWorkspace.post(new Runnable() { public void run() { if (stateAnimation != mStateAnimation) return; mStateAnimation.start(); } }); } else { fromView.setVisibility(View.GONE); dispatchOnLauncherTransitionPrepare(fromView, animated, true); dispatchOnLauncherTransitionStart(fromView, animated, true); dispatchOnLauncherTransitionEnd(fromView, animated, true); dispatchOnLauncherTransitionPrepare(toView, animated, true); dispatchOnLauncherTransitionStart(toView, animated, true); dispatchOnLauncherTransitionEnd(toView, animated, true); mWorkspace.hideScrollingIndicator(false); } } /** * add by leixp 2013-07-29 * Zoom the camera back into the workspace, hiding 'fromView'. * This is the opposite of showAppsEditCustomizeHelper. * @param animated If true, the transition will be animated. */ private void hideAppsEditCustomizeHelper(State toState, final boolean animated, final boolean springLoaded, final Runnable onCompleteRunnable) { if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime); final int fadeOutDuration = res.getInteger(R.integer.config_appsCustomizeFadeOutTime); final float scaleFactor = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mAppsEditCustomizeTabHost; final View toView = mWorkspace; Animator workspaceAnim = null; if (toState == State.WORKSPACE) { int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger); workspaceAnim = mWorkspace.getChangeStateAnimation( Workspace.State.NORMAL, animated, stagger); } else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) { workspaceAnim = mWorkspace.getChangeStateAnimation( Workspace.State.SPRING_LOADED, animated); } setPivotsForZoom(fromView, scaleFactor); updateWallpaperVisibility(true); mWorkspace.hideBackagroundCell(animated); //mWorkspace.setBackgroundColor(getResources().getColor(android.R.color.transparent)); // hide hotseat by xiangss 20130805 // showHotseat(animated); showDockDivider(animated); if (animated) { final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(fromView); scaleAnim. scaleX(scaleFactor).scaleY(scaleFactor). setDuration(duration). setInterpolator(new Workspace.ZoomInInterpolator()); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(fromView, "alpha", 1f, 0f) .setDuration(fadeOutDuration); alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator()); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = 1f - (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(fromView, t); dispatchOnLauncherTransitionStep(toView, t); } }); mStateAnimation = LauncherAnimUtils.createAnimatorSet(); dispatchOnLauncherTransitionPrepare(fromView, animated, true); dispatchOnLauncherTransitionPrepare(toView, animated, true); mAppsEditCustomizeContent.pauseScrolling(); mStateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { updateWallpaperVisibility(true); fromView.setVisibility(View.GONE); dispatchOnLauncherTransitionEnd(fromView, animated, true); dispatchOnLauncherTransitionEnd(toView, animated, true); if (mWorkspace != null) { mWorkspace.hideScrollingIndicator(false); } if (onCompleteRunnable != null) { onCompleteRunnable.run(); } mAppsEditCustomizeContent.updateCurrentPageScroll(); mAppsEditCustomizeContent.resumeScrolling(); } }); mStateAnimation.playTogether(scaleAnim, alphaAnim); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } dispatchOnLauncherTransitionStart(fromView, animated, true); dispatchOnLauncherTransitionStart(toView, animated, true); final Animator stateAnimation = mStateAnimation; mWorkspace.post(new Runnable() { public void run() { if (stateAnimation != mStateAnimation) return; mStateAnimation.start(); } }); } else { fromView.setVisibility(View.GONE); dispatchOnLauncherTransitionPrepare(fromView, animated, true); dispatchOnLauncherTransitionStart(fromView, animated, true); dispatchOnLauncherTransitionEnd(fromView, animated, true); dispatchOnLauncherTransitionPrepare(toView, animated, true); dispatchOnLauncherTransitionStart(toView, animated, true); dispatchOnLauncherTransitionEnd(toView, animated, true); mWorkspace.hideScrollingIndicator(false); } } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) { mAppsCustomizeTabHost.onTrimMemory(); } if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) { mAppsEditCustomizeTabHost.onTrimMemory(); } } @Override public void onWindowFocusChanged(boolean hasFocus) { if (!hasFocus) { // When another window occludes launcher (like the notification shade, or recents), // ensure that we enable the wallpaper flag so that transitions are done correctly. updateWallpaperVisibility(true); } else { // When launcher has focus again, disable the wallpaper if we are in AllApps mWorkspace.postDelayed(new Runnable() { @Override public void run() { disableWallpaperIfInAllApps(); } }, 500); } } void showWorkspace(boolean animated) { showWorkspace(animated, null); } void showWorkspace(boolean animated, Runnable onCompleteRunnable) { if (mState != State.WORKSPACE) { boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED); mWorkspace.setVisibility(View.VISIBLE); if(isAllAppsVisible()||mState == State.APPS_CUSTOMIZE_SPRING_LOADED){ hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable); } // hide Edit state if(isEditState()){ hideAppsEditCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable); } // Show the search bar (only animate if we were showing the drop target bar in spring // loaded mode) if (mSearchDropTargetBar != null) { mSearchDropTargetBar.showSearchBar(true); mSearchDropTargetBar.hideEditHelpInfo(true); } // We only need to animate in the dock divider if we're going from spring loaded mode showDockDivider(animated && wasInSpringLoadedMode); // Set focus to the AppsCustomize button if (mAllAppsButton != null) { mAllAppsButton.requestFocus(); } } mWorkspace.flashScrollingIndicator(animated); // Change the state *after* we've called all the transition code mState = State.WORKSPACE; // Resume the auto-advance of widgets mUserPresent = true; updateRunning(); //show wallpaper shortcut curtain.setViewVisible(true); lampCordView.setViewVisible(true); // Send an accessibility event to announce the context change getWindow().getDecorView() .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } void showAllApps(boolean animated) { if (mState != State.WORKSPACE) return; disPopupDialog(); showAppsCustomizeHelper(animated, false); mAppsCustomizeTabHost.requestFocus(); // Change the state *after* we've called all the transition code mState = State.APPS_CUSTOMIZE; // Pause the auto-advance of widgets until we are out of AllApps mUserPresent = false; updateRunning(); closeFolder(); //close wallpaper shortcut curtain.setViewVisible(false); lampCordView.setViewVisible(false); // Send an accessibility event to announce the context change getWindow().getDecorView() .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } /* * add by leixp 2013-07-29 * Enter into Edit state */ void showEditAllAppWidget(boolean animated) { if (mState != State.WORKSPACE) return; showAppsEditCustomizeHelper(animated,false); mAppsEditCustomizeTabHost.requestFocus(); // Change the state *after* we've called all the transition code mState = State.EDIT_STATE; // Pause the auto-advance of widgets until we are out of AllApps mUserPresent = false; updateRunning(); closeFolder(); // Send an accessibility event to announce the context change getWindow().getDecorView() .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } void enterSpringLoadedDragMode() { if (isAllAppsVisible()) { hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null); hideDockDivider(); mState = State.APPS_CUSTOMIZE_SPRING_LOADED; } } void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay, final Runnable onCompleteRunnable) { if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return; mHandler.postDelayed(new Runnable() { @Override public void run() { if (successfulDrop) { // Before we show workspace, hide all apps again because // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should // clean up our state transition functions mAppsCustomizeTabHost.setVisibility(View.GONE); showWorkspace(true, onCompleteRunnable); } else { exitSpringLoadedDragMode(); } } }, (extendedDelay ? EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT : EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT)); } void exitSpringLoadedDragMode() { if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) { final boolean animated = true; final boolean springLoaded = true; showAppsCustomizeHelper(animated, springLoaded); mState = State.APPS_CUSTOMIZE; } // Otherwise, we are not in spring loaded mode, so don't do anything. } void hideDockDivider() { /* //hide divider by xiangss 201308014 // modified by leixp 2013-07-29 mDockDivider.setVisibility(View.INVISIBLE); if (mQsbDivider != null && mDockDivider != null) { mQsbDivider.setVisibility(View.INVISIBLE); mDockDivider.setVisibility(View.INVISIBLE); } */ } void showDockDivider(boolean animated) { /* //hide divider by xiangss 201308014 // modified by leixp 2013-07-29 mDockDivider.setVisibility(View.VISIBLE); if (mQsbDivider != null && mDockDivider != null) { mQsbDivider.setVisibility(View.VISIBLE); mDockDivider.setVisibility(View.VISIBLE); if (mDividerAnimator != null) { mDividerAnimator.cancel(); mQsbDivider.setAlpha(1f); mDockDivider.setAlpha(1f); mDividerAnimator = null; } if (animated) { mDividerAnimator = LauncherAnimUtils.createAnimatorSet(); mDividerAnimator.playTogether(LauncherAnimUtils.ofFloat(mQsbDivider, "alpha", 1f), LauncherAnimUtils.ofFloat(mDockDivider, "alpha", 1f)); int duration = 0; if (mSearchDropTargetBar != null) { duration = mSearchDropTargetBar.getTransitionInDuration(); } mDividerAnimator.setDuration(duration); mDividerAnimator.start(); } } */ } void lockAllApps() { // TODO } void unlockAllApps() { // TODO } // hide hotseat by xiangss 20130805 /** * Shows the hotseat area. */ /* void showHotseat(boolean animated) { // modified by leixp 2013-07-29 // if (!LauncherApplication.isScreenLarge()) { if (animated) { if (mHotseat.getAlpha() != 1f) { int duration = 0; if (mSearchDropTargetBar != null) { duration = mSearchDropTargetBar.getTransitionInDuration(); } mHotseat.animate().alpha(1f).setDuration(duration); mHotseat.setVisibility(View.VISIBLE); } } else { mHotseat.setAlpha(1f); mHotseat.setVisibility(View.VISIBLE); } // } }*/ // hide hotseat by xiangss 20130805 /** * Hides the hotseat area. */ /*void hideHotseat(boolean animated) { // modified by leixp 2013-07-29 // if (!LauncherApplication.isScreenLarge()) { if (animated) { if (mHotseat.getAlpha() != 0f) { int duration = 0; if (mSearchDropTargetBar != null) { duration = mSearchDropTargetBar.getTransitionOutDuration(); } mHotseat.animate().alpha(0f).setDuration(duration); } } else { mHotseat.setAlpha(0f); } // } }*/ /** * Add an item from all apps or customize onto the given workspace screen. * If layout is null, add to the current screen. */ void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) { if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) { showOutOfSpaceMessage(isHotseatLayout(layout)); } } /** Maps the current orientation to an index for referencing orientation correct global icons */ private int getCurrentOrientationIndexForGlobalIcons() { // default - 0, landscape - 1 switch (getResources().getConfiguration().orientation) { case Configuration.ORIENTATION_LANDSCAPE: return 1; default: return 0; } } private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) { try { PackageManager packageManager = getPackageManager(); // Look for the toolbar icon specified in the activity meta-data Bundle metaData = packageManager.getActivityInfo( activityName, PackageManager.GET_META_DATA).metaData; if (metaData != null) { int iconResId = metaData.getInt(resourceName); if (iconResId != 0) { Resources res = packageManager.getResourcesForActivity(activityName); return res.getDrawable(iconResId); } } } catch (NameNotFoundException e) { // This can happen if the activity defines an invalid drawable Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() + " not found", e); } catch (Resources.NotFoundException nfe) { // This can happen if the activity defines an invalid drawable Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(), nfe); } return null; } // if successful in getting icon, return it; otherwise, set button to use default drawable private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity( int buttonId, ComponentName activityName, int fallbackDrawableId, String toolbarResourceName) { Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName); Resources r = getResources(); int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width); int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height); TextView button = (TextView) findViewById(buttonId); // If we were unable to find the icon via the meta-data, use a generic one if (toolbarIcon == null) { toolbarIcon = r.getDrawable(fallbackDrawableId); toolbarIcon.setBounds(0, 0, w, h); if (button != null) { button.setCompoundDrawables(toolbarIcon, null, null, null); } return null; } else { toolbarIcon.setBounds(0, 0, w, h); if (button != null) { button.setCompoundDrawables(toolbarIcon, null, null, null); } return toolbarIcon.getConstantState(); } } // if successful in getting icon, return it; otherwise, set button to use default drawable private Drawable.ConstantState updateButtonWithIconFromExternalActivity( int buttonId, ComponentName activityName, int fallbackDrawableId, String toolbarResourceName) { ImageView button = (ImageView) findViewById(buttonId); Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName); if (button != null) { // If we were unable to find the icon via the meta-data, use a // generic one if (toolbarIcon == null) { button.setImageResource(fallbackDrawableId); } else { button.setImageDrawable(toolbarIcon); } } return toolbarIcon != null ? toolbarIcon.getConstantState() : null; } private void updateTextButtonWithDrawable(int buttonId, Drawable d) { TextView button = (TextView) findViewById(buttonId); button.setCompoundDrawables(d, null, null, null); } private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) { ImageView button = (ImageView) findViewById(buttonId); button.setImageDrawable(d.newDrawable(getResources())); } private void invalidatePressedFocusedStates(View container, View button) { if (container instanceof HolographicLinearLayout) { HolographicLinearLayout layout = (HolographicLinearLayout) container; layout.invalidatePressedFocusedStates(); } else if (button instanceof HolographicImageView) { HolographicImageView view = (HolographicImageView) button; view.invalidatePressedFocusedStates(); } } private boolean updateGlobalSearchIcon() { final View searchButtonContainer = findViewById(R.id.search_button_container); final ImageView searchButton = (ImageView) findViewById(R.id.search_button); final View voiceButtonContainer = findViewById(R.id.voice_button_container); final View voiceButton = findViewById(R.id.voice_button); final View voiceButtonProxy = findViewById(R.id.voice_button_proxy); final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName activityName = searchManager.getGlobalSearchActivity(); if (activityName != null) { int coi = getCurrentOrientationIndexForGlobalIcons(); sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo, TOOLBAR_SEARCH_ICON_METADATA_NAME); if (sGlobalSearchIcon[coi] == null) { sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo, TOOLBAR_ICON_METADATA_NAME); } if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE); searchButton.setVisibility(View.VISIBLE); invalidatePressedFocusedStates(searchButtonContainer, searchButton); return true; } else { // We disable both search and voice search when there is no global search provider if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE); if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE); searchButton.setVisibility(View.GONE); voiceButton.setVisibility(View.GONE); if (voiceButtonProxy != null) { voiceButtonProxy.setVisibility(View.GONE); } return false; } } private void updateGlobalSearchIcon(Drawable.ConstantState d) { final View searchButtonContainer = findViewById(R.id.search_button_container); final View searchButton = (ImageView) findViewById(R.id.search_button); updateButtonWithDrawable(R.id.search_button, d); invalidatePressedFocusedStates(searchButtonContainer, searchButton); } private boolean updateVoiceSearchIcon(boolean searchVisible) { final View voiceButtonContainer = findViewById(R.id.voice_button_container); final View voiceButton = findViewById(R.id.voice_button); final View voiceButtonProxy = findViewById(R.id.voice_button_proxy); // We only show/update the voice search icon if the search icon is enabled as well final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity(); ComponentName activityName = null; if (globalSearchActivity != null) { // Check if the global search activity handles voice search Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); intent.setPackage(globalSearchActivity.getPackageName()); activityName = intent.resolveActivity(getPackageManager()); } if (activityName == null) { // Fallback: check if an activity other than the global search activity // resolves this Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); activityName = intent.resolveActivity(getPackageManager()); } if (searchVisible && activityName != null) { int coi = getCurrentOrientationIndexForGlobalIcons(); sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo, TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME); if (sVoiceSearchIcon[coi] == null) { sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo, TOOLBAR_ICON_METADATA_NAME); } if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE); voiceButton.setVisibility(View.VISIBLE); if (voiceButtonProxy != null) { voiceButtonProxy.setVisibility(View.VISIBLE); } invalidatePressedFocusedStates(voiceButtonContainer, voiceButton); return true; } else { if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE); voiceButton.setVisibility(View.GONE); if (voiceButtonProxy != null) { voiceButtonProxy.setVisibility(View.GONE); } return false; } } private void updateVoiceSearchIcon(Drawable.ConstantState d) { final View voiceButtonContainer = findViewById(R.id.voice_button_container); final View voiceButton = findViewById(R.id.voice_button); updateButtonWithDrawable(R.id.voice_button, d); invalidatePressedFocusedStates(voiceButtonContainer, voiceButton); } /** * Sets the app market icon */ private void updateAppMarketIcon() { final View marketButton = findViewById(R.id.market_button); Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET); // Find the app market activity by resolving an intent. // (If multiple app markets are installed, it will return the ResolverActivity.) ComponentName activityName = intent.resolveActivity(getPackageManager()); if (activityName != null) { int coi = getCurrentOrientationIndexForGlobalIcons(); mAppMarketIntent = intent; sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity( R.id.market_button, activityName, R.drawable.ic_launcher_market_holo, TOOLBAR_ICON_METADATA_NAME); marketButton.setVisibility(View.VISIBLE); } else { // We should hide and disable the view so that we don't try and restore the visibility // of it when we swap between drag & normal states from IconDropTarget subclasses. marketButton.setVisibility(View.GONE); marketButton.setEnabled(false); } } private void updateAppMarketIcon(Drawable.ConstantState d) { // Ensure that the new drawable we are creating has the approprate toolbar icon bounds Resources r = getResources(); Drawable marketIconDrawable = d.newDrawable(r); int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width); int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height); marketIconDrawable.setBounds(0, 0, w, h); updateTextButtonWithDrawable(R.id.market_button, marketIconDrawable); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { final boolean result = super.dispatchPopulateAccessibilityEvent(event); final List<CharSequence> text = event.getText(); text.clear(); // Populate event with a fake title based on the current state. if (mState == State.APPS_CUSTOMIZE) { text.add(getString(R.string.all_apps_button_label)); } else { text.add(getString(R.string.all_apps_home_button_label)); } return result; } /** * Receives notifications when system dialogs are to be closed. */ private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { closeSystemDialogs(); } } /** * Receives notifications whenever the appwidgets are reset. */ private class AppWidgetResetObserver extends ContentObserver { public AppWidgetResetObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { onAppWidgetReset(); } } /** * If the activity is currently paused, signal that we need to re-run the loader * in onResume. * * This needs to be called from incoming places where resources might have been loaded * while we are paused. That is becaues the Configuration might be wrong * when we're not running, and if it comes back to what it was when we * were paused, we are not restarted. * * Implementation of the method from LauncherModel.Callbacks. * * @return true if we are currently paused. The caller might be able to * skip some work in that case since we will come back again. */ public boolean setLoadOnResume() { if (mPaused) { Log.i(TAG, "setLoadOnResume"); mOnResumeNeedsLoad = true; return true; } else { return false; } } /** * Implementation of the method from LauncherModel.Callbacks. */ public int getCurrentWorkspaceScreen() { if (mWorkspace != null) { return mWorkspace.getCurrentPage(); } else { return SCREEN_COUNT / 2; } } /** * 切换workspace到指定页 * @param curPage */ public void setCurrentWorkspaceScreen(int curPage) { if (mWorkspace != null) { mWorkspace.setCurrentPage(curPage); } } /** * Refreshes the shortcuts shown on the workspace. * * Implementation of the method from LauncherModel.Callbacks. */ public void startBinding() { final Workspace workspace = mWorkspace; mNewShortcutAnimatePage = -1; mNewShortcutAnimateViews.clear(); mWorkspace.clearDropTargets(); int count = workspace.getChildCount(); for (int i = 0; i < count; i++) { // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate(). final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i); layoutParent.removeAllViewsInLayout(); } mWidgetsToAdvance.clear(); if (mHotseat != null) { mHotseat.resetLayout(); } } /** * Bind the items start-end from the list. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) { setLoadOnResume(); // Get the list of added shortcuts and intersect them with the set of shortcuts here Set<String> newApps = new HashSet<String>(); newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps); Workspace workspace = mWorkspace; for (int i = start; i < end; i++) { final ItemInfo item = shortcuts.get(i); // Short circuit if we are loading dock items for a configuration which has no dock if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT && mHotseat == null) { continue; } switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: ShortcutInfo info = (ShortcutInfo) item; String uri = info.intent.toUri(0).toString(); View shortcut = createShortcut(info); workspace.addInScreen(shortcut, item.container, item.screen, item.cellX, item.cellY, 1, 1, false); boolean animateIconUp = false; synchronized (newApps) { if (newApps.contains(uri)) { animateIconUp = newApps.remove(uri); } } if (animateIconUp) { // Prepare the view to be animated up shortcut.setAlpha(0f); shortcut.setScaleX(0f); shortcut.setScaleY(0f); mNewShortcutAnimatePage = item.screen; if (!mNewShortcutAnimateViews.contains(shortcut)) { mNewShortcutAnimateViews.add(shortcut); } } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()), (FolderInfo) item, mIconCache); workspace.addInScreen(newFolder, item.container, item.screen, item.cellX, item.cellY, 1, 1, false); break; } } workspace.requestLayout(); } /** * Implementation of the method from LauncherModel.Callbacks. */ public void bindFolders(HashMap<Long, FolderInfo> folders) { setLoadOnResume(); sFolders.clear(); sFolders.putAll(folders); } /** * Add the views for a widget to the workspace. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppWidget(LauncherAppWidgetInfo item) { setLoadOnResume(); final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0; if (DEBUG_WIDGETS) { Log.d(TAG, "bindAppWidget: " + item); } final Workspace workspace = mWorkspace; final int appWidgetId = item.appWidgetId; Log.d(TAG, "bindAppWidget------appWidgetId = " + appWidgetId); Log.d(TAG, "bindAppWidget------providerName = " + item.providerName); if(appWidgetId <= 0){ item.localWidgetView = LauncherApplication.getLocalWidgetManager().getLocalWidgetById(appWidgetId); item.localWidgetView.setTag(item); item.localWidgetView.show(); workspace.addInScreen(item.localWidgetView, item.container, item.screen, item.cellX, item.cellY, item.spanX, item.spanY, false); }else{ final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); if (DEBUG_WIDGETS) { Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider); } item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); item.hostView.setTag(item); item.onBindAppWidget(this); workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX, item.cellY, item.spanX, item.spanY, false); addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo); } workspace.requestLayout(); if (DEBUG_WIDGETS) { Log.d(TAG, "bound widget id="+item.appWidgetId+" in " + (SystemClock.uptimeMillis()-start) + "ms"); } } public void onPageBoundSynchronously(int page) { mSynchronouslyBoundPages.add(page); } /** * Callback saying that there aren't any more items to bind. * * Implementation of the method from LauncherModel.Callbacks. */ public void finishBindingItems() { setLoadOnResume(); if (mSavedState != null) { if (!mWorkspace.hasFocus()) { mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus(); } mSavedState = null; } mWorkspace.restoreInstanceStateForRemainingPages(); // If we received the result of any pending adds while the loader was running (e.g. the // widget configuration forced an orientation change), process them now. for (int i = 0; i < sPendingAddList.size(); i++) { completeAdd(sPendingAddList.get(i)); } sPendingAddList.clear(); // Update the market app icon as necessary (the other icons will be managed in response to // package changes in bindSearchablesChanged() // updateAppMarketIcon(); // Animate up any icons as necessary if (mVisible || mWorkspaceLoading) { Runnable newAppsRunnable = new Runnable() { @Override public void run() { runNewAppsAnimation(false); } }; boolean willSnapPage = mNewShortcutAnimatePage > -1 && mNewShortcutAnimatePage != mWorkspace.getCurrentPage(); if (canRunNewAppsAnimation()) { // If the user has not interacted recently, then either snap to the new page to show // the new-apps animation or just run them if they are to appear on the current page if (willSnapPage) { mWorkspace.snapToPage(mNewShortcutAnimatePage, newAppsRunnable); } else { runNewAppsAnimation(false); } } else { // If the user has interacted recently, then just add the items in place if they // are on another page (or just normally if they are added to the current page) runNewAppsAnimation(willSnapPage); } } mWorkspaceLoading = false; } private boolean canRunNewAppsAnimation() { long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime(); return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000); } /** * Runs a new animation that scales up icons that were added while Launcher was in the * background. * * @param immediate whether to run the animation or show the results immediately */ private void runNewAppsAnimation(boolean immediate) { AnimatorSet anim = LauncherAnimUtils.createAnimatorSet(); Collection<Animator> bounceAnims = new ArrayList<Animator>(); // Order these new views spatially so that they animate in order Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() { @Override public int compare(View a, View b) { CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams(); CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams(); int cellCountX = LauncherModel.getCellCountX(); return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX); } }); // Animate each of the views in place (or show them immediately if requested) if (immediate) { for (View v : mNewShortcutAnimateViews) { v.setAlpha(1f); v.setScaleX(1f); v.setScaleY(1f); } } else { for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) { View v = mNewShortcutAnimateViews.get(i); ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v, PropertyValuesHolder.ofFloat("alpha", 1f), PropertyValuesHolder.ofFloat("scaleX", 1f), PropertyValuesHolder.ofFloat("scaleY", 1f)); bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION); bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY); bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator()); bounceAnims.add(bounceAnim); } anim.playTogether(bounceAnims); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (mWorkspace != null) { mWorkspace.postDelayed(mBuildLayersRunnable, 500); } } }); anim.start(); } // Clean up mNewShortcutAnimatePage = -1; mNewShortcutAnimateViews.clear(); new Thread("clearNewAppsThread") { public void run() { mSharedPrefs.edit() .putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1) .putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null) .commit(); } }.start(); } @Override public void bindSearchablesChanged() { boolean searchVisible = updateGlobalSearchIcon(); boolean voiceVisible = updateVoiceSearchIcon(searchVisible); if (mSearchDropTargetBar != null) { mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible); } } /** * Add the icons for all apps. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAllApplications(final ArrayList<ApplicationInfo> apps) { Runnable setAllAppsRunnable = new Runnable() { public void run() { if (mAppsCustomizeContent != null) { mAppsCustomizeContent.setApps(apps); } if(mAppsEditCustomizeContent != null){ mAppsEditCustomizeContent.setApps(apps); } } }; // Remove the progress bar entirely; we could also make it GONE // but better to remove it since we know it's not going to be used View progressBar = mAppsCustomizeTabHost. findViewById(R.id.apps_customize_progress_bar); if (progressBar != null) { ((ViewGroup)progressBar.getParent()).removeView(progressBar); // We just post the call to setApps so the user sees the progress bar // disappear-- otherwise, it just looks like the progress bar froze // which doesn't look great mAppsCustomizeTabHost.post(setAllAppsRunnable); mAppsEditCustomizeTabHost.post(setAllAppsRunnable); } else { // If we did not initialize the spinner in onCreate, then we can directly set the // list of applications without waiting for any progress bars views to be hidden. setAllAppsRunnable.run(); } } /** * A package was installed. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppsAdded(ArrayList<ApplicationInfo> apps) { setLoadOnResume(); if (mAppsCustomizeContent != null) { mAppsCustomizeContent.addApps(apps); } if(mAppsEditCustomizeContent != null){ mAppsEditCustomizeContent.addApps(apps); } } /** * A package was updated. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) { setLoadOnResume(); if (mWorkspace != null) { mWorkspace.updateShortcuts(apps); } if (mAppsCustomizeContent != null) { mAppsCustomizeContent.updateApps(apps); } if(mAppsEditCustomizeContent != null){ mAppsEditCustomizeContent.updateApps(apps); } } /** * A package was uninstalled. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppsRemoved(ArrayList<String> packageNames, boolean permanent) { if (permanent) { mWorkspace.removeItems(packageNames); } if (mAppsCustomizeContent != null) { mAppsCustomizeContent.removeApps(packageNames); } if(mAppsEditCustomizeContent != null){ mAppsEditCustomizeContent.removeApps(packageNames); } // Notify the drag controller mDragController.onAppsRemoved(packageNames, this); } /** * A number of packages were updated. */ public void bindPackagesUpdated() { if (mAppsCustomizeContent != null) { mAppsCustomizeContent.onPackagesUpdated(); } if(mAppsEditCustomizeContent != null){ mAppsEditCustomizeContent.onPackagesUpdated(); } } private int mapConfigurationOriActivityInfoOri(int configOri) { final Display d = getWindowManager().getDefaultDisplay(); int naturalOri = Configuration.ORIENTATION_LANDSCAPE; switch (d.getRotation()) { case Surface.ROTATION_0: case Surface.ROTATION_180: // We are currently in the same basic orientation as the natural orientation naturalOri = configOri; break; case Surface.ROTATION_90: case Surface.ROTATION_270: // We are currently in the other basic orientation to the natural orientation naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE; break; } int[] oriMap = { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE }; // Since the map starts at portrait, we need to offset if this device's natural orientation // is landscape. int indexOffset = 0; if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) { indexOffset = 1; } return oriMap[(d.getRotation() + indexOffset) % 4]; } public boolean isRotationEnabled() { boolean forceEnableRotation = doesFileExist(FORCE_ENABLE_ROTATION_PROPERTY); boolean enableRotation = forceEnableRotation || getResources().getBoolean(R.bool.allow_rotation); return enableRotation; } public void lockScreenOrientation() { if (isRotationEnabled()) { setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources() .getConfiguration().orientation)); } } public void unlockScreenOrientation(boolean immediate) { if (isRotationEnabled()) { if (immediate) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } else { mHandler.postDelayed(new Runnable() { public void run() { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } }, mRestoreScreenOrientationDelay); } } } /* // hide cling by xiangss 20130821 Cling related private boolean isClingsEnabled() { // disable clings when running in a test harness if(ActivityManager.isRunningInTestHarness()) return false; return true; } private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) { final Cling cling = (Cling) findViewById(clingId); if (cling != null) { cling.init(this, positionData); cling.setVisibility(View.VISIBLE); cling.setLayerType(View.LAYER_TYPE_HARDWARE, null); if (animate) { cling.buildLayer(); cling.setAlpha(0f); cling.animate() .alpha(1f) .setInterpolator(new AccelerateInterpolator()) .setDuration(SHOW_CLING_DURATION) .setStartDelay(delay) .start(); } else { cling.setAlpha(1f); } cling.setFocusableInTouchMode(true); cling.post(new Runnable() { public void run() { cling.setFocusable(true); cling.requestFocus(); } }); mHideFromAccessibilityHelper.setImportantForAccessibilityToNo( mDragLayer, clingId == R.id.all_apps_cling); } return cling; } private void dismissCling(final Cling cling, final String flag, int duration) { if (cling != null && cling.getVisibility() == View.VISIBLE) { ObjectAnimator anim = LauncherAnimUtils.ofFloat(cling, "alpha", 0f); anim.setDuration(duration); anim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { cling.setVisibility(View.GONE); cling.cleanup(); // We should update the shared preferences on a background thread new Thread("dismissClingThread") { public void run() { SharedPreferences.Editor editor = mSharedPrefs.edit(); editor.putBoolean(flag, true); editor.commit(); } }.start(); }; }); anim.start(); mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer); } } private void removeCling(int id) { final View cling = findViewById(id); if (cling != null) { final ViewGroup parent = (ViewGroup) cling.getParent(); parent.post(new Runnable() { @Override public void run() { parent.removeView(cling); } }); mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer); } } private boolean skipCustomClingIfNoAccounts() { Cling cling = (Cling) findViewById(R.id.workspace_cling); boolean customCling = cling.getDrawIdentifier().equals("workspace_custom"); if (customCling) { AccountManager am = AccountManager.get(this); Account[] accounts = am.getAccountsByType("com.google"); return accounts.length == 0; } return false; } public void showFirstRunWorkspaceCling() { // Enable the clings only if they have not been dismissed before if (isClingsEnabled() && !mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) && !skipCustomClingIfNoAccounts() ) { // If we're not using the default workspace layout, replace workspace cling // with a custom workspace cling (usually specified in an overlay) // For now, only do this on tablets if (mSharedPrefs.getInt(LauncherProvider.DEFAULT_WORKSPACE_RESOURCE_ID, 0) != 0 && getResources().getBoolean(R.bool.config_useCustomClings)) { // Use a custom cling View cling = findViewById(R.id.workspace_cling); ViewGroup clingParent = (ViewGroup) cling.getParent(); int clingIndex = clingParent.indexOfChild(cling); clingParent.removeViewAt(clingIndex); View customCling = mInflater.inflate(R.layout.custom_workspace_cling, clingParent, false); clingParent.addView(customCling, clingIndex); customCling.setId(R.id.workspace_cling); } initCling(R.id.workspace_cling, null, false, 0); } else { removeCling(R.id.workspace_cling); } } public void showFirstRunAllAppsCling(int[] position) { // Enable the clings only if they have not been dismissed before if (isClingsEnabled() && !mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) { initCling(R.id.all_apps_cling, position, true, 0); } else { removeCling(R.id.all_apps_cling); } } public Cling showFirstRunFoldersCling() { // Enable the clings only if they have not been dismissed before if (isClingsEnabled() && !mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) { return initCling(R.id.folder_cling, null, true, 0); } else { removeCling(R.id.folder_cling); return null; } }*/ public boolean isFolderClingVisible() { Cling cling = (Cling) findViewById(R.id.folder_cling); if (cling != null) { return cling.getVisibility() == View.VISIBLE; } return false; } /* // hide cling by xiangss 20130821 public void dismissWorkspaceCling(View v) { Cling cling = (Cling) findViewById(R.id.workspace_cling); dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION); } public void dismissAllAppsCling(View v) { Cling cling = (Cling) findViewById(R.id.all_apps_cling); dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION); } public void dismissFolderCling(View v) { Cling cling = (Cling) findViewById(R.id.folder_cling); dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION); }*/ /** * Prints out out state for debugging. */ public void dumpState() { Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this); Log.d(TAG, "mSavedState=" + mSavedState); Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading); Log.d(TAG, "mRestoring=" + mRestoring); Log.d(TAG, "mWaitingForResult=" + mWaitingForResult); Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState); Log.d(TAG, "sFolders.size=" + sFolders.size()); mModel.dumpState(); if (mAppsCustomizeContent != null) { mAppsCustomizeContent.dumpState(); } if (mAppsEditCustomizeContent != null) { mAppsEditCustomizeContent.dumpState(); } Log.d(TAG, "END launcher2 dump state"); } @Override public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.println(" "); writer.println("Debug logs: "); for (int i = 0; i < sDumpLogs.size(); i++) { writer.println(" " + sDumpLogs.get(i)); } } public static void dumpDebugLogsToConsole() { Log.d(TAG, ""); Log.d(TAG, "*********************"); Log.d(TAG, "Launcher debug logs: "); for (int i = 0; i < sDumpLogs.size(); i++) { Log.d(TAG, " " + sDumpLogs.get(i)); } Log.d(TAG, "*********************"); Log.d(TAG, ""); } //------------------------ScreenManager---------------------------- /** * 关闭屏幕管理页面 * @param screenIndex 返回到指定workspace页面 */ public void closeScreenManager(int screenIndex) { Log.d(TAG, "------closeScreenManager-----screenIndex = " + screenIndex); if (screenIndex >= 0){ // mWorkspace.setCurrentPage(screenIndex); mWorkspace.snapToPage(screenIndex); } mDragController.removeDropTarget(mScreenManager); int width = mDragLayer.getWidth() / 3; int height = mDragLayer.getHeight() / 3; int count = getCurrentWorkspaceScreen(); int pivotX = count % 3; int pivotY = count / 3; ScaleAnimation closeAnimation = new ScaleAnimation(1.0F, 3.0F, 1.0F, 3.0F, width * pivotX + width / 2, height * pivotY + height / 2); closeAnimation.setDuration(200); mScreenManager.startAnimation(closeAnimation); mScreenManager.setVisibility(View.GONE); mScreenManager.closeScreenManager(); mWorkspace.setVisibility(View.VISIBLE); // hide hotseat by xiangss 20130805 // mHotseat.setVisibility(View.VISIBLE); //显示下拉换壁纸 lampCordView.setViewVisible(true); curtain.setViewVisible(true); // Show the search bar if (mSearchDropTargetBar != null) { mSearchDropTargetBar.showSearchBar(false); } // if (PreferenceUtils.getUserGuidePref(this, "pref_userguide_manage_screen_with_fingers") >= 3) // return; // showUserGuideToast("pref_userguide_manage_screen_with_fingers"); } /** * 判断是否在屏幕管理页 * @return */ public boolean isScreenManagerMode() { boolean isScreenMode = false; if (mScreenManager.getVisibility() == View.VISIBLE){ isScreenMode = true; } Log.d(TAG, "isScreenManagerMode--------isScreenMode = " + isScreenMode); return isScreenMode; } /** * 启动屏幕管理页面 */ public void showScreenManager() { Log.d(TAG, "------showScreenManager-----"); if (this.mWorkspaceLoading){ Log.d(TAG, "showScreenManager---mWorkspaceLoading is ture!"); return; } if(mState != State.WORKSPACE){ Log.d(TAG, "showScreenManager---state is not workspace!"); return; } if(isScreenManagerMode() == true){ Log.d(TAG, "showScreenManager---isScreenManagerMode true!"); return; } //隐藏下拉换壁纸 lampCordView.setViewVisible(false); curtain.setViewVisible(false); // Hide the search bar if (mSearchDropTargetBar != null) { mSearchDropTargetBar.hideSearchBar(false); } // changeToNormalMode(); // mState = State.WORKSPACE; closeFolder(); mScreenManager.showScreenManager(this); mScreenManager.setVisibility(View.VISIBLE); int width = this.mDragLayer.getWidth() / 3; int height = this.mDragLayer.getHeight() / 3; int count = getCurrentWorkspaceScreen(); int pivotX = count % 3; int pivotY = count / 3; ScaleAnimation localScaleAnimation = new ScaleAnimation(2.0F, 1.0F, 2.0F, 1.0F, width * pivotX + width / 2, height * pivotY + height / 2); localScaleAnimation.setDuration(200L); mDragController.addDropTarget(mScreenManager); mScreenManager.startAnimation(localScaleAnimation); mWorkspace.setVisibility(View.GONE); // hide hotseat by xiangss 20130805 // mHotseat.setVisibility(View.GONE); // if (PreferenceUtils.getUserGuidePref(this, // "pref_userguide_set_homescreen") >= 3) // continue; // showUserGuideToast("pref_userguide_set_homescreen"); // if (PreferenceUtils.getUserGuidePref(this, // "pref_userguide_edit_screen_seq") >= 3) // continue; // mHandler.postDelayed(new Runnable() { // public void run() { // if (Launcher.this.mHomeDestroyed){ // //// Launcher.this //// .showUserGuideToast("pref_userguide_edit_screen_seq"); // } // } // }, 3000L); } /** * 判断是否启动开机向导 */ private void firstStartup(){ boolean isFirstStartup = mSharedPrefs.getBoolean(ConstantUtil.FIRST_STARTUP_FLAG, true); Log.d(TAG, "firstStartup------isFirstStartup = " + isFirstStartup); if(isFirstStartup == true){ mSharedPrefs.edit().putBoolean(ConstantUtil.FIRST_STARTUP_FLAG, false).commit(); Intent intent = new Intent(); intent.setClassName("com.tctmobile.guide", "com.tctmobile.guide.StartGuideActivity"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(intent); } catch (android.content.ActivityNotFoundException anf) { Log.e(TAG, "android.content.ActivityNotFoundException"); } catch (Exception e) { Log.e(TAG, e.toString()); } try { Log.d(TAG, "firstStartup----sleep start!"); Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block Log.e(TAG, "launchView----Thread sleep err!!!"); e.printStackTrace(); } Log.d(TAG, "firstStartup----sleep end!"); } Log.d(TAG, "isFirstStartup------end"); } /** * 为了应用匣子和主界面其他弹出框互斥,添加此方法供应用匣子调用 */ public void hideAllOverlayWindow(){ Log.d(TAG, "hideAllOverlayWindow------start"); if(isEditState()){ exitEditStatus(false); } closeMenuDialogAndWallpaper(); Log.d(TAG, "hideAllOverlayWindow------end"); } //返回壁纸是否正在显示 private boolean wallpaperShow(){ return wallpaperShow; } //解决菜单或壁纸和应用匣子的互斥问题 private void closeMenuDialogAndWallpaper(){ Log.d(TAG, "closeMenuDialogAndWallpaper------end"); //如果launcher页面菜单正在显示,将其关闭 if(launcher_Menudialog != null && launcher_Menudialog.isShowing()){ Log.d(TAG, "close------myMenudialog1"); launcher_Menudialog.dismiss(); return; } //如果allApp页面菜单正在显示,将其关闭 if(allapp_Menudialog != null && allapp_Menudialog.isShowing()){ Log.d(TAG, "close------allapp_Menudialog2"); allapp_Menudialog.dismiss(); return; } //如果allApp页面应用排序对话框正在显示,将其关闭 if(appSortDialog != null && appSortDialog.isShowing()){ Log.d(TAG, "close------appSortDialog"); appSortDialog.dismiss(); return; } //如果本地壁纸 正在显示,将其关闭 if(wallpaperShow()){ Log.d(TAG, "close------localwallpaper"); adapter.setCurItem(-1); wallpaer_layout.setVisibility(View.GONE); wallpaperShow = false; return; } } private void exitEditStatus(boolean animated){ showWorkspace(animated); } } interface LauncherTransitionable { View getContent(); void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace); void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace); void onLauncherTransitionStep(Launcher l, float t); void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace); }
apache-2.0
menismu/decody-simple-json-client
sources/SimpleJSONClient/src/com/decody/android/core/json/exceptions/ResourceNotFoundException.java
999
/* * Copyright (C) 2015 Decody Software. * * 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.decody.android.core.json.exceptions; @SuppressWarnings("serial") public class ResourceNotFoundException extends Exception { public ResourceNotFoundException() { super(); } public ResourceNotFoundException(String detailMessage) { super(detailMessage); } public ResourceNotFoundException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } }
apache-2.0
NieDongjia/spring-data-mongodb-master
src/main/java/com/djn/cn/spring/mongodbframework/util/RedisCacheUtil.java
5629
package com.djn.cn.spring.mongodbframework.util; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; /** * * @author NieDongjia * @param <T> */ //@Service public class RedisCacheUtil<T> { @Autowired @Qualifier("jedisTemplate") public RedisTemplate redisTemplate; /** * 缓存基本的对象,Integer、String、实体类等 * * @param key * 缓存的键值 * @param value * 缓存的值 * @return 缓存的对象 */ public <T> ValueOperations<String, T> setCacheObject(String key, T value) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); operation.set(key, value); return operation; } /** * 获得缓存的基本对象。 * * @param key * 缓存键值 * @param operation * @return 缓存键值对应的数据 */ public <T> T getCacheObject( String key/* ,ValueOperations<String,T> operation */) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); return operation.get(key); } /** * 缓存List数据 * * @param key * 缓存的键值 * @param dataList * 待缓存的List数据 * @return 缓存的对象 */ public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList) { ListOperations listOperation = redisTemplate.opsForList(); if (null != dataList) { int size = dataList.size(); for (int i = 0; i < size; i++) { listOperation.rightPush(key, dataList.get(i)); } } return listOperation; } /** * 获得缓存的list对象 * * @param key * 缓存的键值 * @return 缓存键值对应的数据 */ public <T> List<T> getCacheList(String key) { List<T> dataList = new ArrayList<T>(); ListOperations<String, T> listOperation = redisTemplate.opsForList(); Long size = listOperation.size(key); for (int i = 0; i < size; i++) { dataList.add((T) listOperation.leftPop(key)); } return dataList; } /** * 缓存Set * * @param key * 缓存键值 * @param dataSet * 缓存的数据 * @return 缓存数据的对象 */ public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) { BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key); /* * T[] t = (T[]) dataSet.toArray(); setOperation.add(t); */ Iterator<T> it = dataSet.iterator(); while (it.hasNext()) { setOperation.add(it.next()); } return setOperation; } /** * 获得缓存的set * * @param key * @param operation * @return */ public Set<T> getCacheSet( String key/* ,BoundSetOperations<String,T> operation */) { Set<T> dataSet = new HashSet<T>(); BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key); Long size = operation.size(); for (int i = 0; i < size; i++) { dataSet.add(operation.pop()); } return dataSet; } /** * 缓存Map * * @param key * @param dataMap * @return */ public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if (null != dataMap) { for (Map.Entry<String, T> entry : dataMap.entrySet()) { /* * System.out.println("Key = " + entry.getKey() + ", Value = " + * entry.getValue()); */ hashOperations.put(key, entry.getKey(), entry.getValue()); } } return hashOperations; } /** * 获得缓存的Map * * @param key * @param hashOperation * @return */ public <T> Map<String, T> getCacheMap( String key/* ,HashOperations<String,String,T> hashOperation */) { Map<String, T> map = redisTemplate.opsForHash().entries(key); /* Map<String, T> map = hashOperation.entries(key); */ return map; } /** * 缓存Map * * @param key * @param dataMap * @return */ public <T> HashOperations<String, Integer, T> setCacheIntegerMap(String key, Map<Integer, T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if (null != dataMap) { for (Map.Entry<Integer, T> entry : dataMap.entrySet()) { /* * System.out.println("Key = " + entry.getKey() + ", Value = " + * entry.getValue()); */ hashOperations.put(key, entry.getKey(), entry.getValue()); } } return hashOperations; } /** * 获得缓存的Map * * @param key * @param hashOperation * @return */ public <T> Map<Integer, T> getCacheIntegerMap( String key/* ,HashOperations<String,String,T> hashOperation */) { Map<Integer, T> map = redisTemplate.opsForHash().entries(key); /* Map<String, T> map = hashOperation.entries(key); */ return map; } }
apache-2.0
akarnokd/rxjava2-backport
src/test/java/hu/akarnokd/rxjava2/internal/operators/OperatorMulticastTest.java
3809
/** * Copyright 2015 David Karnok and Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package hu.akarnokd.rxjava2.internal.operators; public class OperatorMulticastTest { // FIXME operator multicast not supported // // @Test // public void testMulticast() { // Subject<String, String> source = PublishSubject.create(); // // ConnectableObservable<String> multicasted = new OperatorMulticast<String, String>(source, new PublishSubjectFactory()); // // @SuppressWarnings("unchecked") // Observer<String> observer = mock(Observer.class); // multicasted.subscribe(observer); // // source.onNext("one"); // source.onNext("two"); // // multicasted.connect(); // // source.onNext("three"); // source.onNext("four"); // source.onCompleted(); // // verify(observer, never()).onNext("one"); // verify(observer, never()).onNext("two"); // verify(observer, times(1)).onNext("three"); // verify(observer, times(1)).onNext("four"); // verify(observer, times(1)).onCompleted(); // // } // // @Test // public void testMulticastConnectTwice() { // Subject<String, String> source = PublishSubject.create(); // // ConnectableObservable<String> multicasted = new OperatorMulticast<String, String>(source, new PublishSubjectFactory()); // // @SuppressWarnings("unchecked") // Observer<String> observer = mock(Observer.class); // multicasted.subscribe(observer); // // source.onNext("one"); // // Subscription sub = multicasted.connect(); // Subscription sub2 = multicasted.connect(); // // source.onNext("two"); // source.onCompleted(); // // verify(observer, never()).onNext("one"); // verify(observer, times(1)).onNext("two"); // verify(observer, times(1)).onCompleted(); // // assertEquals(sub, sub2); // // } // // @Test // public void testMulticastDisconnect() { // Subject<String, String> source = PublishSubject.create(); // // ConnectableObservable<String> multicasted = new OperatorMulticast<String, String>(source, new PublishSubjectFactory()); // // @SuppressWarnings("unchecked") // Observer<String> observer = mock(Observer.class); // multicasted.subscribe(observer); // // source.onNext("one"); // // Subscription connection = multicasted.connect(); // source.onNext("two"); // // connection.unsubscribe(); // source.onNext("three"); // // // subscribe again // multicasted.subscribe(observer); // // reconnect // multicasted.connect(); // source.onNext("four"); // source.onCompleted(); // // verify(observer, never()).onNext("one"); // verify(observer, times(1)).onNext("two"); // verify(observer, never()).onNext("three"); // verify(observer, times(1)).onNext("four"); // verify(observer, times(1)).onCompleted(); // // } // // private static final class PublishSubjectFactory implements Func0<Subject<String, String>> { // // @Override // public Subject<String, String> call() { // return PublishSubject.<String> create(); // } // // } }
apache-2.0
lutzfischer/XiSearch
src/main/java/rappsilber/utils/Util.java
44716
/* * Copyright 2016 Lutz Fischer <l.fischer@ed.ac.uk>. * * 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 rappsilber.utils; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.MathContext; import java.net.URL; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.*; import rappsilber.ms.ToleranceUnit; /** * Provides some general static functions needed/ helpful for the rest of the * library/program * * @author Lutz Fischer <l.fischer@ed.ac.uk> */ public class Util { /** * the maximal ratio between two consecutive peeks to be considered part of * the same isotope cluster */ public static double IsotopClusterMaxYRation = 5.5; /** * maximal how many peaks are considered to belong to one isotope cluster */ public static int IsotopClusterMaxPeaks = 7; /** * formats to 6 decimal places */ public static DecimalFormat sixDigits = new DecimalFormat("#,##0.000000"); /** * formats to 5 decimal places */ public static DecimalFormat fiveDigits = new DecimalFormat("#,##0.00000"); /** * formats to 4 decimal places */ public static DecimalFormat fourDigits = new DecimalFormat("#,##0.0000"); /** * formats to 3 decimal places */ public static DecimalFormat threeDigits = new DecimalFormat("#,##0.000"); /** * formats to 2 decimal places */ public static DecimalFormat twoDigits = new DecimalFormat("#,##0.00"); /** * formats to 1 decimal place */ public static DecimalFormat oneDigit = new DecimalFormat("#,##0.0"); // Used for setting the scale of our calculations involving bigdecimals //public static final MathContext mc = new MathContext(6); // Masses of various molecules and such like used by our program /** * mass of a single proton (H+) */ public static final double PROTON_MASS = 1.00727646677; // according to wikipedia /** * what is a difference between C12 and C13 */ public static final double C13_MASS_DIFFERENCE = 1.00335; /** * mass of H2O */ public static final double WATER_MASS = 18.01056027; // Mass of water = 18.01056027 Da /** * mass of NH3 */ public static final double AMMONIA_MASS = 17.02654493; // Mass of ammonia = 17.02654493 Da /** * mass of O */ public static final double OXYGEN_MASS = 15.99491; // mass of fixed mod /** * mass of C */ public static final double CARBON_MASS = 12; // mass of fixed mod public static final double HYDROXO_BS2GD0 = 114.0316808; // Mass of var mod public static final double HYDROXO_BS2GD4 = 118.0563805; // Mass of var mod public static final double OXIDATION_M = 15.99491024; // Mass of Var Mod public static final double NITROGEN_MASS = 14.003074; // Mass of Var Mod public static final double HYDROGEN_MASS = 1.007825035; // Mass of Var Mod public static final double ONE_PPM = 0.000001; public static String[] mannScore(int matched_ions, int total_ions, ToleranceUnit msms_tol, int totalPeaks, double[] min_max) { // need for cumulative score String score_and_p[] = new String[2]; /* Parameter list: * 1. 'matched_ions' = the number of ions that match within the MS2 spectrum * 2. 'total_ions' = the total number of ions that fall within the range of * the masses in the MS2 spectrum * 3. 'msms_tol' = the tolerance unit, used to caluculate the 'p' - the * probability of a random match. */ int n = total_ions; //double double_n = total_ions; int k = matched_ions; //double double_k = matched_ions; // System.out.println("Total peaks = " + totalPeaks); // double p = 0.04"); // System.out.println("-------"); // System.out.println("hits = " + k); // System.out.println("in range = " + n); // System.out.println("total peaks = " + totalPeaks); // System.out.println("min = " + min_max[0]); // System.out.println("max = " + min_max[1]); // System.out.println("-------"); // Using tolerance window double p; if (msms_tol.getUnit() == "ppm") { // parts per million p = (double) (Util.ONE_PPM * msms_tol.getValue()); } else { // we have a dalton unit p = (double) msms_tol.getValue(); } p = p * 2; // old // p = p.multiply( new double(4) ); p = p * totalPeaks; // p = p.divide( new double(100), Util.mc); p = p / (min_max[1] - min_max[0]); // need for Cumulative score score_and_p[1] = String.valueOf(p); // System.out.println("small p value = " + score_and_p[1]); // end use tolerance window double score = 0; // initialize the score //score = score.setScale(6, double.ROUND_HALF_UP); if (k == 0) { // if there are no matching ions the score is 0 // return ""; // need for cumulative score score_and_p[0] = ""; } // end if // .setScale(4, ) /* Probability * ----------- */ // Part 1: (n k) permutations try { // recursive component for probs double permutations = factorial(n); double divisor = factorial(k); divisor = divisor * factorial(n - k); permutations = permutations / divisor; // Part 2: p^k double part2 = (double) Math.pow(p, k); // Part 3: (1-p)^(n-k) double part3 = 1; part3 = part3 - p; part3 = (double) Math.pow(part3, n - k); double probability = (permutations * part2 * part3); // end recursive component if (probability <= 0) { // we do not allow 0 or neagtive probability // return "0"; score_and_p[0] = "0"; } else { // log for score double log_probability = probability; score = (double) (-10d * Math.log10(log_probability)); //score = Math.round(score*100.0d) / 100.0d; // System.out.println( "SCORE = " + score.toString() ); // return score.toString(); score_and_p[0] = String.valueOf(score); } } catch (IllegalArgumentException ie) { String error = "n = " + n + " k = " + k; System.err.println("Problem with factorial calculation: " + error); // return error; score_and_p[0] = error; } //return ""; return score_and_p; }// end method mannScore() private static final double[] factorials = { /* 0 */ 1d /* 1 */ ,1d /* 2 */ ,2d /* 3 */ ,6d /* 4 */ ,24d /* 5 */ ,120d /* 6 */ ,720d /* 7 */ ,5040d /* 8 */ ,40320d /* 9 */ ,362880d /* 10 */ ,3628800d /* 11 */ ,39916800d /* 12 */ ,479001600d /* 13 */ ,6227020800d /* 14 */ ,87178291200d /* 15 */ ,1307674368000d /* 16 */ ,20922789888000d /* 17 */ ,355687428096000d /* 18 */ ,6402373705728000d /* 19 */ ,121645100408832000d /* 20 */ ,2432902008176640000d /* 21 */ ,51090942171709440000d /* 22 */ ,1124000727777607680000d /* 23 */ ,25852016738884976640000d /* 24 */ ,620448401733239439360000d /* 25 */ ,15511210043330985984000000d /* 26 */ ,403291461126605635584000000d /* 27 */ ,10888869450418352160768000000d /* 28 */ ,304888344611713860501504000000d /* 29 */ ,8841761993739701954543616000000d /* 30 */ ,265252859812191058636308480000000d /* 31 */ ,8222838654177922817725562880000000d /* 32 */ ,263130836933693530167218012160000000d /* 33 */ ,8683317618811886495518194401280000000d /* 34 */ ,295232799039604140847618609643520000000d /* 35 */ ,10333147966386144929666651337523200000000d /* 36 */ ,371993326789901217467999448150835200000000d /* 37 */ ,13763753091226345046315979581580902400000000d /* 38 */ ,523022617466601111760007224100074291200000000d /* 39 */ ,20397882081197443358640281739902897356800000000d /* 40 */ ,815915283247897734345611269596115894272000000000d /* 41 */ ,33452526613163807108170062053440751665152000000000d /* 42 */ ,1405006117752879898543142606244511569936384000000000d /* 43 */ ,60415263063373835637355132068513997507264512000000000d /* 44 */ ,2658271574788448768043625811014615890319638528000000000d /* 45 */ ,119622220865480194561963161495657715064383733760000000000d /* 46 */ ,5502622159812088949850305428800254892961651752960000000000d /* 47 */ ,258623241511168180642964355153611979969197632389120000000000d /* 48 */ ,12413915592536072670862289047373375038521486354677760000000000d /* 49 */ ,608281864034267560872252163321295376887552831379210240000000000d /* 50 */ ,30414093201713378043612608166064768844377641568960512000000000000d /* 51 */ ,1551118753287382280224243016469303211063259720016986112000000000000d /* 52 */ ,80658175170943878571660636856403766975289505440883277824000000000000d /* 53 */ ,4274883284060025564298013753389399649690343788366813724672000000000000d /* 54 */ ,230843697339241380472092742683027581083278564571807941132288000000000000d /* 55 */ ,12696403353658275925965100847566516959580321051449436762275840000000000000d /* 56 */ ,710998587804863451854045647463724949736497978881168458687447040000000000000d /* 57 */ ,40526919504877216755680601905432322134980384796226602145184481280000000000000d /* 58 */ ,2350561331282878571829474910515074683828862318181142924420699914240000000000000d /* 59 */ ,138683118545689835737939019720389406345902876772687432540821294940160000000000000d /* 60 */ ,8320987112741390144276341183223364380754172606361245952449277696409600000000000000d /* 61 */ ,507580213877224798800856812176625227226004528988036003099405939480985600000000000000d /* 62 */ ,31469973260387937525653122354950764088012280797258232192163168247821107200000000000000d /* 63 */ ,1982608315404440064116146708361898137544773690227268628106279599612729753600000000000000d /* 64 */ ,126886932185884164103433389335161480802865516174545192198801894375214704230400000000000000d /* 65 */ ,8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000d /* 66 */ ,544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000d /* 67 */ ,36471110918188685288249859096605464427167635314049524593701628500267962436943872000000000000000d /* 68 */ ,2480035542436830599600990418569171581047399201355367672371710738018221445712183296000000000000000d /* 69 */ ,171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000d /* 70 */ ,11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000d /* 71 */ ,850478588567862317521167644239926010288584608120796235886430763388588680378079017697280000000000000000d /* 72 */ ,61234458376886086861524070385274672740778091784697328983823014963978384987221689274204160000000000000000d /* 73 */ ,4470115461512684340891257138125051110076800700282905015819080092370422104067183317016903680000000000000000d /* 74 */ ,330788544151938641225953028221253782145683251820934971170611926835411235700971565459250872320000000000000000d /* 75 */ ,24809140811395398091946477116594033660926243886570122837795894512655842677572867409443815424000000000000000000d /* 76 */ ,1885494701666050254987932260861146558230394535379329335672487982961844043495537923117729972224000000000000000000d /* 77 */ ,145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000d /* 78 */ ,11324281178206297831457521158732046228731749579488251990048962825668835325234200766245086213177344000000000000000000d /* 79 */ ,894618213078297528685144171539831652069808216779571907213868063227837990693501860533361810841010176000000000000000000d /* 80 */ ,71569457046263802294811533723186532165584657342365752577109445058227039255480148842668944867280814080000000000000000000d /* 81 */ ,5797126020747367985879734231578109105412357244731625958745865049716390179693892056256184534249745940480000000000000000000d /* 82 */ ,475364333701284174842138206989404946643813294067993328617160934076743994734899148613007131808479167119360000000000000000000d /* 83 */ ,39455239697206586511897471180120610571436503407643446275224357528369751562996629334879591940103770870906880000000000000000000d /* 84 */ ,3314240134565353266999387579130131288000666286242049487118846032383059131291716864129885722968716753156177920000000000000000000d /* 85 */ ,281710411438055027694947944226061159480056634330574206405101912752560026159795933451040286452340924018275123200000000000000000000d /* 86 */ ,24227095383672732381765523203441259715284870552429381750838764496720162249742450276789464634901319465571660595200000000000000000000d /* 87 */ ,2107757298379527717213600518699389595229783738061356212322972511214654115727593174080683423236414793504734471782400000000000000000000d /* 88 */ ,185482642257398439114796845645546284380220968949399346684421580986889562184028199319100141244804501828416633516851200000000000000000000d /* 89 */ ,16507955160908461081216919262453619309839666236496541854913520707833171034378509739399912570787600662729080382999756800000000000000000000d /* 90 */ ,1485715964481761497309522733620825737885569961284688766942216863704985393094065876545992131370884059645617234469978112000000000000000000000d /* 91 */ ,135200152767840296255166568759495142147586866476906677791741734597153670771559994765685283954750449427751168336768008192000000000000000000000d /* 92 */ ,12438414054641307255475324325873553077577991715875414356840239582938137710983519518443046123837041347353107486982656753664000000000000000000000d /* 93 */ ,1156772507081641574759205162306240436214753229576413535186142281213246807121467315215203289516844845303838996289387078090752000000000000000000000d /* 94 */ ,108736615665674308027365285256786601004186803580182872307497374434045199869417927630229109214583415458560865651202385340530688000000000000000000000d /* 95 */ ,10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000d /* 96 */ ,991677934870949689209571401541893801158183648651267795444376054838492222809091499987689476037000748982075094738965754305639874560000000000000000000000d /* 97 */ ,96192759682482119853328425949563698712343813919172976158104477319333745612481875498805879175589072651261284189679678167647067832320000000000000000000000d /* 98 */ ,9426890448883247745626185743057242473809693764078951663494238777294707070023223798882976159207729119823605850588608460429412647567360000000000000000000000d /* 99 */ ,933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000d /* 100 */ ,93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000d /* 101 */ ,9425947759838359420851623124482936749562312794702543768327889353416977599316221476503087861591808346911623490003549599583369706302603264000000000000000000000000d /* 102 */ ,961446671503512660926865558697259548455355905059659464369444714048531715130254590603314961882364451384985595980362059157503710042865532928000000000000000000000000d /* 103 */ ,99029007164861804075467152545817733490901658221144924830052805546998766658416222832141441073883538492653516385977292093222882134415149891584000000000000000000000000d /* 104 */ ,10299016745145627623848583864765044283053772454999072182325491776887871732475287174542709871683888003235965704141638377695179741979175588724736000000000000000000000000d /* 105 */ ,1081396758240290900504101305800329649720646107774902579144176636573226531909905153326984536526808240339776398934872029657993872907813436816097280000000000000000000000000d /* 106 */ ,114628056373470835453434738414834942870388487424139673389282723476762012382449946252660360871841673476016298287096435143747350528228224302506311680000000000000000000000000d /* 107 */ ,12265202031961379393517517010387338887131568154382945052653251412013535324922144249034658613287059061933743916719318560380966506520420000368175349760000000000000000000000000d /* 108 */ ,1324641819451828974499891837121832599810209360673358065686551152497461815091591578895743130235002378688844343005686404521144382704205360039762937774080000000000000000000000000d /* 109 */ ,144385958320249358220488210246279753379312820313396029159834075622223337844983482099636001195615259277084033387619818092804737714758384244334160217374720000000000000000000000000d /* 110 */ ,15882455415227429404253703127090772871724410234473563207581748318444567162948183030959960131517678520479243672638179990208521148623422266876757623911219200000000000000000000000000d /* 111 */ ,1762952551090244663872161047107075788761409536026565516041574063347346955087248316436555574598462315773196047662837978913145847497199871623320096254145331200000000000000000000000000d /* 112 */ ,197450685722107402353682037275992488341277868034975337796656295094902858969771811440894224355027779366597957338237853638272334919686385621811850780464277094400000000000000000000000000d /* 113 */ ,22311927486598136465966070212187151182564399087952213171022161345724023063584214692821047352118139068425569179220877461124773845924561575264739138192463311667200000000000000000000000000d /* 114 */ ,2543559733472187557120132004189335234812341496026552301496526393412538629248600474981599398141467853800514886431180030568224218435400019580180261753940817530060800000000000000000000000000d /* 115 */ ,292509369349301569068815180481773552003419272043053514672100535242441942363589054622883930786268803187059211939585703515345785120071002251720730101703194015956992000000000000000000000000000d /* 116 */ ,33931086844518982011982560935885732032396635556994207701963662088123265314176330336254535971207181169698868584991941607780111073928236261199604691797570505851011072000000000000000000000000000d /* 117 */ ,3969937160808720895401959629498630647790406360168322301129748464310422041758630649341780708631240196854767624444057168110272995649603642560353748940315749184568295424000000000000000000000000000d /* 118 */ ,468452584975429065657431236280838416439267950499862031533310318788629800927518416622330123618486343228862579684398745837012213486653229822121742374957258403779058860032000000000000000000000000000d /* 119 */ ,55745857612076058813234317117419771556272886109483581752463927935846946310374691578057284710599874844234646982443450754604453404911734348832487342619913750049708004343808000000000000000000000000000d /* 120 */ ,6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000d /* 121 */ ,809429852527344373968162284544935082997082306309701607045776233628497660426640521713391773997910182738287074185078904956856663439318382745047716214841147650721760223072092160000000000000000000000000000d /* 122 */ ,98750442008336013624115798714482080125644041369783596059584700502676714572050143649033796427745042294071023050579626404736512939596842694895821378210620013388054747214795243520000000000000000000000000000d /* 123 */ ,12146304367025329675766243241881295855454217088483382315328918161829235892362167668831156960612640202170735835221294047782591091570411651472186029519906261646730733907419814952960000000000000000000000000000d /* 124 */ ,1506141741511140879795014161993280686076322918971939407100785852066825250652908790935063463115967385069171243567440461925041295354731044782551067660468376444194611004520057054167040000000000000000000000000000d /* 125 */ ,188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000d /* 126 */ ,23721732428800468856771473051394170805702085973808045661837377170052497697783313457227249544076486314839447086187187275319400401837013955325179315652376928996065123321190898603130880000000000000000000000000000000d /* 127 */ ,3012660018457659544809977077527059692324164918673621799053346900596667207618480809067860692097713761984609779945772783965563851033300772326297773087851869982500270661791244122597621760000000000000000000000000000000d /* 128 */ ,385620482362580421735677065923463640617493109590223590278828403276373402575165543560686168588507361534030051833058916347592172932262498857766114955245039357760034644709279247692495585280000000000000000000000000000000d /* 129 */ ,49745042224772874403902341504126809639656611137138843145968864022652168932196355119328515747917449637889876686464600208839390308261862352651828829226610077151044469167497022952331930501120000000000000000000000000000000d /* 130 */ ,6466855489220473672507304395536485253155359447828049608975952322944781961185526165512707047229268452925683969240398027149120740074042105844737747799459310029635780991774612983803150965145600000000000000000000000000000000d /* 131 */ ,847158069087882051098456875815279568163352087665474498775849754305766436915303927682164623187034167333264599970492141556534816949699515865660644961729169613882287309922474300878212776434073600000000000000000000000000000000d /* 132 */ ,111824865119600430744996307607616902997562475571842633838412167568361169672820118454045730260688510087990927196104962685462595837360336094267205134948250389032461924909766607715924086489297715200000000000000000000000000000000d /* 133 */ ,14872707060906857289084508911813048098675809251055070300508818286592035566485075754388082124671571841702793317081960037166525246368924700537538282948117301741317436012998958826217903503076596121600000000000000000000000000000000d /* 134 */ ,1992942746161518876737324194182948445222558439641379420268181650403332765909000151088003004705990626788174304488982644980314383013435909872030129915047718433336536425741860482713199069412263880294400000000000000000000000000000000d /* 135 */ ,269047270731805048359538766214698040105045389351586221736204522804449923397715020396880405635308734616403531106012657072342441706813847832724067538531441988500432417475151165166281874370655623839744000000000000000000000000000000000d /* 136 */ ,36590428819525486576897272205198933454286172951815726156123815101405189582089242773975735166401987907830880230417721361838572072126683305250473185240276110436058808776620558462614334914409164842205184000000000000000000000000000000000d /* 137 */ ,5012888748274991661034926292112253883237205694398754483388962668892510972746226260034675717797072343372830591567227826571884373881355612819314826377917827129740056802397016509378163883274055583382110208000000000000000000000000000000000d /* 138 */ ,691778647261948849222819828311491035886734385827028118707676848307166514238979223884785249055995983385450621636277440066920043595627074569065446040152660143904127838730788278294186615891819670506731208704000000000000000000000000000000000d /* 139 */ ,96157231969410890041971956135297253988256079629956908500367081914696145479218112119985149618783441690577636407442564169301886059792163365100096999581219760002673769583579570682891939608962934200435638009856000000000000000000000000000000000d /* 140 */ ,13462012475717524605876073858941615558355851148193967190051391468057460367090535696797920946629681836680869097041958983702264048370902871114013579941370766400374327741701139895604871545254810788060989321379840000000000000000000000000000000000d /* 141 */ ,1898143759076170969428526414110767793728175011895349373797246196996101911759765533248506853474785138972002542682916216702019230820297304827075914771733278062452780211579860725280286887880928321116599494314557440000000000000000000000000000000000d /* 142 */ ,269536413788816277658850750803729026709400851689139611079208959973446471469886705721287973193419489734024361060974102771686730776482217285444779897586125484868294790044340222989800738079091821598557128192667156480000000000000000000000000000000000d /* 143 */ ,38543707171800727705215657364933250819444321791546964384326881276202845420193798918144180166658987031965483631719296696351202501036957071818603525354815944336166154976340651887541505545310130488593669331551403376640000000000000000000000000000000000d /* 144 */ ,5550293832739304789551054660550388117999982337982762871343070903773209740507907044212761943998894132603029642967578724274573160149321818341878907651093495984407926316593053871805976798524658790357488383743402086236160000000000000000000000000000000000d /* 145 */ ,804792605747199194484902925779806277109997439007500616344745281047115412373646521410850481879839649227439298230298915019813108221651663659572441609408556917739149315905992811411866635786075524601835815642793302504243200000000000000000000000000000000000d /* 146 */ ,117499720439091082394795827163851716458059626095095089986332811032878850206552392125984170354456588787206137541623641592892713800361142894297576474973649309989915800122274950466132528824767026591868029083847822165619507200000000000000000000000000000000000d /* 147 */ ,17272458904546389112034986593086202319334765035978978227990923221833190980363201642519673042105118551719302218618675314155228928653088005461743741821126448568517622617974417718521481737240752909004600275325629858346067558400000000000000000000000000000000000d /* 148 */ ,2556323917872865588581178015776757943261545225324888777742656636831312265093753843092911610231557545654456728355563946494973881440657024808338073789526714388140608147460213822341179297111631430532680840748193219035217998643200000000000000000000000000000000000d /* 149 */ ,380892263763056972698595524350736933545970238573408427883655838887865527498969322620843829924502074302514052524979028027751108334657896696442372994639480443832950613971571859528835715269633083149369445271480789636247481797836800000000000000000000000000000000000d /* 150 */ ,57133839564458545904789328652610540031895535786011264182548375833179829124845398393126574488675311145377107878746854204162666250198684504466355949195922066574942592095735778929325357290444962472405416790722118445437122269675520000000000000000000000000000000000000d /* 151 */ ,8627209774233240431623188626544191544816225903687700891564804750810154197851655157362112747789971982951943289690774984828562603780001360174419748328584232052816331406456102618328128950857189333333217935399039885261005462721003520000000000000000000000000000000000000d /* 152 */ ,1311335885683452545606724671234717114812066337360530535517850322123143438073451583919041137664075741408695380032997797693941515774560206746511801745944803272028082373781327597985875600530292778666649126180654062559672830333592535040000000000000000000000000000000000000d /* 153 */ ,200634390509568239477828874698911718566246149616161171934231099284840946025238092339613294062603588435530393145048663047173051913507711632216305667129554900620296603188543122491838966881134795135997316305640071571629943041039657861120000000000000000000000000000000000000d /* 154 */ ,30897696138473508879585646703632404659201907040888820477871589289865505687886666220300447285640952619071680544337494109264649994680187591361311072737951454695525676891035640863743200899694758450943586711068571022031011228320107310612480000000000000000000000000000000000000d /* 155 */ ,4789142901463393876335775239063022722176295591337767174070096339929153381622433264146569329274347655956110484372311586936020749175429076661003216274382475477806479918110524333880196139452687559896255940215628508414806740389616633144934400000000000000000000000000000000000000d /* 156 */ ,747106292628289444708380937293831544659502112248691679154935029028947927533099589206864815366798234329153235562080607562019236871366935959116501738803666174537810867225241796085310597754619259343815926673638047312709851500780194770609766400000000000000000000000000000000000000d /* 157 */ ,117295687942641442819215807155131552511541831623044593627324799557544824622696635505477776012587322789677057983246655387237020188804608945581290772992175589402436306154362961985393763847475223716979100487761173428095446685622490578985733324800000000000000000000000000000000000000d /* 158 */ ,18532718694937347965436097530510785296823609396441045793117318330092082290386068409865488609988797000768975161352971551183449189831128213401843942132763743125584936372389347993692214687901085347282697877066265401639080576328353511479745865318400000000000000000000000000000000000000d /* 159 */ ,2946702272495038326504339507351214862194953894034126281105653614484641084171384877168612688988218723122267050655122476638168421183149385930893186799109435156968004883209906330997062135376272570217948962453536198860613811636208208325279592585625600000000000000000000000000000000000000d /* 160 */ ,471472363599206132240694321176194377951192623045460204976904578317542573467421580346978030238114995699562728104819596262106947389303901748942909887857509625114880781313585012959529941660203611234871833992565791817698209861793313332044734813700096000000000000000000000000000000000000000d /* 161 */ ,75907050539472187290751785709367294850142012310319093001281637109124354328254874435863462868336514307629599224875954998199218529677928181579808491945059049643495805791487187086484320607292781408814365272803092482649411787748723446459202305005715456000000000000000000000000000000000000000d /* 162 */ ,12296942187394494341101789284917501765723005994271693066207625211678145401177289658609880984670515317835995074429904709708273401807824365415928975695099566042246320538220924308010459938381430588227927174194100982189204709615293198326390773410925903872000000000000000000000000000000000000000d /* 163 */ ,2004401576545302577599591653441552787812849977066285969791842909503537700391898214353410600501293996807267197132074467682448564494675371562796423038301229264886150247730010662205704969956173185881152129393638460096840367667292791327201696065980922331136000000000000000000000000000000000000000d /* 164 */ ,328721858553429622726333031164414657201307396238870899045862237158580182864271307153959338482212215476391820329660212699921564577126760936298613378281401599441328640627721748601735615072812402484508949220556707455881820297436017777661078154820871262306304000000000000000000000000000000000000000d /* 165 */ ,54239106661315887749844950142128418438215720379413698342567269131165730172604765680403290849565015553604650354393935095487058155225915554489271207416431263907819225703574088519286376487014046409943976621391856730220500349076942933314077895545443758280540160000000000000000000000000000000000000000d /* 166 */ ,9003691705778437366474261723593317460743809582982673924866166675773511208652391102946946281027792581898371958829393225850851653767501982045219020431127589808697991466793298694201538496844331704050700119151048217216603057946772526930136930660543663874569666560000000000000000000000000000000000000000d /* 167 */ ,1503616514864999040201201707840084015944216200358106545452649834854176371844949314192140028931641361177028117124508668717092226179172831001551576411998307498052564574954480881931656928973003394576466919898225052275172710677111011997332867420310791867053134315520000000000000000000000000000000000000000d /* 168 */ ,252607574497319838753801886917134114678628321660161899636045172255501630469951484784279524860515748677740723676917456344471493998101035608260664837215715659672830848592352788164518364067464570288846442542901808782229015393754650015551921726612213033664926565007360000000000000000000000000000000000000000d /* 169 */ ,42690680090047052749392518888995665380688186360567361038491634111179775549421800928543239701427161526538182301399050122215682485679075017796052357489455946484708413412107621199803603527401512378815048789750405684196703601544535852628274771797464002689372589486243840000000000000000000000000000000000000000d /* 170 */ ,7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000d }; // end array declaration /** * the highest pre-calculated factorial - this is also the last factorial that does not exceed the limits of a double. * 170!=7.257415615307999E+306. */ public static final int LAST_DOUBLE_FACTORIAL = factorials.length; /** * 22! should be accurately representable as a double value. *<p><i> Notice 21! would actually be inaccurate as double.</i></p> *<p>We use this to get an accurate starting point for the {@link #factorialBig(int) } method.</p> */ public static final int HIGHEST_ACCURATE_DOUBLE_FACTORIAL = 22; /** * basically a lookup-function for n! * @param n * @return */ public static double factorial(int n) { // to speed up calculation all factorials that result in valid double values // are precalculated. 170! is the last factorial still representable by a double. if (n < 0) { throw new IllegalArgumentException("factorial can only handle n >= 0"); } if (n > LAST_DOUBLE_FACTORIAL) { throw new ArithmeticException("Can't calculate a factorial for n larger then " + factorials.length + " within doubles."); } else { // do a simple lookup return factorials[n]; // take the shortcut :) } }// end method factorial /** * for values of n smaller then {@link #HIGHEST_ACCURATE_DOUBLE_FACTORIAL} the double version will be used. * Beyond that a double can't hold an accurate representation of the value. * @param n * @return */ public static BigDecimal factorialBig(int n) { // For fast factorial calculation we assume // most factorial calculations we carry out are in the range 0 <= n <= 20 // so we just do a very fast lookup in memory. // If the case arises where n > 20 we do the calculation if (n < 0) { throw new IllegalArgumentException("factorial can only handle n >= 0"); } if (n > HIGHEST_ACCURATE_DOUBLE_FACTORIAL) { BigDecimal bd = new BigDecimal(factorials[HIGHEST_ACCURATE_DOUBLE_FACTORIAL]); for (int i = HIGHEST_ACCURATE_DOUBLE_FACTORIAL+1; i<=n;i++) { bd=bd.multiply(bd); } return bd; } else { // do a simple lookup return new BigDecimal(factorials[n]); // take the shortcut :) } }// end method factorial public static double binomialCoefficient(int n, int k) { if (n > LAST_DOUBLE_FACTORIAL || k > LAST_DOUBLE_FACTORIAL) { MathContext mc = MathContext.DECIMAL128; return factorialBig(n).divide(factorialBig(k).multiply(factorialBig(n-k), mc), mc).doubleValue(); } else { return factorial(n)/(factorial(k)*factorial(n-k)); } } /** * @param filePath name of file to open. The file can reside anywhere in the * classpath */ public static BufferedReader readFromClassPath(String filePath) throws java.io.IOException { String path = filePath; System.err.println("!!!reading config!!!"); System.err.println("from : " + filePath); StringBuffer fileData = new StringBuffer(1000); URL res = Util.class.getResource(path); while (res == null && path.contains(".")) { path = path.replaceFirst("\\.", Matcher.quoteReplacement(File.separator)); res = Util.class.getResource(path); } if (res == null) { path = filePath; while (res == null && path.contains(".")) { path = path.replaceFirst("\\.", "/"); res = Util.class.getResource(path); } } InputStream is = Util.class.getResourceAsStream(path); return new BufferedReader(new InputStreamReader(is)); } public static String repeatString(String s, int repeat) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < repeat; i++) { sb.append(s); } return sb.toString(); } public static void forceGC() { for (int i = 1; i > 0; i--) { System.gc(); } } public static String doubleToString(double value) { // DecimalFormat oneDigit = new DecimalFormat("0.0"); String fUnit = "B"; if (value > 1024 * 1024 * 900) { value /= 1024 * 1024 * 1024; fUnit = "GB"; } else if (value > 1024 * 900) { value /= 1024 * 1024; fUnit = "MB"; } else if (value > 900) { value /= 1024; fUnit = "KB"; } return "" + oneDigit.format(value) + fUnit; } public static void verboseGC() { double freemem = Runtime.getRuntime().freeMemory(); double maxmem = Runtime.getRuntime().maxMemory(); double totalmem = Runtime.getRuntime().totalMemory(); StringBuilder sb = new StringBuilder(); sb.append("===================\n"); sb.append("======= GC ========\n"); sb.append("===================\n"); sb.append("free mem" + Util.doubleToString(freemem) + "\n"); sb.append("max mem" + Util.doubleToString(maxmem) + "\n"); sb.append("total mem" + Util.doubleToString(totalmem) + "\n"); sb.append("do gc\n"); System.out.println(sb.toString()); for (int i=10;i>0; i--) { System.gc(); } sb = new StringBuilder(); freemem = Runtime.getRuntime().freeMemory(); maxmem = Runtime.getRuntime().maxMemory(); totalmem = Runtime.getRuntime().totalMemory(); sb.append("free mem" + Util.doubleToString(freemem) + "\n"); sb.append("max mem" + Util.doubleToString(maxmem) + "\n"); sb.append("total mem" + Util.doubleToString(totalmem) + "\n"); sb.append("====================\n"); System.out.println(sb.toString()); } public static void joinAllThread(Thread[] gatherthread) { boolean running = true; while (running) { running = false; for (int i = 0; i < gatherthread.length; i++) { if (gatherthread[i]!= null) { try { gatherthread[i].join(1000); } catch (InterruptedException ex1) { } running |= gatherthread[i].isAlive(); } } } } /** * creates a string that contains some info about the current memory situation * @return String representation of used and free memory */ public static String memoryToString() { Runtime runtime = Runtime.getRuntime(); double fm = runtime.freeMemory(); String fmu = "B"; double mm = runtime.maxMemory(); double tm = runtime.totalMemory(); double um = tm-fm; return "Used: " + StringUtils.toHuman(um) + " of " + StringUtils.toHuman(mm) + " (Free:" + StringUtils.toHuman(fm) + " Total:" + StringUtils.toHuman(tm) + " Max:"+ StringUtils.toHuman(mm) +")"; } public static void logStackTraces(Level level) { ThreadGroup tg = Thread.currentThread().getThreadGroup(); logStackTraces(level, tg); } public static void logStackTraces(Level level,ThreadGroup tg) { StringBuilder sb = getStackTraces(tg); Logger.getLogger(Util.class.getName()).log(level, sb.toString()); } public static StringBuilder getStackTraces() { ThreadGroup tg = Thread.currentThread().getThreadGroup(); return getStackTraces(tg); } public static StringBuilder getStackTraces(ThreadGroup tg) { Thread[] active = new Thread[tg.activeCount()*100]; tg.enumerate(active, true); StringBuilder sb = new StringBuilder(); for (Thread t : active) { if (t != null) { try { sb.append("\n--------------------------\n"); sb.append("--- Thread stack-trace ---\n"); sb.append("--------------------------\n"); sb.append("--- " + t.getId() + " : " + t.getName()+"\n"); if (t.isDaemon()) sb.append("--- DAEMON-THREAD \n"); sb.append(MyArrayUtils.toString(t.getStackTrace(), "\n")); sb.append("\n"); } catch (SecurityException se) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, "Error:", se); System.err.println("could not get a stacktrace"); } } } return sb; } public static Locale getLocale(String locale) { Locale ret = null; String localeLC = locale.toLowerCase().trim(); for (Locale l : Locale.getAvailableLocales()) { if (l.toString().toLowerCase().contentEquals(localeLC)) { return l; } if (l.getDisplayName().toLowerCase().contentEquals(localeLC)) { return l; } if (l.getDisplayName().toLowerCase().contentEquals(localeLC)) { return l; } if (l.getCountry().toLowerCase().contentEquals(localeLC)) { ret = l; } if (l.getDisplayScript().toLowerCase().contentEquals(localeLC)) { ret = l; } if (l.getDisplayLanguage().toLowerCase().contentEquals(localeLC)) { ret = l; } if (l.getLanguage().toLowerCase().contentEquals(localeLC)) { ret = l; } } return ret; } public static <T extends Number> double weightedMedian(Collection<T> data, Collection<T> weight) { class Combined implements Comparable<Combined>{ double v; double w; public Combined(double v, double w) { this.v = v; this.w = w; } @Override public int compareTo(Combined o) { return Double.compare(v,o.v); } } Iterator<T> di = data.iterator(); Iterator<T> wi = weight.iterator(); Combined[] md = new Combined[data.size()]; int pos =0; double weightsum = 0; while (di.hasNext()) { T vt = di.next(); T wt = wi.next(); double v = vt.doubleValue(); double w = wt.doubleValue(); Combined c = new Combined(v,w); md[pos++] = c; weightsum += w; } Arrays.sort(md); double weightTarget = weightsum/2; weightsum = 0; pos = -1; do { pos++; weightsum += md[pos].w; } while (weightsum<weightTarget); if (weightsum == weightTarget) { return (md[pos].v * md[pos].w + md[pos+1].v * md[pos+1].w) / (md[pos].w + md[pos+1].w); } return md[pos].v; } public static <T extends Number> double weightedAverage(Collection<T> data, Collection<T> weight) { double valueSum = 0; double weightSum = 0; Iterator<T> di = data.iterator(); Iterator<T> wi = weight.iterator(); while (di.hasNext()) { double w = wi.next().doubleValue(); weightSum += w; valueSum += di.next().doubleValue() * w; } return valueSum/weightSum; } }// end class Util
apache-2.0
alexeev/jboss-fuse-mirror
fabric/fabric-core/src/main/java/io/fabric8/api/jmx/MetaTypeObjectDTO.java
2471
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.api.jmx; import org.fusesource.insight.log.support.Strings; import org.osgi.service.metatype.AttributeDefinition; import org.osgi.service.metatype.ObjectClassDefinition; import java.util.ArrayList; import java.util.List; /** */ public class MetaTypeObjectDTO extends MetaTypeObjectSupportDTO { private List<MetaTypeAttributeDTO> attributes = new ArrayList<MetaTypeAttributeDTO>(); public MetaTypeObjectDTO() { } public MetaTypeObjectDTO(ObjectClassDefinition objectDef) { super(objectDef); addAttributes(objectDef); } /** * Appends any metadata from an additional object definition from a different bundle */ public void appendObjectDefinition(ObjectClassDefinition objectDef) { super.appendObjectDefinition(objectDef); addAttributes(objectDef); } protected void addAttributes(ObjectClassDefinition objectDef) { addAttributes(objectDef.getAttributeDefinitions(ObjectClassDefinition.REQUIRED), true); addAttributes(objectDef.getAttributeDefinitions(ObjectClassDefinition.OPTIONAL), false); } protected void addAttributes(AttributeDefinition[] attributeDefinitions, boolean required) { if (attributeDefinitions != null) { for (AttributeDefinition attributeDefinition : attributeDefinitions) { attributes.add(new MetaTypeAttributeDTO(attributeDefinition, required)); } } } public List<MetaTypeAttributeDTO> getAttributes() { return attributes; } public void setAttributes(List<MetaTypeAttributeDTO> attributes) { this.attributes = attributes; } }
apache-2.0
PurelyApplied/geode
geode-dunit/src/main/java/org/apache/geode/test/dunit/DUnitEnv.java
2522
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.test.dunit; import java.io.File; import java.rmi.RemoteException; import java.util.Properties; import org.apache.geode.test.dunit.internal.BounceResult; /** * This class provides an abstraction over the environment that is used to run dunit. This will * delegate to the hydra or to the standalone dunit launcher as needed. * * <p> * Any dunit tests that rely on hydra configuration should go through here, so that we can separate * them out from depending on hydra and run them on a different VM launching system. */ public abstract class DUnitEnv { private static DUnitEnv instance = null; public static DUnitEnv get() { if (instance == null) { try { // for tests that are still being migrated to the open-source // distributed unit test framework we need to look for this // old closed-source dunit environment Class clazz = Class.forName("dunit.hydra.HydraDUnitEnv"); instance = (DUnitEnv) clazz.newInstance(); } catch (Exception e) { throw new Error("Distributed unit test environment is not initialized"); } } return instance; } public static void set(DUnitEnv dunitEnv) { instance = dunitEnv; } public abstract String getLocatorString(); public abstract String getLocatorAddress(); public abstract int getLocatorPort(); public abstract Properties getDistributedSystemProperties(); public abstract int getPid(); public abstract int getVMID(); public abstract BounceResult bounce(String version, int pid, boolean force) throws RemoteException; public abstract File getWorkingDirectory(int pid); public abstract File getWorkingDirectory(String version, int pid); }
apache-2.0
janicduplessis/buck
src/com/facebook/buck/rules/macros/MacroExpanderWithCustomFileOutput.java
1320
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.rules.macros; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.MacroException; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; /** * {@link MacroExpander}s that also implement this interface can provide different output when * they are expanding to a file. */ public interface MacroExpanderWithCustomFileOutput { /** * Expand the input given for the this macro to some string, which is intended to be written to * a file. */ String expandForFile( BuildTarget target, CellPathResolver cellNames, BuildRuleResolver resolver, String input) throws MacroException; }
apache-2.0
tyrelltle/microservice
microservices/api/product-api-service/src/main/java/com/zimolo/inventory/domain/util/CustomDateTimeSerializer.java
930
package com.zimolo.inventory.domain.util; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.io.IOException; /** * Custom Jackson serializer for displaying Joda DateTime objects. */ public class CustomDateTimeSerializer extends JsonSerializer<DateTime> { private static DateTimeFormatter formatter = DateTimeFormat .forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); @Override public void serialize(DateTime value, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException { generator.writeString(formatter.print(value.toDateTime(DateTimeZone.UTC))); } }
apache-2.0
opg7371/Smack
smack-extensions/src/test/java/org/jivesoftware/smackx/forward/ForwardedTest.java
3759
/** * * Copyright the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.forward; import static org.jivesoftware.smack.test.util.CharsequenceEquals.equalsCharSequence; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.util.Properties; import org.jivesoftware.smack.util.PacketParserUtils; import org.jivesoftware.smackx.delay.packet.DelayInformation; import org.jivesoftware.smackx.forward.packet.Forwarded; import org.jivesoftware.smackx.forward.provider.ForwardedProvider; import org.junit.Test; import org.xmlpull.v1.XmlPullParser; import com.jamesmurty.utils.XMLBuilder; public class ForwardedTest { private static Properties outputProperties = new Properties(); static { outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); } @Test public void forwardedTest() throws Exception { XmlPullParser parser; String control; Forwarded fwd; control = XMLBuilder.create("forwarded") .a("xmlns", "urn:xmpp:forwarded:0") .e("message") .a("from", "romeo@montague.com") .asString(outputProperties); parser = PacketParserUtils.getParserFor(control); fwd = (Forwarded) new ForwardedProvider().parse(parser); // no delay in packet assertEquals(null, fwd.getDelayInformation()); // check message assertThat("romeo@montague.com", equalsCharSequence(fwd.getForwardedPacket().getFrom())); // check end of tag assertEquals(XmlPullParser.END_TAG, parser.getEventType()); assertEquals("forwarded", parser.getName()); } @Test public void forwardedWithDelayTest() throws Exception { XmlPullParser parser; String control; Forwarded fwd; // @formatter:off control = XMLBuilder.create("forwarded").a("xmlns", "urn:xmpp:forwarded:0") .e("message").a("from", "romeo@montague.com").up() .e("delay").ns(DelayInformation.NAMESPACE).a("stamp", "2010-07-10T23:08:25Z") .asString(outputProperties); // @formatter:on parser = PacketParserUtils.getParserFor(control); fwd = (Forwarded) new ForwardedProvider().parse(parser); // assert there is delay information in packet DelayInformation delay = fwd.getDelayInformation(); assertNotNull(delay); // check message assertThat("romeo@montague.com", equalsCharSequence(fwd.getForwardedPacket().getFrom())); // check end of tag assertEquals(XmlPullParser.END_TAG, parser.getEventType()); assertEquals("forwarded", parser.getName()); } @Test(expected=Exception.class) public void forwardedEmptyTest() throws Exception { XmlPullParser parser; String control; control = XMLBuilder.create("forwarded") .a("xmlns", "urn:xmpp:forwarded:0") .asString(outputProperties); parser = PacketParserUtils.getParserFor(control); new ForwardedProvider().parse(parser); } }
apache-2.0
Zhangbaowen13/greenhouse
app/src/main/java/com/example/pengpeng/db/County.java
731
package com.example.pengpeng.db; import org.litepal.crud.DataSupport; /** * Created by Administrator on 2017/9/21 0021. */ public class County extends DataSupport { private int id; private String countyName; private String weatherId; private int cityId; public int getId() {return id;} public void setId(int id) {this.id = id;} public String getCountyName() {return countyName;} public void setCountyName(String countyName) {this.countyName = countyName;} public String getWeatherId() {return weatherId;} public void setWeatherId(String weatherId) {this.weatherId = weatherId;} public int getCityId() {return cityId;} public void setCityId(int cityId) {this.cityId = cityId;} }
apache-2.0
ddppfamily/xgb
src/main/java/cn/tomoya/module/section/entity/Section.java
569
package cn.tomoya.module.section.entity; import javax.persistence.*; import java.io.Serializable; /** * xgb. * Copyright (c) 2016, All Rights Reserved. * http://tomoya.cn */ @Entity @Table(name = "pybbs_section") public class Section implements Serializable { @Id @GeneratedValue private int id; @Column(unique = true) private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
apache-2.0
SEEG-Oxford/ABRAID-MP
src/Common/test/uk/ac/ox/zoo/seeg/abraid/mp/common/service/core/EmailServiceIntegrationTest.java
1815
package uk.ac.ox.zoo.seeg.abraid.mp.common.service.core; import org.apache.commons.io.FileUtils; import org.joda.time.DateTime; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import uk.ac.ox.zoo.seeg.abraid.mp.common.config.SmtpConfiguration; import uk.ac.ox.zoo.seeg.abraid.mp.common.util.EmailFactoryImpl; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Integration test for EmailServiceImpl. * Copyright (c) 2014 University of Oxford */ @Ignore public class EmailServiceIntegrationTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); ///CHECKSTYLE:SUPPRESS VisibilityModifier @Test public void sendEmailNow() throws Exception { EmailService emailService = new EmailServiceImpl( new EmailFactoryImpl(), "EmailServiceIntegrationTestFrom@uk.ac.ox.zoo.seeg.abraid.mp.common.service.core", "EmailServiceIntegrationTestTo@uk.ac.ox.zoo.seeg.abraid.mp.common.service.core", new SmtpConfiguration( "mailtrap.io", 2525, false, "235398130c23105ca", "b69aea70436f30" ), new Class[0], new File[] {testFolder.getRoot()}); FileUtils.writeStringToFile(new File(testFolder.getRoot().toString(), "template.ftl"), "${foo} ${date}"); Map<String, Object> data = new HashMap<>(); data.put("foo", "bar"); data.put("date", DateTime.now()); emailService.sendEmail( "sendEmailNow@EmailServiceIntegrationTest", "Test " + DateTime.now().toString(), "template.ftl", data); } }
apache-2.0
halober/ovirt-engine
frontend/webadmin/modules/userportal-gwtp/src/main/java/org/ovirt/engine/ui/userportal/section/main/view/popup/vm/VmNextRunConfigurationPopupView.java
1626
package org.ovirt.engine.ui.userportal.section.main.view.popup.vm; import org.ovirt.engine.ui.common.CommonApplicationResources; import org.ovirt.engine.ui.common.CommonApplicationTemplates; import org.ovirt.engine.ui.common.idhandler.ElementIdHandler; import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundWidgetPopupView; import org.ovirt.engine.ui.common.widget.uicommon.popup.vm.VmNextRunConfigurationWidget; import org.ovirt.engine.ui.uicommonweb.models.vms.VmNextRunConfigurationModel; import org.ovirt.engine.ui.userportal.ApplicationConstants; import org.ovirt.engine.ui.userportal.ApplicationMessages; import org.ovirt.engine.ui.userportal.section.main.presenter.popup.vm.VmNextRunConfigurationPresenterWidget; import com.google.gwt.core.client.GWT; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; public class VmNextRunConfigurationPopupView extends AbstractModelBoundWidgetPopupView<VmNextRunConfigurationModel> implements VmNextRunConfigurationPresenterWidget.ViewDef { interface ViewIdHandler extends ElementIdHandler<VmNextRunConfigurationPopupView> { ViewIdHandler idHandler = GWT.create(ViewIdHandler.class); } @Inject public VmNextRunConfigurationPopupView(EventBus eventBus, CommonApplicationResources resources, ApplicationConstants constants, ApplicationMessages messages, CommonApplicationTemplates templates) { super(eventBus, resources, new VmNextRunConfigurationWidget(constants, messages, templates), "400px", "200px"); //$NON-NLS-1$ //$NON-NLS-2$ ViewIdHandler.idHandler.generateAndSetIds(this); } }
apache-2.0
jomof/cdep
cdep/src/main/java/io/cdep/cdep/ast/finder/ModuleArchiveExpression.java
1901
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cdep.cdep.ast.finder; import io.cdep.annotations.NotNull; import io.cdep.annotations.Nullable; import io.cdep.cdep.yml.cdepmanifest.CxxLanguageFeatures; import java.net.URL; import static io.cdep.cdep.utils.Invariant.require; public class ModuleArchiveExpression extends StatementExpression { @NotNull final public URL file; // The zip file. @NotNull final public String sha256; @NotNull final public Long size; @Nullable final public String include; @Nullable final public Expression includePath; @NotNull final public String libs[]; @NotNull final public Expression libraryPaths[]; @NotNull final public CxxLanguageFeatures requires[]; public ModuleArchiveExpression( @NotNull URL file, @NotNull String sha256, @NotNull Long size, @Nullable String include, // Like "include" @Nullable Expression fullIncludePath, @NotNull String libs[], // Like "lib/libsqlite.a" @NotNull Expression libraryPaths[], @NotNull CxxLanguageFeatures requires[]) { require(libs.length == libraryPaths.length); this.file = file; this.sha256 = sha256; this.size = size; this.include = include; this.includePath = fullIncludePath; this.libs = libs; this.libraryPaths = libraryPaths; this.requires = requires; } }
apache-2.0
iormark/Knigoed
src/test/java/info/knigoed/dao/SearchSphinxDaoTest.java
1655
package info.knigoed.dao; import info.knigoed.config.DataSourceConfig; import info.knigoed.config.OtherConfig; import info.knigoed.config.RequestContext; import info.knigoed.config.WebConfig; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.sql.SQLException; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {WebConfig.class, OtherConfig.class, DataSourceConfig.class, RequestContext.class}) @WebAppConfiguration @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SearchSphinxDaoTest { // @Autowired private SearchSphinxDao searchSphinxDao; @Test public void testARunSearch() throws SQLException { assertTrue(searchSphinxDao.runSearch("а", 0, 10)); } @Test public void testGetYears() throws SQLException { assertThat(searchSphinxDao.getYears().isEmpty(), is(false)); } @Test public void testGetBooksId() throws SQLException { assertNotNull(searchSphinxDao.getBooksId()); } @Test public void testGetShopsId() throws SQLException { assertThat(searchSphinxDao.getShopsId().isEmpty(), is(false)); } }
apache-2.0
xqgdmg/DavidNBA-master
app/src/main/java/com/yuyh/sprintnba/mvp/view/PostView.java
348
package com.yuyh.sprintnba.mvp.view; /** * @author yuyh. * @date 2016/6/27. */ public interface PostView { void showLoadding(); void hideLoadding(); void postSuccess(); void postFailure(String msg); void feedbackSuccess(); void checkPermissionSuccess(boolean hasPermission, int code, String msg, boolean retry); }
apache-2.0
firejack-open/Firejack-Platform
platform/src/main/java/net/firejack/platform/core/config/meta/element/authority/RoleElement.java
1620
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package net.firejack.platform.core.config.meta.element.authority; import net.firejack.platform.core.config.meta.element.PackageDescriptorElement; import net.firejack.platform.core.model.registry.authority.RoleModel; import java.util.List; public class RoleElement extends PackageDescriptorElement<RoleModel> { private List<RolePermissionReference> permissions; /** * @return */ public List<RolePermissionReference> getPermissions() { return permissions; } /** * @param permissions */ public void setPermissions(List<RolePermissionReference> permissions) { this.permissions = permissions; } @Override public Class<RoleModel> getEntityClass() { return RoleModel.class; } }
apache-2.0
ben-manes/caffeine
jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java
3335
/* * Copyright 2016 Ben Manes. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.benmanes.caffeine.jcache.integration; import static com.google.common.truth.Truth.assertThat; import java.util.Collections; import java.util.Map; import java.util.function.Supplier; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheLoaderException; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.github.benmanes.caffeine.jcache.AbstractJCacheTest; import com.github.benmanes.caffeine.jcache.configuration.CaffeineConfiguration; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; /** * @author ben.manes@gmail.com (Ben Manes) */ public final class CacheLoaderTest extends AbstractJCacheTest { private Supplier<Map<Integer, Integer>> loadAllSupplier; private Supplier<Integer> loadSupplier; @BeforeMethod public void beforeMethod() { loadSupplier = () -> { throw new UnsupportedOperationException(); }; loadAllSupplier = () -> { throw new UnsupportedOperationException(); }; } @Test public void load() { loadSupplier = () -> -1; assertThat(jcacheLoading.get(1)).isEqualTo(-1); } @Test public void load_null() { loadSupplier = () -> null; assertThat(jcacheLoading.get(1)).isNull(); } @Test public void load_failure() { try { loadSupplier = () -> { throw new IllegalStateException(); }; jcacheLoading.get(1); Assert.fail(); } catch (CacheLoaderException e) { assertThat(e).hasCauseThat().isInstanceOf(IllegalStateException.class); } } @Test public void loadAll() { loadAllSupplier = () -> ImmutableMap.of(1, -1, 2, -2, 3, -3); var result = jcacheLoading.getAll(ImmutableSet.of(1, 2, 3)); assertThat(result).containsExactlyEntriesIn(loadAllSupplier.get()); } @Test(expectedExceptions = CacheLoaderException.class) public void loadAll_null() { loadAllSupplier = () -> null; jcacheLoading.getAll(ImmutableSet.of(1, 2, 3)); } @Test public void loadAll_nullMapping() { loadAllSupplier = () -> Collections.singletonMap(1, null); var result = jcacheLoading.getAll(ImmutableSet.of(1, 2, 3)); assertThat(result).isEmpty(); } @Override protected CaffeineConfiguration<Integer, Integer> getConfiguration() { return new CaffeineConfiguration<>(); } @Override protected CacheLoader<Integer, Integer> getCacheLoader() { return new CacheLoader<Integer, Integer>() { @Override public Integer load(Integer key) { return loadSupplier.get(); } @Override public Map<Integer, Integer> loadAll(Iterable<? extends Integer> keys) { return loadAllSupplier.get(); } }; } }
apache-2.0
snxmv/coolweather
app/src/main/java/shixiaofei/coolweather/love/shaonianAndxmv/model/County.java
832
package shixiaofei.coolweather.love.shaonianAndxmv.model; /**County实体类 * Created by shixiaofei on 2016/9/24. */ public class County { private int id; private String countyName; private String countyCode; private int cityId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getCountyCode() { return countyCode; } public void setCountyCode(String countyCode) { this.countyCode = countyCode; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
apache-2.0
roberthafner/flowable-engine
modules/flowable-ui-modeler/flowable-ui-modeler-logic/src/main/java/org/activiti/app/service/editor/ModelImageService.java
7838
/* 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.activiti.app.service.editor; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.activiti.app.domain.editor.Model; import org.activiti.app.util.ImageGenerator; import org.activiti.bpmn.model.Artifact; import org.activiti.bpmn.model.Association; import org.activiti.bpmn.model.BpmnModel; import org.activiti.bpmn.model.FlowElement; import org.activiti.bpmn.model.GraphicInfo; import org.activiti.bpmn.model.Lane; import org.activiti.bpmn.model.Pool; import org.activiti.bpmn.model.Process; import org.activiti.bpmn.model.SequenceFlow; import org.activiti.bpmn.model.SubProcess; import org.activiti.editor.language.json.converter.BpmnJsonConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.node.ObjectNode; @Service @Transactional public class ModelImageService { private final Logger log = LoggerFactory.getLogger(ModelImageService.class); private static float THUMBNAIL_WIDTH = 300f; protected BpmnJsonConverter bpmnJsonConverter = new BpmnJsonConverter(); public byte[] generateThumbnailImage(Model model, ObjectNode editorJsonNode) { try { BpmnModel bpmnModel = bpmnJsonConverter.convertToBpmnModel(editorJsonNode); double scaleFactor = 1.0; GraphicInfo diagramInfo = calculateDiagramSize(bpmnModel); if (diagramInfo.getWidth() > THUMBNAIL_WIDTH) { scaleFactor = diagramInfo.getWidth() / THUMBNAIL_WIDTH; scaleDiagram(bpmnModel, scaleFactor); } BufferedImage modelImage = ImageGenerator.createImage(bpmnModel, scaleFactor); if (modelImage != null) { return ImageGenerator.createByteArrayForImage(modelImage, "png"); } } catch (Exception e) { log.error("Error creating thumbnail image " + model.getId(), e); } return null; } protected GraphicInfo calculateDiagramSize(BpmnModel bpmnModel) { GraphicInfo diagramInfo = new GraphicInfo(); for (Pool pool : bpmnModel.getPools()) { GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(pool.getId()); double elementMaxX = graphicInfo.getX() + graphicInfo.getWidth(); double elementMaxY = graphicInfo.getY() + graphicInfo.getHeight(); if (elementMaxX > diagramInfo.getWidth()) { diagramInfo.setWidth(elementMaxX); } if (elementMaxY > diagramInfo.getHeight()) { diagramInfo.setHeight(elementMaxY); } } for (Process process : bpmnModel.getProcesses()) { calculateWidthForFlowElements(process.getFlowElements(), bpmnModel, diagramInfo); calculateWidthForArtifacts(process.getArtifacts(), bpmnModel, diagramInfo); } return diagramInfo; } protected void scaleDiagram(BpmnModel bpmnModel, double scaleFactor) { for (Pool pool : bpmnModel.getPools()) { GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(pool.getId()); scaleGraphicInfo(graphicInfo, scaleFactor); } for (Process process : bpmnModel.getProcesses()) { scaleFlowElements(process.getFlowElements(), bpmnModel, scaleFactor); scaleArtifacts(process.getArtifacts(), bpmnModel, scaleFactor); for (Lane lane : process.getLanes()) { scaleGraphicInfo(bpmnModel.getGraphicInfo(lane.getId()), scaleFactor); } } } protected void calculateWidthForFlowElements(Collection<FlowElement> elementList, BpmnModel bpmnModel, GraphicInfo diagramInfo) { for (FlowElement flowElement : elementList) { List<GraphicInfo> graphicInfoList = new ArrayList<GraphicInfo>(); if (flowElement instanceof SequenceFlow) { List<GraphicInfo> flowGraphics = bpmnModel.getFlowLocationGraphicInfo(flowElement.getId()); if (flowGraphics != null && flowGraphics.size() > 0) { graphicInfoList.addAll(flowGraphics); } } else { GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowElement.getId()); if (graphicInfo != null) { graphicInfoList.add(graphicInfo); } } processGraphicInfoList(graphicInfoList, diagramInfo); } } protected void calculateWidthForArtifacts(Collection<Artifact> artifactList, BpmnModel bpmnModel, GraphicInfo diagramInfo) { for (Artifact artifact : artifactList) { List<GraphicInfo> graphicInfoList = new ArrayList<GraphicInfo>(); if (artifact instanceof Association) { graphicInfoList.addAll(bpmnModel.getFlowLocationGraphicInfo(artifact.getId())); } else { graphicInfoList.add(bpmnModel.getGraphicInfo(artifact.getId())); } processGraphicInfoList(graphicInfoList, diagramInfo); } } protected void processGraphicInfoList(List<GraphicInfo> graphicInfoList, GraphicInfo diagramInfo) { for (GraphicInfo graphicInfo : graphicInfoList) { double elementMaxX = graphicInfo.getX() + graphicInfo.getWidth(); double elementMaxY = graphicInfo.getY() + graphicInfo.getHeight(); if (elementMaxX > diagramInfo.getWidth()) { diagramInfo.setWidth(elementMaxX); } if (elementMaxY > diagramInfo.getHeight()) { diagramInfo.setHeight(elementMaxY); } } } protected void scaleFlowElements(Collection<FlowElement> elementList, BpmnModel bpmnModel, double scaleFactor) { for (FlowElement flowElement : elementList) { List<GraphicInfo> graphicInfoList = new ArrayList<GraphicInfo>(); if (flowElement instanceof SequenceFlow) { List<GraphicInfo> flowList = bpmnModel.getFlowLocationGraphicInfo(flowElement.getId()); if (flowList != null) { graphicInfoList.addAll(flowList); } } else { graphicInfoList.add(bpmnModel.getGraphicInfo(flowElement.getId())); } scaleGraphicInfoList(graphicInfoList, scaleFactor); if (flowElement instanceof SubProcess) { SubProcess subProcess = (SubProcess) flowElement; scaleFlowElements(subProcess.getFlowElements(), bpmnModel, scaleFactor); } } } protected void scaleArtifacts(Collection<Artifact> artifactList, BpmnModel bpmnModel, double scaleFactor) { for (Artifact artifact : artifactList) { List<GraphicInfo> graphicInfoList = new ArrayList<GraphicInfo>(); if (artifact instanceof Association) { List<GraphicInfo> flowList = bpmnModel.getFlowLocationGraphicInfo(artifact.getId()); if (flowList != null) { graphicInfoList.addAll(flowList); } } else { graphicInfoList.add(bpmnModel.getGraphicInfo(artifact.getId())); } scaleGraphicInfoList(graphicInfoList, scaleFactor); } } protected void scaleGraphicInfoList(List<GraphicInfo> graphicInfoList, double scaleFactor) { for (GraphicInfo graphicInfo : graphicInfoList) { scaleGraphicInfo(graphicInfo, scaleFactor); } } protected void scaleGraphicInfo(GraphicInfo graphicInfo, double scaleFactor) { graphicInfo.setX(graphicInfo.getX() / scaleFactor); graphicInfo.setY(graphicInfo.getY() / scaleFactor); graphicInfo.setWidth(graphicInfo.getWidth() / scaleFactor); graphicInfo.setHeight(graphicInfo.getHeight() / scaleFactor); } }
apache-2.0
vimaier/conqat
org.conqat.engine.sourcecode/external/scanner-generated-src/org/conqat/lib/scanner/JavaToken.java
2366
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.lib.scanner; /** * Class for JAVA tokens generated by the JAVA scanner. This does only add the * language identification to the base class. * <p> * NOTE: This class was automatically generated. DO NOT MODIFY. * * @see org.conqat.lib.scanner.Token * @see org.conqat.lib.scanner.JavaScanner */ public class JavaToken extends Token { /** * Create new Java token. * * @param type * token type * @param offset * number of characters before token in its origin * @param lineNumber * line number * @param text * original text * @param originId * origin id */ /* package */JavaToken(ETokenType type, int offset, int lineNumber, String text, String originId) { super(type, offset, lineNumber, text, originId); } /** {@inheritDoc} */ @Override public ELanguage getLanguage() { return ELanguage.JAVA; } /** {@inheritDoc} */ @Override public JavaToken newToken(ETokenType type, int offset, int lineNumber, String text, String originId) { return new JavaToken(type, offset, lineNumber, text, originId); } }
apache-2.0
ConnCollege/cas-5
src/main/java/edu/conncoll/cas/interrupts/web/flow/AbstractConncollInterruptsRepository.java
3485
package edu.conncoll.cas.interrupts.web.flow; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; import org.apereo.cas.authentication.Credential; import org.apereo.cas.authentication.principal.Principal; import org.apereo.cas.ticket.registry.TicketRegistrySupport; import org.apereo.cas.web.support.WebUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.webflow.execution.RequestContext; import edu.conncoll.cas.jdbc.JDBCCamel; /* * Figure out which of these needs to be included for init import org.apereo.cas.authentication.UsernamePasswordCredential; import org.pac4j.core.credentials.UsernamePasswordCredentials; import org.apereo.cas.ticket.registry.TicketRegistry; import org.apereo.cas.ticket.TicketGrantingTicket; */ public abstract class AbstractConncollInterruptsRepository implements ConncollInterruptsRepository { private static final long serialVersionUID = 1883808902502739L; private static final Logger LOGGER = LoggerFactory.getLogger(AbstractConncollInterruptsRepository.class); /** * Single-valued attribute in LDAP that describes whether the policy * has been accepted. Its value must match either TRUE/FALSE. */ protected String intAttributeName; protected JDBCCamel jdbcCamel; /** * Ticket registry support. */ protected TicketRegistrySupport ticketRegistrySupport; public AbstractConncollInterruptsRepository(final TicketRegistrySupport ticketRegistrySupport) { this.ticketRegistrySupport = ticketRegistrySupport; } @Override public Pair<String, Principal> verify(final RequestContext requestContext, final Credential credential) { final Principal principal = WebUtils.getPrincipalFromRequestContext(requestContext, this.ticketRegistrySupport); final Map<String, Object> attributes = principal.getAttributes(); LOGGER.debug("Principal attributes found for [{}] are [{}]", principal.getId(), attributes); if (attributes != null && attributes.containsKey(this.intAttributeName)) { final Object value = attributes.get(this.intAttributeName); LOGGER.debug("Evaluating attribute value [{}] found for [{}]", value, this.intAttributeName); if (value.toString().equalsIgnoreCase("true")) { return Pair.of("true", principal); } } return Pair.of("false", principal); } @Override public String checkInt(RequestContext requestContext, Credential credential, Boolean loggedIn){ return "noInterrupt"; } @Override public String setFlag(RequestContext requestContext, Credential credential){ String interrupt = requestContext.getFlowScope().get("interrupt",String.class); LOGGER.debug("setFlag updating Flag to " + interrupt); requestContext.getFlowScope().put("Flag", interrupt); return "success"; } public void setIntAttributeName(final String intAttributeName) { this.intAttributeName = intAttributeName; LOGGER.debug("Interrupt attribute set to [{}]",intAttributeName); } public void setTicketRegistrySupport(final TicketRegistrySupport ticketRegistrySupport) { this.ticketRegistrySupport = ticketRegistrySupport; } public void setJDBCCamel (final JDBCCamel jdbcCamel){ this.jdbcCamel = jdbcCamel; } public JDBCCamel getJDBCCamel (){ return this.jdbcCamel; } }
apache-2.0
luciapayo/RxDynamicSearch
app/src/main/java/com/lucilu/rxdynamicsearch/fragments/base/BaseFragment.java
1338
package com.lucilu.rxdynamicsearch.fragments.base; import com.lucilu.rxdynamicsearch.IInjectable; import com.lucilu.rxdynamicsearch.viewmodel.base.ViewModel; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import rx.subscriptions.CompositeSubscription; /** * This base fragment provides the common functionality to all fragments in the app. */ public abstract class BaseFragment extends Fragment implements IInjectable { @NonNull private final CompositeSubscription mSubscription = new CompositeSubscription(); @Override public void onActivityCreated(@Nullable final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); onInject(); getViewModel().subscribeToDataStore(); } @Override public void onResume() { super.onResume(); onBind(mSubscription); } @Override public void onPause() { mSubscription.clear(); super.onPause(); } @Override public void onDestroyView() { getViewModel().dispose(); super.onDestroyView(); } protected abstract void onBind(@NonNull final CompositeSubscription subscription); @NonNull protected abstract ViewModel getViewModel(); }
apache-2.0
yehchilai/IQ
Easy/246 Strobogrammatic Number.java
1026
/* This question is from https://leetcode.com/problems/strobogrammatic-number/ Difficulty: easy A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string. Example 1: Input: "69" Output: true Example 2: Input: "88" Output: true Example 3: Input: "962" Output: false */ // T:O(N), S:O(1), 1 ms class Solution { public boolean isStrobogrammatic(String num) { int[] pattern = new int[]{0,1,-1,-1,-1,-1,9,-1,8,6}; int len = num.length(); StringBuilder sb = new StringBuilder(); for(int i = len - 1; i >= 0; i--){ char c = num.charAt(i); // System.out.println(c+": "+pattern[c - '0']+", "+(char)pattern[c - '0']); if(pattern[c - '0'] == -1) return false; sb.append(pattern[c - '0']); } System.out.println(sb.toString()); return sb.toString().equals(num); } }
apache-2.0
Saulis/gerrit
gerrit-server/src/main/java/com/google/gerrit/server/project/RefControl.java
20772
// Copyright (C) 2010 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.project; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gerrit.common.data.AccessSection; import com.google.gerrit.common.data.Permission; import com.google.gerrit.common.data.PermissionRange; import com.google.gerrit.common.data.PermissionRule; import com.google.gerrit.common.data.RefConfigSection; import com.google.gerrit.common.errors.InvalidNameException; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.RefNames; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.InternalUser; import com.google.gerrit.server.group.SystemGroupBackend; import dk.brics.automaton.RegExp; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevTag; import org.eclipse.jgit.revwalk.RevWalk; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** Manages access control for Git references (aka branches, tags). */ public class RefControl { private final ProjectControl projectControl; private final String refName; /** All permissions that apply to this reference. */ private final PermissionCollection relevant; /** Cached set of permissions matching this user. */ private final Map<String, List<PermissionRule>> effective; private Boolean owner; private Boolean canForgeAuthor; private Boolean canForgeCommitter; private Boolean isVisible; RefControl(ProjectControl projectControl, String ref, PermissionCollection relevant) { this.projectControl = projectControl; this.refName = ref; this.relevant = relevant; this.effective = new HashMap<String, List<PermissionRule>>(); } public String getRefName() { return refName; } public ProjectControl getProjectControl() { return projectControl; } public CurrentUser getCurrentUser() { return projectControl.getCurrentUser(); } public RefControl forUser(CurrentUser who) { ProjectControl newCtl = projectControl.forUser(who); if (relevant.isUserSpecific()) { return newCtl.controlForRef(getRefName()); } else { return new RefControl(newCtl, getRefName(), relevant); } } /** Is this user a ref owner? */ public boolean isOwner() { if (owner == null) { if (canPerform(Permission.OWNER)) { owner = true; } else { owner = projectControl.isOwner(); } } return owner; } /** Can this user see this reference exists? */ public boolean isVisible() { if (isVisible == null) { isVisible = (getCurrentUser() instanceof InternalUser || canPerform(Permission.READ)) && canRead(); } return isVisible; } /** * True if this reference is visible by all REGISTERED_USERS */ public boolean isVisibleByRegisteredUsers() { List<PermissionRule> access = relevant.getPermission(Permission.READ); Set<ProjectRef> allows = Sets.newHashSet(); Set<ProjectRef> blocks = Sets.newHashSet(); for (PermissionRule rule : access) { if (rule.isBlock()) { blocks.add(relevant.getRuleProps(rule)); } else if (SystemGroupBackend.isAnonymousOrRegistered(rule.getGroup())) { allows.add(relevant.getRuleProps(rule)); } } blocks.removeAll(allows); return blocks.isEmpty() && !allows.isEmpty(); } /** * Determines whether the user can upload a change to the ref controlled by * this object. * * @return {@code true} if the user specified can upload a change to the Git * ref */ public boolean canUpload() { return projectControl.controlForRef("refs/for/" + getRefName()) .canPerform(Permission.PUSH) && canWrite(); } /** @return true if this user can submit merge patch sets to this ref */ public boolean canUploadMerges() { return projectControl.controlForRef("refs/for/" + getRefName()) .canPerform(Permission.PUSH_MERGE) && canWrite(); } /** @return true if this user can rebase changes on this ref */ public boolean canRebase() { return canPerform(Permission.REBASE) && canWrite(); } /** @return true if this user can submit patch sets to this ref */ public boolean canSubmit() { if (RefNames.REFS_CONFIG.equals(refName)) { // Always allow project owners to submit configuration changes. // Submitting configuration changes modifies the access control // rules. Allowing this to be done by a non-project-owner opens // a security hole enabling editing of access rules, and thus // granting of powers beyond submitting to the configuration. return projectControl.isOwner(); } return canPerform(Permission.SUBMIT) && canWrite(); } /** @return true if this user was granted submitAs to this ref */ public boolean canSubmitAs() { return canPerform(Permission.SUBMIT_AS); } /** @return true if the user can update the reference as a fast-forward. */ public boolean canUpdate() { if (RefNames.REFS_CONFIG.equals(refName) && !projectControl.isOwner()) { // Pushing requires being at least project owner, in addition to push. // Pushing configuration changes modifies the access control // rules. Allowing this to be done by a non-project-owner opens // a security hole enabling editing of access rules, and thus // granting of powers beyond pushing to the configuration. // On the AllProjects project the owner access right cannot be assigned, // this why for the AllProjects project we allow administrators to push // configuration changes if they have push without being project owner. if (!(projectControl.getProjectState().isAllProjects() && getCurrentUser().getCapabilities().canAdministrateServer())) { return false; } } return canPerform(Permission.PUSH) && canWrite(); } /** @return true if the user can rewind (force push) the reference. */ public boolean canForceUpdate() { return (canPushWithForce() || canDelete()) && canWrite(); } public boolean canWrite() { return getProjectControl().getProject().getState().equals( Project.State.ACTIVE); } public boolean canRead() { return getProjectControl().getProject().getState().equals( Project.State.READ_ONLY) || canWrite(); } private boolean canPushWithForce() { if (!canWrite() || (RefNames.REFS_CONFIG.equals(refName) && !projectControl.isOwner())) { // Pushing requires being at least project owner, in addition to push. // Pushing configuration changes modifies the access control // rules. Allowing this to be done by a non-project-owner opens // a security hole enabling editing of access rules, and thus // granting of powers beyond pushing to the configuration. return false; } return canForcePerform(Permission.PUSH); } /** * Determines whether the user can create a new Git ref. * * @param rw revision pool {@code object} was parsed in. * @param object the object the user will start the reference with. * @param existsOnServer the object exists on server or not. * @return {@code true} if the user specified can create a new Git ref */ public boolean canCreate(RevWalk rw, RevObject object, boolean existsOnServer) { if (!canWrite()) { return false; } boolean owner; boolean admin; switch (getCurrentUser().getAccessPath()) { case REST_API: case JSON_RPC: owner = isOwner(); admin = getCurrentUser().getCapabilities().canAdministrateServer(); break; default: owner = false; admin = false; } if (object instanceof RevCommit) { return admin || (owner && !isBlocked(Permission.CREATE)) || (canPerform(Permission.CREATE) && (!existsOnServer && canUpdate() || projectControl .canReadCommit(rw, (RevCommit) object))); } else if (object instanceof RevTag) { final RevTag tag = (RevTag) object; try { rw.parseBody(tag); } catch (IOException e) { return false; } // If tagger is present, require it matches the user's email. // final PersonIdent tagger = tag.getTaggerIdent(); if (tagger != null) { boolean valid; if (getCurrentUser().isIdentifiedUser()) { final IdentifiedUser user = (IdentifiedUser) getCurrentUser(); final String addr = tagger.getEmailAddress(); valid = user.getEmailAddresses().contains(addr); } else { valid = false; } if (!valid && !owner && !canForgeCommitter()) { return false; } } // If the tag has a PGP signature, allow a lower level of permission // than if it doesn't have a PGP signature. // if (tag.getFullMessage().contains("-----BEGIN PGP SIGNATURE-----\n")) { return owner || canPerform(Permission.PUSH_SIGNED_TAG); } else { return owner || canPerform(Permission.PUSH_TAG); } } else { return false; } } /** * Determines whether the user can delete the Git ref controlled by this * object. * * @return {@code true} if the user specified can delete a Git ref. */ public boolean canDelete() { if (!canWrite() || (RefNames.REFS_CONFIG.equals(refName))) { // Never allow removal of the refs/meta/config branch. // Deleting the branch would destroy all Gerrit specific // metadata about the project, including its access rules. // If a project is to be removed from Gerrit, its repository // should be removed first. return false; } switch (getCurrentUser().getAccessPath()) { case REST_API: case JSON_RPC: case SSH_COMMAND: return getCurrentUser().getCapabilities().canAdministrateServer() || (isOwner() && !isForceBlocked(Permission.PUSH)) || canPushWithForce(); case GIT: return canPushWithForce(); default: return false; } } /** @return true if this user can forge the author line in a commit. */ public boolean canForgeAuthor() { if (canForgeAuthor == null) { canForgeAuthor = canPerform(Permission.FORGE_AUTHOR); } return canForgeAuthor; } /** @return true if this user can forge the committer line in a commit. */ public boolean canForgeCommitter() { if (canForgeCommitter == null) { canForgeCommitter = canPerform(Permission.FORGE_COMMITTER); } return canForgeCommitter; } /** @return true if this user can forge the server on the committer line. */ public boolean canForgeGerritServerIdentity() { return canPerform(Permission.FORGE_SERVER); } /** @return true if this user can abandon a change for this ref */ public boolean canAbandon() { return canPerform(Permission.ABANDON); } /** @return true if this user can remove a reviewer for a change. */ public boolean canRemoveReviewer() { return canPerform(Permission.REMOVE_REVIEWER); } /** @return true if this user can view draft changes. */ public boolean canViewDrafts() { return canPerform(Permission.VIEW_DRAFTS); } /** @return true if this user can publish draft changes. */ public boolean canPublishDrafts() { return canPerform(Permission.PUBLISH_DRAFTS); } /** @return true if this user can delete draft changes. */ public boolean canDeleteDrafts() { return canPerform(Permission.DELETE_DRAFTS); } /** @return true if this user can edit topic names. */ public boolean canEditTopicName() { return canPerform(Permission.EDIT_TOPIC_NAME); } /** @return true if this user can force edit topic names. */ public boolean canForceEditTopicName() { return canForcePerform(Permission.EDIT_TOPIC_NAME); } /** All value ranges of any allowed label permission. */ public List<PermissionRange> getLabelRanges(boolean isChangeOwner) { List<PermissionRange> r = new ArrayList<PermissionRange>(); for (Map.Entry<String, List<PermissionRule>> e : relevant.getDeclaredPermissions()) { if (Permission.isLabel(e.getKey())) { int min = 0; int max = 0; for (PermissionRule rule : e.getValue()) { if (projectControl.match(rule, isChangeOwner)) { min = Math.min(min, rule.getMin()); max = Math.max(max, rule.getMax()); } } if (min != 0 || max != 0) { r.add(new PermissionRange(e.getKey(), min, max)); } } } return r; } /** The range of permitted values associated with a label permission. */ public PermissionRange getRange(String permission) { return getRange(permission, false); } /** The range of permitted values associated with a label permission. */ public PermissionRange getRange(String permission, boolean isChangeOwner) { if (Permission.hasRange(permission)) { return toRange(permission, access(permission, isChangeOwner)); } return null; } private static class AllowedRange { private int allowMin = 0; private int allowMax = 0; private int blockMin = Integer.MIN_VALUE; private int blockMax = Integer.MAX_VALUE; void update(PermissionRule rule) { if (rule.isBlock()) { blockMin = Math.max(blockMin, rule.getMin()); blockMax = Math.min(blockMax, rule.getMax()); } else { allowMin = Math.min(allowMin, rule.getMin()); allowMax = Math.max(allowMax, rule.getMax()); } } int getAllowMin() { return allowMin; } int getAllowMax() { return allowMax; } int getBlockMin() { // ALLOW wins over BLOCK on the same project return Math.min(blockMin, allowMin - 1); } int getBlockMax() { // ALLOW wins over BLOCK on the same project return Math.max(blockMax, allowMax + 1); } } private PermissionRange toRange(String permissionName, List<PermissionRule> ruleList) { Map<ProjectRef, AllowedRange> ranges = Maps.newHashMap(); for (PermissionRule rule : ruleList) { ProjectRef p = relevant.getRuleProps(rule); AllowedRange r = ranges.get(p); if (r == null) { r = new AllowedRange(); ranges.put(p, r); } r.update(rule); } int allowMin = 0; int allowMax = 0; int blockMin = Integer.MIN_VALUE; int blockMax = Integer.MAX_VALUE; for (AllowedRange r : ranges.values()) { allowMin = Math.min(allowMin, r.getAllowMin()); allowMax = Math.max(allowMax, r.getAllowMax()); blockMin = Math.max(blockMin, r.getBlockMin()); blockMax = Math.min(blockMax, r.getBlockMax()); } // BLOCK wins over ALLOW across projects int min = Math.max(allowMin, blockMin + 1); int max = Math.min(allowMax, blockMax - 1); return new PermissionRange(permissionName, min, max); } /** True if the user has this permission. Works only for non labels. */ boolean canPerform(String permissionName) { return doCanPerform(permissionName, false); } /** True if the user is blocked from using this permission. */ public boolean isBlocked(String permissionName) { return !doCanPerform(permissionName, true); } private boolean doCanPerform(String permissionName, boolean blockOnly) { List<PermissionRule> access = access(permissionName); Set<ProjectRef> allows = Sets.newHashSet(); Set<ProjectRef> blocks = Sets.newHashSet(); for (PermissionRule rule : access) { if (rule.isBlock() && !rule.getForce()) { blocks.add(relevant.getRuleProps(rule)); } else { allows.add(relevant.getRuleProps(rule)); } } blocks.removeAll(allows); return blocks.isEmpty() && (!allows.isEmpty() || blockOnly); } /** True if the user has force this permission. Works only for non labels. */ private boolean canForcePerform(String permissionName) { List<PermissionRule> access = access(permissionName); Set<ProjectRef> allows = Sets.newHashSet(); Set<ProjectRef> blocks = Sets.newHashSet(); for (PermissionRule rule : access) { if (rule.isBlock()) { blocks.add(relevant.getRuleProps(rule)); } else if (rule.getForce()) { allows.add(relevant.getRuleProps(rule)); } } blocks.removeAll(allows); return blocks.isEmpty() && !allows.isEmpty(); } /** True if for this permission force is blocked for the user. Works only for non labels. */ private boolean isForceBlocked(String permissionName) { List<PermissionRule> access = access(permissionName); Set<ProjectRef> allows = Sets.newHashSet(); Set<ProjectRef> blocks = Sets.newHashSet(); for (PermissionRule rule : access) { if (rule.isBlock()) { blocks.add(relevant.getRuleProps(rule)); } else if (rule.getForce()) { allows.add(relevant.getRuleProps(rule)); } } blocks.removeAll(allows); return !blocks.isEmpty(); } /** Rules for the given permission, or the empty list. */ private List<PermissionRule> access(String permissionName) { return access(permissionName, false); } /** Rules for the given permission, or the empty list. */ private List<PermissionRule> access(String permissionName, boolean isChangeOwner) { List<PermissionRule> rules = effective.get(permissionName); if (rules != null) { return rules; } rules = relevant.getPermission(permissionName); if (rules.isEmpty()) { effective.put(permissionName, rules); return rules; } if (rules.size() == 1) { if (!projectControl.match(rules.get(0), isChangeOwner)) { rules = Collections.emptyList(); } effective.put(permissionName, rules); return rules; } List<PermissionRule> mine = new ArrayList<PermissionRule>(rules.size()); for (PermissionRule rule : rules) { if (projectControl.match(rule, isChangeOwner)) { mine.add(rule); } } if (mine.isEmpty()) { mine = Collections.emptyList(); } effective.put(permissionName, mine); return mine; } public static boolean isRE(String refPattern) { return refPattern.startsWith(AccessSection.REGEX_PREFIX); } public static String shortestExample(String pattern) { if (isRE(pattern)) { // Since Brics will substitute dot [.] with \0 when generating // shortest example, any usage of dot will fail in // Repository.isValidRefName() if not combined with star [*]. // To get around this, we substitute the \0 with an arbitrary // accepted character. return toRegExp(pattern).toAutomaton().getShortestExample(true).replace('\0', '-'); } else if (pattern.endsWith("/*")) { return pattern.substring(0, pattern.length() - 1) + '1'; } else { return pattern; } } public static RegExp toRegExp(String refPattern) { if (isRE(refPattern)) { refPattern = refPattern.substring(1); } return new RegExp(refPattern, RegExp.NONE); } public static void validateRefPattern(String refPattern) throws InvalidNameException { if (refPattern.startsWith(RefConfigSection.REGEX_PREFIX)) { if (!Repository.isValidRefName(RefControl.shortestExample(refPattern))) { throw new InvalidNameException(refPattern); } } else if (refPattern.equals(RefConfigSection.ALL)) { // This is a special case we have to allow, it fails below. } else if (refPattern.endsWith("/*")) { String prefix = refPattern.substring(0, refPattern.length() - 2); if (!Repository.isValidRefName(prefix)) { throw new InvalidNameException(refPattern); } } else if (!Repository.isValidRefName(refPattern)) { throw new InvalidNameException(refPattern); } } }
apache-2.0
OSGP/Platform
osgp-adapter-domain-microgrids/src/main/java/org/opensmartgridplatform/adapter/domain/microgrids/infra/jms/core/OsgpCoreRequestMessageListener.java
2183
/** * Copyright 2016 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.adapter.domain.microgrids.infra.jms.core; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.opensmartgridplatform.shared.infra.jms.RequestMessage; import org.opensmartgridplatform.shared.infra.jms.UnknownMessageTypeException; // This class should fetch request messages from incoming requests queue of OSGP Core. @Component(value = "domainMicrogridsIncomingOsgpCoreRequestMessageListener") public class OsgpCoreRequestMessageListener implements MessageListener { private static final Logger LOGGER = LoggerFactory.getLogger(OsgpCoreRequestMessageListener.class); @Autowired @Qualifier(value = "domainMicrogridsIncomingOsgpCoreRequestMessageProcessor") private OsgpCoreRequestMessageProcessor osgpCoreRequestMessageProcessor; @Override public void onMessage(final Message message) { try { LOGGER.info("Received message"); final ObjectMessage objectMessage = (ObjectMessage) message; final String messageType = objectMessage.getJMSType(); final RequestMessage requestMessage = (RequestMessage) objectMessage.getObject(); this.osgpCoreRequestMessageProcessor.processMessage(requestMessage, messageType); } catch (final JMSException e) { // Can't read message. LOGGER.error("Exception: {}, StackTrace: {}", e.getMessage(), e.getStackTrace(), e); } catch (final UnknownMessageTypeException e) { // Don't know this message. LOGGER.error("UnknownMessageTypeException", e); } } }
apache-2.0
PkayJava/fintech
src/test/java/com/angkorteam/fintech/pages/teller/TellerCreatePageUITest.java
579
package com.angkorteam.fintech.pages.teller; import org.junit.Before; import org.junit.Test; import com.angkorteam.fintech.junit.JUnit; import com.angkorteam.fintech.junit.JUnitWicketTester; public class TellerCreatePageUITest { private JUnitWicketTester wicket; @Before public void before() { this.wicket = JUnit.getWicket(); } @Test public void visitPage() { this.wicket.login(); TellerCreatePage page = this.wicket.startPage(TellerCreatePage.class); this.wicket.assertRenderedPage(TellerCreatePage.class); } }
apache-2.0
Grrsun/sunweather
app/src/test/java/com/grr/sunweather/ExampleUnitTest.java
396
package com.grr.sunweather; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
GoogleCloudPlatform/training-data-analyst
courses/data_analysis/deepdive/pubsub-exercises/exercise2/solution/src/main/java/com/google/cloud/sme/pubsub/Subscriber.java
5078
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package com.google.cloud.sme.pubsub; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.google.api.gax.batching.FlowControlSettings; import com.google.cloud.pubsub.v1.AckReplyConsumer; import com.google.cloud.pubsub.v1.MessageReceiver; import com.google.pubsub.v1.ProjectSubscriptionName; import com.google.pubsub.v1.PubsubMessage; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.joda.time.DateTime; /** A basic Pub/Sub subscriber for purposes of demonstrating use of the API. */ public class Subscriber implements MessageReceiver { public static class Args { @Parameter( names = {"--project", "-p"}, required = true, description = "The Google Cloud Pub/Sub project in which the subscription exists.") public String project = null; @Parameter( names = {"--subscription", "-s"}, required = true, description = "The Google Cloud Pub/Sub subscription to which to subscribe.") public String subscription = null; } private static final String TOPIC = "pubsub-e2e-example"; private final Args args; private com.google.cloud.pubsub.v1.Subscriber subscriber; private ScheduledExecutorService executor; private AtomicLong receivedMessageCount = new AtomicLong(0); private AtomicLong processedMessageCount = new AtomicLong(0); private AtomicLong lastReceivedTimestamp = new AtomicLong(0); private Subscriber(Args args) { this.args = args; this.executor = Executors.newScheduledThreadPool(1000); ProjectSubscriptionName subscription = ProjectSubscriptionName.of(args.project, args.subscription); com.google.cloud.pubsub.v1.Subscriber.Builder builder = com.google.cloud.pubsub.v1.Subscriber.newBuilder(subscription, this); // Each mssage allocates a 5MB buffer upon receiving the message. Memory on // the JVM is limited to 1.2GB (see run.sh). Therefore, we can handle // approximately 1.2GB/5MB ~ 240 messages at a time. Round down to 200 to // account for other uses of memory. Since each message is the same 100 // bytes, we can also limit based on size, which woudl be 200 * 100 = 20,000 builder.setFlowControlSettings( FlowControlSettings.newBuilder() .setMaxOutstandingRequestBytes(2_000_000L) .setMaxOutstandingElementCount(200L) .build()); try { this.subscriber = builder.build(); } catch (Exception e) { System.out.println("Could not create subscriber: " + e); System.exit(1); } } @Override public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) { long receivedCount = receivedMessageCount.addAndGet(1); lastReceivedTimestamp.set(DateTime.now().getMillis()); if (receivedCount % 100 == 0) { System.out.println("Received " + receivedCount + " messages."); } byte[] extraBytes = new byte[5_000_000]; executor.schedule( () -> { long now = DateTime.now().getMillis(); // This is here just to keep a hold on extraBytes so it isn't deallocated yet. extraBytes[0] = (byte) now; consumer.ack(); long processedCount = processedMessageCount.addAndGet(1); if (processedCount % 100 == 0) { System.out.println("Processed " + processedCount + " messages."); } lastReceivedTimestamp.set(now); }, 30, TimeUnit.SECONDS); } private void run() { subscriber.startAsync(); while (true) { long now = DateTime.now().getMillis(); long lastReceived = lastReceivedTimestamp.get(); if (lastReceived > 0 && ((now - lastReceived) > 60000)) { subscriber.stopAsync(); break; } try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Error while waiting for completion: " + e); } } System.out.println("Subscriber has not received message in 60s. Stopping."); subscriber.awaitTerminated(); } public static void main(String[] args) { Args parsedArgs = new Args(); JCommander.newBuilder().addObject(parsedArgs).build().parse(args); Subscriber s = new Subscriber(parsedArgs); s.run(); System.exit(0); } }
apache-2.0
mdproctor/drools
drools-reteoo/src/main/java/org/drools/reteoo/nodes/ReteRightInputAdapterNode.java
7154
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.reteoo.nodes; import org.drools.core.RuleBaseConfiguration; import org.drools.core.base.DroolsQuery; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.common.Memory; import org.drools.core.reteoo.AccumulateNode.AccumulateMemory; import org.drools.core.reteoo.BetaMemory; import org.drools.core.reteoo.BetaNode; import org.drools.core.reteoo.LeftTuple; import org.drools.core.reteoo.LeftTupleSource; import org.drools.core.reteoo.NodeTypeEnums; import org.drools.core.reteoo.ObjectSink; import org.drools.core.reteoo.ReteooBuilder; import org.drools.core.reteoo.RightInputAdapterNode; import org.drools.core.reteoo.RightTuple; import org.drools.core.reteoo.RuleRemovalContext; import org.drools.core.reteoo.builder.BuildContext; import org.drools.core.spi.PropagationContext; import org.drools.core.util.Iterator; public class ReteRightInputAdapterNode extends RightInputAdapterNode { public ReteRightInputAdapterNode() { } public ReteRightInputAdapterNode(int id, LeftTupleSource source, LeftTupleSource startTupleSource, BuildContext context) { super(id, source, startTupleSource, context); } public void assertLeftTuple(final LeftTuple leftTuple, final PropagationContext context, final InternalWorkingMemory workingMemory) { // while we don't do anything with this, it's needed to serialization has a hook point // It will still keep the LT's in the serialization, but sucked form the child workingMemory.getNodeMemory( this ); // creating a dummy fact handle to wrap the tuple final InternalFactHandle handle = createFactHandle( leftTuple, context, workingMemory ); boolean useLeftMemory = true; if ( !isLeftTupleMemoryEnabled() ) { // This is a hack, to not add closed DroolsQuery objects Object object = leftTuple.get( 0 ).getObject(); if ( !(object instanceof DroolsQuery) || !((DroolsQuery) object).isOpen() ) { useLeftMemory = false; } } if ( useLeftMemory) { leftTuple.setContextObject( handle ); } // propagate it this.sink.propagateAssertObject( handle, context, workingMemory ); // if ( useLeftMemory) { // leftTuple.setObject( handle.getFirstRightTuple() ); // } } /** * Retracts the corresponding tuple by retrieving and retracting * the fact created for it */ public void retractLeftTuple(final LeftTuple tuple, final PropagationContext context, final InternalWorkingMemory workingMemory) { // retrieve handle from memory final InternalFactHandle factHandle = (InternalFactHandle) tuple.getContextObject(); factHandle.forEachRightTuple( rt -> rt.retractTuple( context, workingMemory ) ); factHandle.clearRightTuples(); factHandle.forEachLeftTuple( lt -> lt.retractTuple( context, workingMemory ) ); factHandle.clearLeftTuples(); } public void modifyLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) { // add it to a memory mapping InternalFactHandle handle = (InternalFactHandle) leftTuple.getContextObject(); // propagate it handle.forEachRightTuple( rt -> rt.modifyTuple( context, workingMemory ) ); } public void updateSink(final ObjectSink sink, final PropagationContext context, final InternalWorkingMemory workingMemory) { BetaNode betaNode = (BetaNode) this.sink.getSinks()[0]; Memory betaMemory = workingMemory.getNodeMemory( betaNode ); BetaMemory bm; if ( betaNode.getType() == NodeTypeEnums.AccumulateNode ) { bm = ((AccumulateMemory) betaMemory).getBetaMemory(); } else { bm = (BetaMemory) betaMemory; } // for RIA nodes, we need to store the ID of the created handles bm.getRightTupleMemory().iterator(); if ( bm.getRightTupleMemory().size() > 0 ) { final org.drools.core.util.Iterator it = bm.getRightTupleMemory().iterator(); for ( RightTuple entry = (RightTuple) it.next(); entry != null; entry = (RightTuple) it.next() ) { LeftTuple leftTuple = (LeftTuple) entry.getFactHandle().getObject(); InternalFactHandle handle = (InternalFactHandle) leftTuple.getContextObject(); sink.assertObject( handle, context, workingMemory ); } } } protected boolean doRemove(final RuleRemovalContext context, final ReteooBuilder builder, final InternalWorkingMemory[] workingMemories) { // this is now done by the child beta node, as it needs the child beta memory // if ( !this.isInUse() ) { // removeMemory(workingMemories); // } if ( !isInUse() ) { getLeftTupleSource().removeTupleSink(this); return true; } return false; } public void removeMemory(InternalWorkingMemory workingMemory) { BetaNode betaNode = (BetaNode) this.sink.getSinks()[0]; Memory betaMemory = workingMemory.getNodeMemory( betaNode ); BetaMemory bm; if ( betaNode.getType() == NodeTypeEnums.AccumulateNode ) { bm = ((AccumulateMemory) betaMemory).getBetaMemory(); } else { bm = (BetaMemory) betaMemory; } if ( bm.getRightTupleMemory().size() > 0 ) { final Iterator it = bm.getRightTupleMemory().iterator(); for ( RightTuple entry = (RightTuple) it.next(); entry != null; entry = (RightTuple) it.next() ) { LeftTuple leftTuple = (LeftTuple) entry.getFactHandle().getObject(); leftTuple.unlinkFromLeftParent(); leftTuple.unlinkFromRightParent(); } } workingMemory.clearNodeMemory( this ); } public RiaNodeMemory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) { return new RiaNodeMemory(); } }
apache-2.0
x251089003/EveryXDay
EveryXDay/src/main/java/com/xinxin/everyxday/widget/swipelistview/SwipeListViewListener.java
3114
/* * Copyright (C) 2013 47 Degrees, LLC * http://47deg.com * hello@47deg.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xinxin.everyxday.widget.swipelistview; /** * Listener to get callback notifications for the SwipeListView */ public interface SwipeListViewListener { /** * Called when open animation finishes * @param position of the view in the list * @param toRight Open to right */ void onOpened(int position, boolean toRight); /** * Called when close animation finishes * @param position of the view in the list * @param fromRight Close from right */ void onClosed(int position, boolean fromRight); /** * Called when the list changed */ void onListChanged(); /** * Called when user is moving an item * @param position of the view in the list * @param x Current position X */ void onMove(int position, float x); /** * Start open item * @param position of the view in the list * @param action current action * @param right to right */ void onStartOpen(int position, int action, boolean right); /** * Start close item * @param position of the view in the list * @param right */ void onStartClose(int position, boolean right); /** * Called when user clicks on the front view * @param position of the view in the list */ void onClickFrontView(int position); /** * Called when user clicks on the back view * @param position of the view in the list */ void onClickBackView(int position); /** * Called when user dismisses items * @param reverseSortedPositions Items dismissed */ void onDismiss(int[] reverseSortedPositions); /** * Used when user want to change swipe list mode on some rows. Return SWIPE_MODE_DEFAULT * if you don't want to change swipe list mode * @param position position that you want to change * @return type */ int onChangeSwipeMode(int position); /** * Called when user choice item * @param position of the view in the list that choice * @param selected if item is selected or not */ void onChoiceChanged(int position, boolean selected); /** * User start choice items */ void onChoiceStarted(); /** * User end choice items */ void onChoiceEnded(); /** * User is in first item of list */ void onFirstListItem(); /** * User is in last item of list */ void onLastListItem(); }
apache-2.0
xcyde/Java-A-to-Z
chapter_001/part_002/src/test/java/ru/CalculatorTest.java
1423
package ru; /** * Реализуем тест для класса Calculator * @author Aleksandr Belov * @date 23.09.2016 */ import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class CalculatorTest { /* * Тест сложения */ @Test public void whenAddShouldSummateIt() { final Calculator calc = new Calculator(); calc.add(1, 1); final double result = calc.getResult(); assertThat(result, is(2d)); } /* * Тест деления */ @Test public void whenDivShouldDivideIt() { final Calculator calc = new Calculator(); calc.div(2, 2); final double result = calc.getResult(); assertThat(result, is(1d)); } /* * Тест проверки исключения - деления на 0 */ @Test(expected=ArithmeticException.class) public void whenDivShouldNotDivideByZero() { final Calculator calc = new Calculator(); calc.div(1, 0); } /* * Тест вычитания */ @Test public void whenSubstractShouldSubstract() { final Calculator calc = new Calculator(); calc.substract(1, 1); final double result = calc.getResult(); assertThat(result, is(0d)); } /* * Тест умножения */ @Test public void whenMultiplyShouldMultiply() { final Calculator calc = new Calculator(); calc.multiply(3, 3); final double result = calc.getResult(); assertThat(result, is(9d)); } }
apache-2.0
googleapis/java-gkehub
proto-google-cloud-gkehub-v1alpha2/src/main/java/com/google/cloud/gkehub/v1alpha2/CreateMembershipRequest.java
38488
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/gkehub/v1alpha2/membership.proto package com.google.cloud.gkehub.v1alpha2; /** * * * <pre> * Request message for the `GkeHub.CreateMembership` method. * </pre> * * Protobuf type {@code google.cloud.gkehub.v1alpha2.CreateMembershipRequest} */ public final class CreateMembershipRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.gkehub.v1alpha2.CreateMembershipRequest) CreateMembershipRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateMembershipRequest.newBuilder() to construct. private CreateMembershipRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateMembershipRequest() { parent_ = ""; membershipId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateMembershipRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CreateMembershipRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); parent_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); membershipId_ = s; break; } case 26: { com.google.cloud.gkehub.v1alpha2.Membership.Builder subBuilder = null; if (resource_ != null) { subBuilder = resource_.toBuilder(); } resource_ = input.readMessage( com.google.cloud.gkehub.v1alpha2.Membership.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(resource_); resource_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.v1alpha2.MembershipProto .internal_static_google_cloud_gkehub_v1alpha2_CreateMembershipRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.v1alpha2.MembershipProto .internal_static_google_cloud_gkehub_v1alpha2_CreateMembershipRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest.class, com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; private volatile java.lang.Object parent_; /** * * * <pre> * Required. The parent (project and location) where the Memberships will be created. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent (project and location) where the Memberships will be created. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MEMBERSHIP_ID_FIELD_NUMBER = 2; private volatile java.lang.Object membershipId_; /** * * * <pre> * Required. Client chosen ID for the membership. `membership_id` must be a valid RFC * 1123 compliant DNS label: * 1. At most 63 characters in length * 2. It must consist of lower case alphanumeric characters or `-` * 3. It must start and end with an alphanumeric character * Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, * with a maximum length of 63 characters. * </pre> * * <code>string membership_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The membershipId. */ @java.lang.Override public java.lang.String getMembershipId() { java.lang.Object ref = membershipId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); membershipId_ = s; return s; } } /** * * * <pre> * Required. Client chosen ID for the membership. `membership_id` must be a valid RFC * 1123 compliant DNS label: * 1. At most 63 characters in length * 2. It must consist of lower case alphanumeric characters or `-` * 3. It must start and end with an alphanumeric character * Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, * with a maximum length of 63 characters. * </pre> * * <code>string membership_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for membershipId. */ @java.lang.Override public com.google.protobuf.ByteString getMembershipIdBytes() { java.lang.Object ref = membershipId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); membershipId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RESOURCE_FIELD_NUMBER = 3; private com.google.cloud.gkehub.v1alpha2.Membership resource_; /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the resource field is set. */ @java.lang.Override public boolean hasResource() { return resource_ != null; } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The resource. */ @java.lang.Override public com.google.cloud.gkehub.v1alpha2.Membership getResource() { return resource_ == null ? com.google.cloud.gkehub.v1alpha2.Membership.getDefaultInstance() : resource_; } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.gkehub.v1alpha2.MembershipOrBuilder getResourceOrBuilder() { return getResource(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(membershipId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, membershipId_); } if (resource_ != null) { output.writeMessage(3, getResource()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(membershipId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, membershipId_); } if (resource_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getResource()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest)) { return super.equals(obj); } com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest other = (com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getMembershipId().equals(other.getMembershipId())) return false; if (hasResource() != other.hasResource()) return false; if (hasResource()) { if (!getResource().equals(other.getResource())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + MEMBERSHIP_ID_FIELD_NUMBER; hash = (53 * hash) + getMembershipId().hashCode(); if (hasResource()) { hash = (37 * hash) + RESOURCE_FIELD_NUMBER; hash = (53 * hash) + getResource().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for the `GkeHub.CreateMembership` method. * </pre> * * Protobuf type {@code google.cloud.gkehub.v1alpha2.CreateMembershipRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.gkehub.v1alpha2.CreateMembershipRequest) com.google.cloud.gkehub.v1alpha2.CreateMembershipRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.v1alpha2.MembershipProto .internal_static_google_cloud_gkehub_v1alpha2_CreateMembershipRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.v1alpha2.MembershipProto .internal_static_google_cloud_gkehub_v1alpha2_CreateMembershipRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest.class, com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest.Builder.class); } // Construct using com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); parent_ = ""; membershipId_ = ""; if (resourceBuilder_ == null) { resource_ = null; } else { resource_ = null; resourceBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.gkehub.v1alpha2.MembershipProto .internal_static_google_cloud_gkehub_v1alpha2_CreateMembershipRequest_descriptor; } @java.lang.Override public com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest getDefaultInstanceForType() { return com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest build() { com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest buildPartial() { com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest result = new com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest(this); result.parent_ = parent_; result.membershipId_ = membershipId_; if (resourceBuilder_ == null) { result.resource_ = resource_; } else { result.resource_ = resourceBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest) { return mergeFrom((com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest other) { if (other == com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; onChanged(); } if (!other.getMembershipId().isEmpty()) { membershipId_ = other.membershipId_; onChanged(); } if (other.hasResource()) { mergeResource(other.getResource()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent (project and location) where the Memberships will be created. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent (project and location) where the Memberships will be created. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent (project and location) where the Memberships will be created. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; onChanged(); return this; } /** * * * <pre> * Required. The parent (project and location) where the Memberships will be created. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); onChanged(); return this; } /** * * * <pre> * Required. The parent (project and location) where the Memberships will be created. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; onChanged(); return this; } private java.lang.Object membershipId_ = ""; /** * * * <pre> * Required. Client chosen ID for the membership. `membership_id` must be a valid RFC * 1123 compliant DNS label: * 1. At most 63 characters in length * 2. It must consist of lower case alphanumeric characters or `-` * 3. It must start and end with an alphanumeric character * Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, * with a maximum length of 63 characters. * </pre> * * <code>string membership_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The membershipId. */ public java.lang.String getMembershipId() { java.lang.Object ref = membershipId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); membershipId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Client chosen ID for the membership. `membership_id` must be a valid RFC * 1123 compliant DNS label: * 1. At most 63 characters in length * 2. It must consist of lower case alphanumeric characters or `-` * 3. It must start and end with an alphanumeric character * Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, * with a maximum length of 63 characters. * </pre> * * <code>string membership_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for membershipId. */ public com.google.protobuf.ByteString getMembershipIdBytes() { java.lang.Object ref = membershipId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); membershipId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Client chosen ID for the membership. `membership_id` must be a valid RFC * 1123 compliant DNS label: * 1. At most 63 characters in length * 2. It must consist of lower case alphanumeric characters or `-` * 3. It must start and end with an alphanumeric character * Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, * with a maximum length of 63 characters. * </pre> * * <code>string membership_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The membershipId to set. * @return This builder for chaining. */ public Builder setMembershipId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } membershipId_ = value; onChanged(); return this; } /** * * * <pre> * Required. Client chosen ID for the membership. `membership_id` must be a valid RFC * 1123 compliant DNS label: * 1. At most 63 characters in length * 2. It must consist of lower case alphanumeric characters or `-` * 3. It must start and end with an alphanumeric character * Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, * with a maximum length of 63 characters. * </pre> * * <code>string membership_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearMembershipId() { membershipId_ = getDefaultInstance().getMembershipId(); onChanged(); return this; } /** * * * <pre> * Required. Client chosen ID for the membership. `membership_id` must be a valid RFC * 1123 compliant DNS label: * 1. At most 63 characters in length * 2. It must consist of lower case alphanumeric characters or `-` * 3. It must start and end with an alphanumeric character * Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, * with a maximum length of 63 characters. * </pre> * * <code>string membership_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for membershipId to set. * @return This builder for chaining. */ public Builder setMembershipIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); membershipId_ = value; onChanged(); return this; } private com.google.cloud.gkehub.v1alpha2.Membership resource_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.v1alpha2.Membership, com.google.cloud.gkehub.v1alpha2.Membership.Builder, com.google.cloud.gkehub.v1alpha2.MembershipOrBuilder> resourceBuilder_; /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the resource field is set. */ public boolean hasResource() { return resourceBuilder_ != null || resource_ != null; } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The resource. */ public com.google.cloud.gkehub.v1alpha2.Membership getResource() { if (resourceBuilder_ == null) { return resource_ == null ? com.google.cloud.gkehub.v1alpha2.Membership.getDefaultInstance() : resource_; } else { return resourceBuilder_.getMessage(); } } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setResource(com.google.cloud.gkehub.v1alpha2.Membership value) { if (resourceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } resource_ = value; onChanged(); } else { resourceBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setResource( com.google.cloud.gkehub.v1alpha2.Membership.Builder builderForValue) { if (resourceBuilder_ == null) { resource_ = builderForValue.build(); onChanged(); } else { resourceBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeResource(com.google.cloud.gkehub.v1alpha2.Membership value) { if (resourceBuilder_ == null) { if (resource_ != null) { resource_ = com.google.cloud.gkehub.v1alpha2.Membership.newBuilder(resource_) .mergeFrom(value) .buildPartial(); } else { resource_ = value; } onChanged(); } else { resourceBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearResource() { if (resourceBuilder_ == null) { resource_ = null; onChanged(); } else { resource_ = null; resourceBuilder_ = null; } return this; } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.gkehub.v1alpha2.Membership.Builder getResourceBuilder() { onChanged(); return getResourceFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.gkehub.v1alpha2.MembershipOrBuilder getResourceOrBuilder() { if (resourceBuilder_ != null) { return resourceBuilder_.getMessageOrBuilder(); } else { return resource_ == null ? com.google.cloud.gkehub.v1alpha2.Membership.getDefaultInstance() : resource_; } } /** * * * <pre> * Required. The membership to create. * </pre> * * <code> * .google.cloud.gkehub.v1alpha2.Membership resource = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.v1alpha2.Membership, com.google.cloud.gkehub.v1alpha2.Membership.Builder, com.google.cloud.gkehub.v1alpha2.MembershipOrBuilder> getResourceFieldBuilder() { if (resourceBuilder_ == null) { resourceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkehub.v1alpha2.Membership, com.google.cloud.gkehub.v1alpha2.Membership.Builder, com.google.cloud.gkehub.v1alpha2.MembershipOrBuilder>( getResource(), getParentForChildren(), isClean()); resource_ = null; } return resourceBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.gkehub.v1alpha2.CreateMembershipRequest) } // @@protoc_insertion_point(class_scope:google.cloud.gkehub.v1alpha2.CreateMembershipRequest) private static final com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest(); } public static com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateMembershipRequest> PARSER = new com.google.protobuf.AbstractParser<CreateMembershipRequest>() { @java.lang.Override public CreateMembershipRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CreateMembershipRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CreateMembershipRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateMembershipRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.gkehub.v1alpha2.CreateMembershipRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
LorenzReinhart/ONOSnew
apps/pce/app/src/main/java/org/onosproject/pce/pceservice/constraint/PceBandwidthConstraint.java
3582
/* * Copyright 2017-present Open Networking Laboratory * * 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.onosproject.pce.pceservice.constraint; import org.onlab.util.Bandwidth; import org.onlab.util.DataRateUnit; import org.onosproject.net.Link; import org.onosproject.net.intent.ResourceContext; import org.onosproject.net.intent.constraint.BooleanConstraint; import org.onosproject.bandwidthmgr.api.BandwidthMgmtService; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkNotNull; /** * Constraint that evaluates links based on available pce bandwidths. */ public final class PceBandwidthConstraint extends BooleanConstraint { private final Bandwidth bandwidth; /** * Creates a new pce bandwidth constraint. * * @param bandwidth required bandwidth */ public PceBandwidthConstraint(Bandwidth bandwidth) { this.bandwidth = checkNotNull(bandwidth, "Bandwidth cannot be null"); } /** * Creates a new pce bandwidth constraint. * * @param v required amount of bandwidth * @param unit {@link DataRateUnit} of {@code v} * @return {@link PceBandwidthConstraint} instance with given bandwidth requirement */ public static PceBandwidthConstraint of(double v, DataRateUnit unit) { return new PceBandwidthConstraint(Bandwidth.of(v, unit)); } // Constructor for serialization private PceBandwidthConstraint() { this.bandwidth = null; } @Override public boolean isValid(Link link, ResourceContext context) { return false; //Do nothing instead using isValidLink needs bandwidthMgmtService to validate link } /** * Validates the link based on pce bandwidth constraint. * * @param link to validate pce bandwidth constraint * @param bandwidthMgmtService instance of BandwidthMgmtService * @return true if link satisfies pce bandwidth constraint otherwise false */ public boolean isValidLink(Link link, BandwidthMgmtService bandwidthMgmtService) { if (bandwidthMgmtService == null) { return false; } return bandwidthMgmtService.isBandwidthAvailable(link, bandwidth.bps()); } /** * Returns the bandwidth required by this constraint. * * @return required bandwidth */ public Bandwidth bandwidth() { return bandwidth; } @Override public int hashCode() { return bandwidth.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final PceBandwidthConstraint other = (PceBandwidthConstraint) obj; return Objects.equals(this.bandwidth, other.bandwidth); } @Override public String toString() { return toStringHelper(this).add("bandwidth", bandwidth).toString(); } }
apache-2.0
Ile2/struts2-showcase-demo
src/core/src/main/java/com/opensymphony/xwork2/ognl/accessor/ParameterPropertyAccessor.java
1102
/** * */ package com.opensymphony.xwork2.ognl.accessor; import ognl.ObjectPropertyAccessor; import ognl.OgnlException; import org.apache.struts2.dispatcher.Parameter; import java.util.Map; public class ParameterPropertyAccessor extends ObjectPropertyAccessor { @Override public Object getProperty(Map context, Object target, Object oname) throws OgnlException { if (target instanceof Parameter) { if ("value".equalsIgnoreCase(String.valueOf(oname))) { throw new OgnlException("Access to " + oname + " is not allowed! Call parameter name directly!"); } return ((Parameter) target).getObject(); } return super.getProperty(context, target, oname); } @Override public void setProperty(Map context, Object target, Object oname, Object value) throws OgnlException { if (target instanceof Parameter) { throw new OgnlException("Access to " + target.getClass().getName() + " is read-only!"); } else { super.setProperty(context, target, oname, value); } } }
apache-2.0
OpenGamma/OG-Commons
modules/collect/src/test/java/com/opengamma/collect/named/MoreMockNameds.java
585
/** * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.collect.named; /** * Mock named object. */ class MoreMockNameds implements MockNamed { public static final MoreMockNameds MORE = new MoreMockNameds(); public static final String TEXT = "Not a constant"; static final MoreMockNameds NOT_PUBLIC = null; public final MoreMockNameds NOT_STATIC = null; public static MoreMockNameds NOT_FINAL = null; @Override public String getName() { return "More"; } }
apache-2.0
gitriver/nutch-learning
src/plugin/extractor/src/java/me/alad/nutch/html/extractor/model/Text.java
665
package me.alad.nutch.html.extractor.model; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import me.alad.nutch.html.extractor.evaluation.EvaluationContext; import org.apache.commons.lang3.Validate; @XmlRootElement public class Text extends Function { @Override public List<?> extract(Object root, EvaluationContext context) throws Exception { Validate.isTrue(args != null && args.size() == 1, "Only one arg should be specified"); List<?> res = args.get(0).extract(root, context); return context.getEvaluator().getText(context, res); } @Override public String toString() { return "Text [" + super.toString() + "]"; } }
apache-2.0
osiris-indoor/mapviewer-android
app/src/main/java/com/fhc25/percepcion/osiris/mapviewer/model/indoor/Office.java
1116
/** Copyright 2015 Osiris Project Team 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.fhc25.percepcion.osiris.mapviewer.model.indoor; import com.fhc25.percepcion.osiris.mapviewer.model.location.LineString; import java.io.Serializable; /** * Model class representing an office inside a building */ public class Office extends BuildingArea implements Serializable { /** * Default constructor * * @param id * @param name * @param geometry * @param level */ public Office(Long id, String name, LineString geometry, String level) { super(id, name, geometry, level); } }
apache-2.0
askneller/DestinationSol
main/src/org/destinationsol/game/screens/CollisionWarnDrawer.java
2268
/* * Copyright 2015 MovingBlocks * * 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.destinationsol.game.screens; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.RayCastCallback; import org.destinationsol.common.SolMath; import org.destinationsol.game.SolGame; import org.destinationsol.game.SolObject; import org.destinationsol.game.ship.SolShip; public class CollisionWarnDrawer extends WarnDrawer { private final MyRayBack myWarnCallback = new MyRayBack(); private SolShip myHero; public CollisionWarnDrawer(float r) { super(r, "Object Near"); } public boolean shouldWarn(SolGame game) { myHero = game.getHero(); if (myHero == null) return false; Vector2 pos = myHero.getPosition(); Vector2 spd = myHero.getSpd(); float acc = myHero.getAcc(); float spdLen = spd.len(); float spdAngle = SolMath.angle(spd); if (acc <= 0 || spdLen < 2 * acc) return false; // t = v/a; // s = att/2 = vv/a/2; float breakWay = spdLen * spdLen / acc / 2; breakWay += 2 * spdLen; Vector2 finalPos = SolMath.getVec(0, 0); SolMath.fromAl(finalPos, spdAngle, breakWay); finalPos.add(pos); myWarnCallback.show = false; game.getObjMan().getWorld().rayCast(myWarnCallback, pos, finalPos); SolMath.free(finalPos); return myWarnCallback.show; } private class MyRayBack implements RayCastCallback { private boolean show; @Override public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) { SolObject o = (SolObject) fixture.getBody().getUserData(); if (myHero == o) { return -1; } show = true; return 0; } } }
apache-2.0
zhe-thoughts/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java
13504
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.scheduler; import java.io.IOException; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.exceptions.InvalidResourceRequestException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.security.AccessType; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.common.collect.Sets; /** * Utilities shared by schedulers. */ @Private @Unstable public class SchedulerUtils { private static final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public static final String RELEASED_CONTAINER = "Container released by application"; public static final String LOST_CONTAINER = "Container released on a *lost* node"; public static final String PREEMPTED_CONTAINER = "Container preempted by scheduler"; public static final String COMPLETED_APPLICATION = "Container of a completed application"; public static final String EXPIRED_CONTAINER = "Container expired since it was unused"; public static final String UNRESERVED_CONTAINER = "Container reservation no longer required."; /** * Utility to create a {@link ContainerStatus} during exceptional * circumstances. * * @param containerId {@link ContainerId} of returned/released/lost container. * @param diagnostics diagnostic message * @return <code>ContainerStatus</code> for an returned/released/lost * container */ public static ContainerStatus createAbnormalContainerStatus( ContainerId containerId, String diagnostics) { return createAbnormalContainerStatus(containerId, ContainerExitStatus.ABORTED, diagnostics); } /** * Utility to create a {@link ContainerStatus} during exceptional * circumstances. * * @param containerId {@link ContainerId} of returned/released/lost container. * @param diagnostics diagnostic message * @return <code>ContainerStatus</code> for an returned/released/lost * container */ public static ContainerStatus createPreemptedContainerStatus( ContainerId containerId, String diagnostics) { return createAbnormalContainerStatus(containerId, ContainerExitStatus.PREEMPTED, diagnostics); } /** * Utility to create a {@link ContainerStatus} during exceptional * circumstances. * * @param containerId {@link ContainerId} of returned/released/lost container. * @param diagnostics diagnostic message * @return <code>ContainerStatus</code> for an returned/released/lost * container */ private static ContainerStatus createAbnormalContainerStatus( ContainerId containerId, int exitStatus, String diagnostics) { ContainerStatus containerStatus = recordFactory.newRecordInstance(ContainerStatus.class); containerStatus.setContainerId(containerId); containerStatus.setDiagnostics(diagnostics); containerStatus.setExitStatus(exitStatus); containerStatus.setState(ContainerState.COMPLETE); return containerStatus; } /** * Utility method to normalize a list of resource requests, by insuring that * the memory for each request is a multiple of minMemory and is not zero. */ public static void normalizeRequests( List<ResourceRequest> asks, ResourceCalculator resourceCalculator, Resource clusterResource, Resource minimumResource, Resource maximumResource) { for (ResourceRequest ask : asks) { normalizeRequest( ask, resourceCalculator, clusterResource, minimumResource, maximumResource, minimumResource); } } /** * Utility method to normalize a resource request, by insuring that the * requested memory is a multiple of minMemory and is not zero. */ public static void normalizeRequest( ResourceRequest ask, ResourceCalculator resourceCalculator, Resource clusterResource, Resource minimumResource, Resource maximumResource) { Resource normalized = Resources.normalize( resourceCalculator, ask.getCapability(), minimumResource, maximumResource, minimumResource); ask.setCapability(normalized); } /** * Utility method to normalize a list of resource requests, by insuring that * the memory for each request is a multiple of minMemory and is not zero. */ public static void normalizeRequests( List<ResourceRequest> asks, ResourceCalculator resourceCalculator, Resource clusterResource, Resource minimumResource, Resource maximumResource, Resource incrementResource) { for (ResourceRequest ask : asks) { normalizeRequest( ask, resourceCalculator, clusterResource, minimumResource, maximumResource, incrementResource); } } /** * Utility method to normalize a resource request, by insuring that the * requested memory is a multiple of minMemory and is not zero. */ public static void normalizeRequest( ResourceRequest ask, ResourceCalculator resourceCalculator, Resource clusterResource, Resource minimumResource, Resource maximumResource, Resource incrementResource) { Resource normalized = Resources.normalize( resourceCalculator, ask.getCapability(), minimumResource, maximumResource, incrementResource); ask.setCapability(normalized); } /** * Utility method to validate a resource request, by insuring that the * requested memory/vcore is non-negative and not greater than max * * @throws <code>InvalidResourceRequestException</code> when there is invalid * request */ public static void validateResourceRequest(ResourceRequest resReq, Resource maximumResource, String queueName, YarnScheduler scheduler) throws InvalidResourceRequestException { if (resReq.getCapability().getMemory() < 0 || resReq.getCapability().getMemory() > maximumResource.getMemory()) { throw new InvalidResourceRequestException("Invalid resource request" + ", requested memory < 0" + ", or requested memory > max configured" + ", requestedMemory=" + resReq.getCapability().getMemory() + ", maxMemory=" + maximumResource.getMemory()); } if (resReq.getCapability().getVirtualCores() < 0 || resReq.getCapability().getVirtualCores() > maximumResource.getVirtualCores()) { throw new InvalidResourceRequestException("Invalid resource request" + ", requested virtual cores < 0" + ", or requested virtual cores > max configured" + ", requestedVirtualCores=" + resReq.getCapability().getVirtualCores() + ", maxVirtualCores=" + maximumResource.getVirtualCores()); } // Get queue from scheduler QueueInfo queueInfo = null; try { queueInfo = scheduler.getQueueInfo(queueName, false, false); } catch (IOException e) { // it is possible queue cannot get when queue mapping is set, just ignore // the queueInfo here, and move forward } // check labels in the resource request. String labelExp = resReq.getNodeLabelExpression(); // if queue has default label expression, and RR doesn't have, use the // default label expression of queue if (labelExp == null && queueInfo != null && ResourceRequest.ANY.equals(resReq.getResourceName())) { labelExp = queueInfo.getDefaultNodeLabelExpression(); resReq.setNodeLabelExpression(labelExp); } // we don't allow specify label expression other than resourceName=ANY now if (!ResourceRequest.ANY.equals(resReq.getResourceName()) && labelExp != null && !labelExp.trim().isEmpty()) { throw new InvalidResourceRequestException( "Invailid resource request, queue=" + queueInfo.getQueueName() + " specified node label expression in a " + "resource request has resource name = " + resReq.getResourceName()); } // we don't allow specify label expression with more than one node labels now if (labelExp != null && labelExp.contains("&&")) { throw new InvalidResourceRequestException( "Invailid resource request, queue=" + queueInfo.getQueueName() + " specified more than one node label " + "in a node label expression, node label expression = " + labelExp); } if (labelExp != null && !labelExp.trim().isEmpty() && queueInfo != null) { if (!checkQueueLabelExpression(queueInfo.getAccessibleNodeLabels(), labelExp)) { throw new InvalidResourceRequestException("Invalid resource request" + ", queue=" + queueInfo.getQueueName() + " doesn't have permission to access all labels " + "in resource request. labelExpression of resource request=" + labelExp + ". Queue labels=" + (queueInfo.getAccessibleNodeLabels() == null ? "" : StringUtils.join(queueInfo .getAccessibleNodeLabels().iterator(), ','))); } } } public static boolean checkQueueAccessToNode(Set<String> queueLabels, Set<String> nodeLabels) { // if queue's label is *, it can access any node if (queueLabels != null && queueLabels.contains(RMNodeLabelsManager.ANY)) { return true; } // any queue can access to a node without label if (nodeLabels == null || nodeLabels.isEmpty()) { return true; } // a queue can access to a node only if it contains any label of the node if (queueLabels != null && Sets.intersection(queueLabels, nodeLabels).size() > 0) { return true; } // sorry, you cannot access return false; } public static void checkIfLabelInClusterNodeLabels(RMNodeLabelsManager mgr, Set<String> labels) throws IOException { if (mgr == null) { if (labels != null && !labels.isEmpty()) { throw new IOException("NodeLabelManager is null, please check"); } return; } if (labels != null) { for (String label : labels) { if (!label.equals(RMNodeLabelsManager.ANY) && !mgr.containsNodeLabel(label)) { throw new IOException("NodeLabelManager doesn't include label = " + label + ", please check."); } } } } public static boolean checkNodeLabelExpression(Set<String> nodeLabels, String labelExpression) { // empty label expression can only allocate on node with empty labels if (labelExpression == null || labelExpression.trim().isEmpty()) { if (!nodeLabels.isEmpty()) { return false; } } if (labelExpression != null) { for (String str : labelExpression.split("&&")) { if (!str.trim().isEmpty() && (nodeLabels == null || !nodeLabels.contains(str.trim()))) { return false; } } } return true; } public static boolean checkQueueLabelExpression(Set<String> queueLabels, String labelExpression) { if (queueLabels != null && queueLabels.contains(RMNodeLabelsManager.ANY)) { return true; } // if label expression is empty, we can allocate container on any node if (labelExpression == null) { return true; } for (String str : labelExpression.split("&&")) { if (!str.trim().isEmpty() && (queueLabels == null || !queueLabels.contains(str.trim()))) { return false; } } return true; } public static AccessType toAccessType(QueueACL acl) { switch (acl) { case ADMINISTER_QUEUE: return AccessType.ADMINISTER_QUEUE; case SUBMIT_APPLICATIONS: return AccessType.SUBMIT_APP; } return null; } }
apache-2.0
anthonime/testbot
src/main/java/com/github/anthonime/testbot/runtime/elements/webdriver/WebElementSupplier.java
955
package com.github.anthonime.testbot.runtime.elements.webdriver; import com.github.anthonime.testbot.runtime.elements.HasWebPageContext; import com.github.anthonime.testbot.runtime.elements.exceptions.MultipleElementsException; import com.github.anthonime.testbot.runtime.elements.exceptions.NoSuchElementException; import org.openqa.selenium.WebElement; /** * Created by schio on 9/16/2017. */ public interface WebElementSupplier extends HasWebPageContext { /** * The description of the way to find the elements * * @return */ String getDescription(); /** * Return the WebElement if it is immediately present and if it is single. * * @return the webelement, if present * @throws NoSuchElementException if the element is not present * @throws MultipleElementsException it several elements are found */ WebElement get() throws NoSuchElementException, MultipleElementsException; }
apache-2.0
sjones4/you-are-sdk
src/main/java/com/github/sjones4/youcan/youtoken/model/transform/GetImpersonationTokenRequestMarshaller.java
2138
/* * Copyright 2014 Steve Jones. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.github.sjones4.youcan.youtoken.model.transform; import com.amazonaws.AmazonClientException; import com.amazonaws.DefaultRequest; import com.amazonaws.Request; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; import com.github.sjones4.youcan.youtoken.model.GetImpersonationTokenRequest; /** * */ public class GetImpersonationTokenRequestMarshaller implements Marshaller<Request<GetImpersonationTokenRequest>, GetImpersonationTokenRequest> { public Request<GetImpersonationTokenRequest> marshall(GetImpersonationTokenRequest getImpersonationTokenRequest) { if (getImpersonationTokenRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<GetImpersonationTokenRequest> request = new DefaultRequest<GetImpersonationTokenRequest>(getImpersonationTokenRequest, "AWSSecurityTokenService"); request.addParameter("Action", "GetImpersonationToken"); request.addParameter("Version", "2011-06-15"); if (getImpersonationTokenRequest.getAccountAlias() != null) { request.addParameter("AccountAlias", StringUtils.fromString( getImpersonationTokenRequest.getAccountAlias() )); } if (getImpersonationTokenRequest.getUserName() != null) { request.addParameter("UserName", StringUtils.fromString(getImpersonationTokenRequest.getUserName())); } if (getImpersonationTokenRequest.getUserId() != null) { request.addParameter("UserId", StringUtils.fromString(getImpersonationTokenRequest.getUserId())); } return request; } }
apache-2.0
Wechat-Group/WxJava
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/message/WxCpMessageSendStatistics.java
1133
package me.chanjar.weixin.cp.bean.message; import com.google.gson.annotations.SerializedName; import lombok.Data; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; import java.io.Serializable; import java.util.List; /** * 应用消息发送统计信息. * * @author <a href="https://github.com/binarywang">Binary Wang</a> * @date 2020-09-13 */ @Data public class WxCpMessageSendStatistics implements Serializable { private static final long serialVersionUID = 6031833682211475786L; public static WxCpMessageSendStatistics fromJson(String json) { return WxCpGsonBuilder.create().fromJson(json, WxCpMessageSendStatistics.class); } private List<StatisticItem> statistics; @Data public static class StatisticItem implements Serializable { private static final long serialVersionUID = 6031833682211475786L; /** * 应用名 */ @SerializedName("app_name") private String appName; /** * 应用id */ @SerializedName("agentid") private Integer agentId; /** * 发消息成功人次 */ @SerializedName("count") private Integer count; } }
apache-2.0
VirtualGamer/SnowEngine
Dependencies/stb/src/org/lwjgl/stb/STBTTAlignedQuad.java
10764
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.stb; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * Quad used for drawing a baked character, returned by {@link STBTruetype#stbtt_GetBakedQuad}. * * <h3>Layout</h3> * * <pre><code>struct stbtt_aligned_quad { float x0; float y0; float s0; float t0; float x1; float y1; float s1; float t1; }</code></pre> */ public class STBTTAlignedQuad extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; public static final int ALIGNOF; /** The struct member offsets. */ public static final int X0, Y0, S0, T0, X1, Y1, S1, T1; static { Layout layout = __struct( __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); X0 = layout.offsetof(0); Y0 = layout.offsetof(1); S0 = layout.offsetof(2); T0 = layout.offsetof(3); X1 = layout.offsetof(4); Y1 = layout.offsetof(5); S1 = layout.offsetof(6); T1 = layout.offsetof(7); } STBTTAlignedQuad(long address, ByteBuffer container) { super(address, container); } /** * Creates a {@link STBTTAlignedQuad} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public STBTTAlignedQuad(ByteBuffer container) { this(memAddress(container), checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** Returns the value of the {@code x0} field. */ public float x0() { return nx0(address()); } /** Returns the value of the {@code y0} field. */ public float y0() { return ny0(address()); } /** Returns the value of the {@code s0} field. */ public float s0() { return ns0(address()); } /** Returns the value of the {@code t0} field. */ public float t0() { return nt0(address()); } /** Returns the value of the {@code x1} field. */ public float x1() { return nx1(address()); } /** Returns the value of the {@code y1} field. */ public float y1() { return ny1(address()); } /** Returns the value of the {@code s1} field. */ public float s1() { return ns1(address()); } /** Returns the value of the {@code t1} field. */ public float t1() { return nt1(address()); } // ----------------------------------- /** Returns a new {@link STBTTAlignedQuad} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static STBTTAlignedQuad malloc() { return create(nmemAlloc(SIZEOF)); } /** Returns a new {@link STBTTAlignedQuad} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static STBTTAlignedQuad calloc() { return create(nmemCalloc(1, SIZEOF)); } /** Returns a new {@link STBTTAlignedQuad} instance allocated with {@link BufferUtils}. */ public static STBTTAlignedQuad create() { return new STBTTAlignedQuad(BufferUtils.createByteBuffer(SIZEOF)); } /** Returns a new {@link STBTTAlignedQuad} instance for the specified memory address or {@code null} if the address is {@code NULL}. */ public static STBTTAlignedQuad create(long address) { return address == NULL ? null : new STBTTAlignedQuad(address, null); } /** * Returns a new {@link STBTTAlignedQuad.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static Buffer malloc(int capacity) { return create(nmemAlloc(capacity * SIZEOF), capacity); } /** * Returns a new {@link STBTTAlignedQuad.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static Buffer calloc(int capacity) { return create(nmemCalloc(capacity, SIZEOF), capacity); } /** * Returns a new {@link STBTTAlignedQuad.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static Buffer create(int capacity) { return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF)); } /** * Create a {@link STBTTAlignedQuad.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static Buffer create(long address, int capacity) { return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity); } // ----------------------------------- /** Returns a new {@link STBTTAlignedQuad} instance allocated on the thread-local {@link MemoryStack}. */ public static STBTTAlignedQuad mallocStack() { return mallocStack(stackGet()); } /** Returns a new {@link STBTTAlignedQuad} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */ public static STBTTAlignedQuad callocStack() { return callocStack(stackGet()); } /** * Returns a new {@link STBTTAlignedQuad} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static STBTTAlignedQuad mallocStack(MemoryStack stack) { return create(stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@link STBTTAlignedQuad} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static STBTTAlignedQuad callocStack(MemoryStack stack) { return create(stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link STBTTAlignedQuad.Buffer} instance allocated on the thread-local {@link MemoryStack}. * * @param capacity the buffer capacity */ public static Buffer mallocStack(int capacity) { return mallocStack(capacity, stackGet()); } /** * Returns a new {@link STBTTAlignedQuad.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. * * @param capacity the buffer capacity */ public static Buffer callocStack(int capacity) { return callocStack(capacity, stackGet()); } /** * Returns a new {@link STBTTAlignedQuad.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static Buffer mallocStack(int capacity, MemoryStack stack) { return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link STBTTAlignedQuad.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static Buffer callocStack(int capacity, MemoryStack stack) { return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #x0}. */ public static float nx0(long struct) { return memGetFloat(struct + STBTTAlignedQuad.X0); } /** Unsafe version of {@link #y0}. */ public static float ny0(long struct) { return memGetFloat(struct + STBTTAlignedQuad.Y0); } /** Unsafe version of {@link #s0}. */ public static float ns0(long struct) { return memGetFloat(struct + STBTTAlignedQuad.S0); } /** Unsafe version of {@link #t0}. */ public static float nt0(long struct) { return memGetFloat(struct + STBTTAlignedQuad.T0); } /** Unsafe version of {@link #x1}. */ public static float nx1(long struct) { return memGetFloat(struct + STBTTAlignedQuad.X1); } /** Unsafe version of {@link #y1}. */ public static float ny1(long struct) { return memGetFloat(struct + STBTTAlignedQuad.Y1); } /** Unsafe version of {@link #s1}. */ public static float ns1(long struct) { return memGetFloat(struct + STBTTAlignedQuad.S1); } /** Unsafe version of {@link #t1}. */ public static float nt1(long struct) { return memGetFloat(struct + STBTTAlignedQuad.T1); } // ----------------------------------- /** An array of {@link STBTTAlignedQuad} structs. */ public static class Buffer extends StructBuffer<STBTTAlignedQuad, Buffer> implements NativeResource { /** * Creates a new {@link STBTTAlignedQuad.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link STBTTAlignedQuad#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) { return new Buffer(address, container, mark, pos, lim, cap); } @Override protected STBTTAlignedQuad newInstance(long address) { return new STBTTAlignedQuad(address, container); } @Override protected int sizeof() { return SIZEOF; } /** Returns the value of the {@code x0} field. */ public float x0() { return STBTTAlignedQuad.nx0(address()); } /** Returns the value of the {@code y0} field. */ public float y0() { return STBTTAlignedQuad.ny0(address()); } /** Returns the value of the {@code s0} field. */ public float s0() { return STBTTAlignedQuad.ns0(address()); } /** Returns the value of the {@code t0} field. */ public float t0() { return STBTTAlignedQuad.nt0(address()); } /** Returns the value of the {@code x1} field. */ public float x1() { return STBTTAlignedQuad.nx1(address()); } /** Returns the value of the {@code y1} field. */ public float y1() { return STBTTAlignedQuad.ny1(address()); } /** Returns the value of the {@code s1} field. */ public float s1() { return STBTTAlignedQuad.ns1(address()); } /** Returns the value of the {@code t1} field. */ public float t1() { return STBTTAlignedQuad.nt1(address()); } } }
apache-2.0
Smartlogic-Semaphore-Limited/Java-APIs
Semaphore-OE-Batch-Tools/src/main/java/com/smartlogic/ModelLoader.java
3924
package com.smartlogic; import org.apache.jena.ext.com.google.common.base.Preconditions; import org.apache.jena.ext.com.google.common.base.Strings; import org.apache.jena.query.Dataset; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.tdb.TDBFactory; import org.apache.jena.tdb.TDBLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * Utilities class for fetching and loading RDF models into Jena models. */ public class ModelLoader { /** * Logger */ static Logger logger = LoggerFactory.getLogger(ModelLoader.class); /** * Fetch a model from Ontology Editor, load and return as TDB-backed Jena model. * * @param endpoint * @param tDbDirectoryPath * @return * @throws OEConnectionException * @throws IOException */ public static Model loadOEModelToTdb(OEModelEndpoint endpoint, String tDbDirectoryPath) throws IOException, OEConnectionException, InterruptedException { Preconditions.checkNotNull(endpoint); Preconditions.checkArgument(!Strings.isNullOrEmpty(tDbDirectoryPath)); if (logger.isDebugEnabled()) { logger.debug("OEModelEndpoint: {}", endpoint); logger.debug("TDB Dir path : {}", tDbDirectoryPath); } Dataset dataset = TDBFactory.createDataset(tDbDirectoryPath); Model model = dataset.getNamedModel(endpoint.modelIri); return endpoint.fetchData(model); } /** * Fetch a model from Ontology Editor, load and return as memory-backed Jena model. * * @param endpoint * @return * @throws OEConnectionException * @throws IOException */ public static Model loadOEModelToMem(OEModelEndpoint endpoint) throws IOException, OEConnectionException, InterruptedException { Preconditions.checkNotNull(endpoint); logger.debug("OEModelEndpoint base URL: {}", endpoint.baseUrl); return endpoint.fetchData(null); } /** * Fetch a model at the specified URI, load and return an TDB-backed Jena model. * * @param rdfUri * @param modelId * @param tDbDirectoryPath * @return */ public static Model loadModelToTdb(String rdfUri, String modelId, String tDbDirectoryPath) { if (logger.isDebugEnabled()) { logger.debug("RDF URI : {}", rdfUri); logger.debug("Model ID: {}", modelId); logger.debug("TDB DIR: {}", tDbDirectoryPath); } Dataset dataset = TDBFactory.createDataset(tDbDirectoryPath); Model model = dataset.getNamedModel(modelId); TDBLoader.loadModel(model, rdfUri); return model; } /** * Creates a new model, adds the specified model to it, and returns the new model. * @param inModel * @return */ public static Model loadModelToMem(Model inModel) { Model newModel = ModelFactory.createDefaultModel(); newModel.add(inModel); return newModel; } /** * Return an new TDB-backed Jena model with the specified model added. * * @param inModel * @param modelId * @param tDbDirectoryPath * @return */ public static Model loadModelToTdb(Model inModel, String modelId, String tDbDirectoryPath) { if (logger.isDebugEnabled()) { logger.debug("Model : <object>"); logger.debug("Model ID: {}", modelId); logger.debug("TDB DIR: {}", tDbDirectoryPath); } Dataset dataset = TDBFactory.createDataset(tDbDirectoryPath); Model model = dataset.getNamedModel(modelId); model.add(inModel); return model; } /** * Fetch a model at the specified URI, load, and return a memory-backed Jena model. * @param rdfUri * @return */ public static Model loadModelToMem(String rdfUri) { Preconditions.checkArgument(!Strings.isNullOrEmpty(rdfUri)); if (logger.isDebugEnabled()) { logger.debug("Model load URI: {}", rdfUri); } return RDFDataMgr.loadModel(rdfUri); } }
apache-2.0
mayuranchalia/swagger4j
src/main/java/com/smartbear/swagger4j/Swagger.java
4617
/** * Copyright 2013 SmartBear Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.smartbear.swagger4j; import com.smartbear.swagger4j.impl.SwaggerFactoryImpl; import java.io.IOException; import java.net.URI; import java.util.Iterator; import static java.util.ServiceLoader.load; /** * Utility methods to read/write/create Swagger objects */ public class Swagger { /** * Avoid instantiation */ private Swagger() { } /** * Creates an empty ResourceListing with the specified basePath - uses the standard SwaggerFactory * * @param swaggerVersion the Swagger version to use * @return an empty ResourceListing */ public static ResourceListing createResourceListing(SwaggerVersion swaggerVersion) { return createSwaggerFactory().createResourceListing(swaggerVersion); } /** * Creates an empty ApiDeclaration with the specified basePath and resourcePath * * @param basePath used to resolve API paths defined in this declaration * @param resourcePath path to the actual resource described in the declaration * @return an empty ApiDeclaration */ public static ApiDeclaration createApiDeclaration(String basePath, String resourcePath) { return createSwaggerFactory().createApiDeclaration(basePath, resourcePath); } /** * Creates a SwaggerReader using the available SwaggerFactory * * @return a SwaggerReader */ public static SwaggerReader createReader() { return createSwaggerFactory().createSwaggerReader(); } /** * Reads a Swagger definition from the specified URI, uses the default SwaggerReader implementation * * @param uri the URI of the api-docs document defining the Swagger ResourceListing * @return the initialized ResourceListing object * @throws IOException */ public static ResourceListing readSwagger( URI uri ) throws IOException { return createReader().readResourceListing( uri ); } /** * Writes the specified Swagger ResourceListing to the specified local path in json format. Uses the default SwaggerWriter * * @param resourceListing the resourceListing to write * @param path path to an existing folder where the api-docs and api declarations will be written * @throws IOException */ public static void writeSwagger( ResourceListing resourceListing, String path ) throws IOException { writeSwagger( resourceListing, path, SwaggerFormat.json ); } /** * Writes the specified Swagger ResourceListing to the specified local path in either json or xml format. * Uses the default SwaggerWriter * * @param resourceListing the resourceListing to write * @param path path to an existing folder where the api-docs and api declarations will be written * @param format the format to use; either json or xml * @throws IOException */ public static void writeSwagger( ResourceListing resourceListing, String path, SwaggerFormat format ) throws IOException { createWriter( format ).writeSwagger( new FileSwaggerStore( path ), resourceListing ); } /** * Creates a SwaggerWriter for the specified format using the default SwaggerFactory * * @param format the format the writer should use, either json or xml * @return the created SwaggerWriter */ public static SwaggerWriter createWriter(SwaggerFormat format) { return createSwaggerFactory().createSwaggerWriter(format); } /** * method for creating a SwaggerFactory; uses java.util.ServiceLoader to find a SwaggerFactory * implementation - falls back to the default implementation if none are found * * @return a SwaggerFactory instance */ public static SwaggerFactory createSwaggerFactory() { Iterator<SwaggerFactory> iterator = load(SwaggerFactory.class).iterator(); if (iterator.hasNext()) { return iterator.next(); } return new SwaggerFactoryImpl(); } }
apache-2.0
alexhilton/miscellaneous
java/Exercises/src/exercises/net/DailyAdviceServer.java
1174
/** * */ package exercises.net; import java.net.*; import java.io.*; /** * @author gongzhihui * */ public class DailyAdviceServer { private String[] adviceList = { "Take smaller bites", // 0 "Go for the tight jeans. No they do not make you look fat", // 1 "One word: inappropriate", // 2 "Just for today, be honest. Tell your boss what you really think", // 3 "You might want to rethink that haircut" // 4 }; public void go() { try { ServerSocket serverSock = new ServerSocket(4242); while (true) { Socket sock = serverSock.accept(); PrintWriter writer = new PrintWriter(sock.getOutputStream()); String advice = getAdvice(); writer.println(advice); writer.close(); System.out.println(advice); } } catch (IOException e) { e.printStackTrace(); } } private String getAdvice() { int random = (int) (Math.random() * adviceList.length); return adviceList[random]; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub DailyAdviceServer server = new DailyAdviceServer(); server.go(); } }
apache-2.0
ZephyrVentum/FlappySpinner
core/src/com/zephyr/ventum/interfaces/GameEventListener.java
1872
/* * Copyright (c) 2014. William Mora * * 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.zephyr.ventum.interfaces; import com.zephyr.ventum.screens.GameScreen; /** * Game events that are platform specific (i.e. submitting a score or displaying an ad inn an * Android app is different than doing the same in a desktop app). */ public interface GameEventListener { public void signIn(); public void signOut(); public void unlockAchievement(String id); public void submitScore(int highScore); public void showAchievement(); public void showScore(); public boolean isSignedIn(); /** * Displays an ad */ public void displayAd(); /** * Hides an ad */ public void hideAd(); /** * */ public void displayVungle(GameScreen.VungleCallBackListener listener); /** * change bg for AdMobs */ public void changeBackgroundColor(String color); /** * Shares the game's website */ public void share(); public String get10ScoreAchievementId(); public String get25ScoreAchievementId(); public String get50ScoreAchievementId(); public String get10GamesAchievementId(); public String get25GamesAchievementId(); public String get50GamesAchievementId(); public String getVentumZephyrAchievementId(); }
apache-2.0
inaiat/jqplot4java
src/main/java/br/com/digilabs/jqplot/elements/Line.java
2334
/* * Copyright 2011 Inaiat H. Moraes. * * 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. * under the License. */ package br.com.digilabs.jqplot.elements; import java.util.ArrayList; import java.util.Collection; /** * Line object. * * Line properties can be set or overriden by the options passed in from the user. * * @author inaiat */ public class Line extends CanvasOverlay { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 7228237374262625679L; /** The start. */ private Collection<Integer> start; /** The stop. */ private Collection<Integer> stop; /** * Instantiates a new line. */ public Line() { } /** * Instantiates a new line. * * @param name the name */ public Line(String name) { setName(name); } public Collection<Integer> startInstance() { if (this.start == null) { this.start = new ArrayList<Integer>(); } return start; } /** * Gets the start. * * @return the start */ public Collection<Integer> getStart() { return start; } /** * Sets the start. * * @param start * the new start * @return Line */ public Line setStart(Collection<Integer> start) { this.start = start; return this; } /** * Get stop instance * @return Collection of integer type */ public Collection<Integer> stopInstance() { if (this.stop == null) { this.stop = new ArrayList<Integer>(); } return stop; } /** * Gets the stop. * * @return the stop */ public Collection<Integer> getStop() { return stop; } /** * Sets the stop. * * @param stop * the new stop * @return Line */ public Line setStop(Collection<Integer> stop) { this.stop = stop; return this; } }
apache-2.0
OSEHRA/ISAAC
komet/semantic-view/src/main/java/sh/isaac/komet/gui/semanticViewer/cells/AttachedDataCellFactory.java
2529
/* * 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. * * Contributions from 2013-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works * * Contributions prior to 2013: * * Copyright (C) International Health Terminology Standards Development Organisation. * Licensed under the Apache License, Version 2.0. * */ package sh.isaac.komet.gui.semanticViewer.cells; import java.util.Hashtable; import java.util.List; import java.util.UUID; import javafx.scene.control.TreeTableCell; import javafx.scene.control.TreeTableColumn; import javafx.util.Callback; import sh.isaac.api.component.semantic.version.dynamic.DynamicColumnInfo; import sh.isaac.komet.gui.semanticViewer.SemanticGUI; /** * {@link AttachedDataCellFactory} * * @author <a href="mailto:daniel.armbrust.list@gmail.com">Dan Armbrust</a> */ public class AttachedDataCellFactory implements Callback <TreeTableColumn<SemanticGUI, SemanticGUI>, TreeTableCell<SemanticGUI,SemanticGUI>> { private Hashtable<UUID, List<DynamicColumnInfo>> colInfo_; private int listPosition_; public AttachedDataCellFactory(Hashtable<UUID, List<DynamicColumnInfo>> colInfo, int listPosition) { colInfo_ = colInfo; listPosition_ = listPosition; } /** * @see javafx.util.Callback#call(java.lang.Object) */ @Override public TreeTableCell<SemanticGUI, SemanticGUI> call(TreeTableColumn<SemanticGUI, SemanticGUI> param) { return new AttachedDataCell(colInfo_, listPosition_); } }
apache-2.0
camunda/camunda-bpm-assert
core/src/test/java/org/camunda/bpm/engine/test/assertions/bpmn/JobAssertHasExceptionMessageTest.java
2782
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.test.assertions.bpmn; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.engine.test.assertions.helpers.Failure; import org.camunda.bpm.engine.test.assertions.helpers.ProcessAssertTestCase; import org.junit.Rule; import org.junit.Test; import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.*; import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** * @author Martin Schimak (martin.schimak@plexiti.com) */ public class JobAssertHasExceptionMessageTest extends ProcessAssertTestCase { @Rule public ProcessEngineRule processEngineRule = new ProcessEngineRule(); @Test @Deployment(resources = {"bpmn/JobAssert-hasExceptionMessage.bpmn" }) public void testHasExceptionMessage_Success() { // Given runtimeService().startProcessInstanceByKey( "JobAssert-hasExceptionMessage" ); // When try { managementService().executeJob(jobQuery().singleResult().getId()); fail ("expected ProcessEngineException to be thrown, but did not find any."); } catch (ProcessEngineException t) {} // Then assertThat(jobQuery().singleResult()).isNotNull(); // And assertThat(jobQuery().singleResult()).hasExceptionMessage(); } @Test @Deployment(resources = {"bpmn/JobAssert-hasExceptionMessage.bpmn" }) public void testHasExceptionMessage_Failure() { // Given runtimeService().startProcessInstanceByKey( "JobAssert-hasExceptionMessage" ); // Then assertThat(jobQuery().singleResult()).isNotNull(); // And expect(new Failure() { @Override public void when() { assertThat(jobQuery().singleResult()).hasExceptionMessage(); } }); } }
apache-2.0
trejkaz/derby
java/engine/org/apache/derby/iapi/types/XML.java
37739
/* Derby - Class org.apache.derby.iapi.types.XML Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.iapi.types; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.cache.ClassSize; import org.apache.derby.iapi.services.io.ArrayInputStream; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.services.io.StreamStorable; import org.apache.derby.iapi.services.io.Storable; import org.apache.derby.iapi.services.io.TypedFormat; import org.apache.derby.shared.common.sanity.SanityManager; import org.apache.derby.iapi.sql.conn.ConnectionUtil; import org.apache.derby.iapi.reference.SQLState; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.text.RuleBasedCollator; import java.io.InputStream; import java.io.IOException; import java.io.ObjectOutput; import java.io.ObjectInput; import java.util.List; /** * This type implements the XMLDataValue interface and thus is * the type on which all XML related operations are executed. * * The first and simplest XML store implementation is a UTF-8 * based one--all XML data is stored on disk as a UTF-8 string, * just like the other Derby string types. In order to make * it possible for smarter XML implementations to exist in * the future, this class always writes an "XML implementation * id" to disk before writing the rest of its data. When * reading the data, the impl id is read first and serves * as an indicator of how the rest of the data should be * read. * * So long as there's only one implementation (UTF-8) * the impl id can be ignored; but when smarter implementations * are written, the impl id will be the key to figuring out * how an XML value should be read, written, and processed. */ public class XML extends DataType implements XMLDataValue, StreamStorable { // Id for this implementation. Should be unique // across all XML type implementations. protected static final short UTF8_IMPL_ID = 0; // Guess at how much memory this type will take. private static final int BASE_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog(XML.class); // Some syntax-related constants used to determine // operator behavior. public static final short XQ_PASS_BY_REF = 1; public static final short XQ_PASS_BY_VALUE = 2; public static final short XQ_RETURN_SEQUENCE = 3; public static final short XQ_RETURN_CONTENT = 4; public static final short XQ_EMPTY_ON_EMPTY = 5; public static final short XQ_NULL_ON_EMPTY = 6; /* Per SQL/XML[2006] 4.2.2, there are several different * XML "types" defined through use of primary and secondary * "type modifiers". For Derby we only support two kinds: * * XML(DOCUMENT(ANY)) : A valid and well-formed XML * document as defined by W3C, meaning that there is * exactly one root element node. This is the only * type of XML that can be stored into a Derby XML * column. This is also the type returned by a call * to XMLPARSE since we require the DOCUMENT keyword. * * XML(SEQUENCE): A sequence of items (could be nodes or * atomic values). This is the type returned from an * XMLQUERY operation. Any node that is XML(DOCUMENT(ANY)) * is also XML(SEQUENCE). Note that an XML(SEQUENCE) * value is *only* storable into a Derby XML column * if it is also an XML(DOCUMENT(ANY)). See the * normalize method below for the code that enforces * this. */ public static final int XML_DOC_ANY = 0; public static final int XML_SEQUENCE = 1; // The fully-qualified type for this XML value. private int xType; // The actual XML data in this implementation is just a simple // string, so this class really just wraps a SQLChar and // defers most calls to the corresponding calls on that // SQLChar. Note that, even though a SQLChar is the // underlying implementation, an XML value is nonetheless // NOT considered comparable nor compatible with any of // Derby string types. private SQLChar xmlStringValue; /* * Status variable used to verify that user's classpath contains * required classes for accessing/operating on XML data values. */ private static String xmlReqCheck = null; /* * Whether or not this XML value corresponds to a sequence * that has one or more top-level ("parentless") attribute * nodes. If so then we have to throw an error if the user * attempts to serialize this value, per XML serialization * rules. */ private boolean containsTopLevelAttr; private SqlXmlUtil tmpUtil; /** * Default constructor. */ public XML() { xmlStringValue = null; xType = -1; containsTopLevelAttr = false; } /** * Private constructor used for the {@code cloneValue} method. * Returns a new instance of XML whose fields are clones * of the values received. * * @param val A SQLChar instance to clone and use for * this XML value. * @param xmlType Qualified XML type for "val" * @param seqWithAttr Whether or not "val" corresponds to * sequence with one or more top-level attribute nodes. * @param materialize whether or not to force materialization of the * underlying source data */ private XML(SQLChar val, int xmlType, boolean seqWithAttr, boolean materialize) { xmlStringValue = (val == null ? null : (SQLChar)val.cloneValue(materialize)); setXType(xmlType); if (seqWithAttr) markAsHavingTopLevelAttr(); } /* **** * DataValueDescriptor interface. * */ /** * @see DataValueDescriptor#cloneValue */ public DataValueDescriptor cloneValue(boolean forceMaterialization) { return new XML(xmlStringValue, getXType(), hasTopLevelAttr(), forceMaterialization); } /** * @see DataValueDescriptor#getNewNull */ public DataValueDescriptor getNewNull() { return new XML(); } /** * @see DataValueDescriptor#getTypeName */ public String getTypeName() { return TypeId.XML_NAME; } /** * @see DataValueDescriptor#typePrecedence */ public int typePrecedence() { return TypeId.XML_PRECEDENCE; } /** * @see DataValueDescriptor#getString */ public String getString() throws StandardException { return (xmlStringValue == null) ? null : xmlStringValue.getString(); } /** * @see DataValueDescriptor#getLength */ public int getLength() throws StandardException { return ((xmlStringValue == null) ? 0 : xmlStringValue.getLength()); } /** * @see DataValueDescriptor#estimateMemoryUsage */ public int estimateMemoryUsage() { int sz = BASE_MEMORY_USAGE; if (xmlStringValue != null) sz += xmlStringValue.estimateMemoryUsage(); return sz; } /** * @see DataValueDescriptor#readExternalFromArray */ public void readExternalFromArray(ArrayInputStream in) throws IOException { if (xmlStringValue == null) xmlStringValue = new SQLChar(); // Read the XML implementation id. Right now there's // only one implementation (UTF-8 based), so we don't // use this value. But if better implementations come // up in the future, we'll have to use this impl id to // figure out how to read the data. in.readShort(); // Now just read the XML data as UTF-8. xmlStringValue.readExternalFromArray(in); // If we read it from disk then it must have type // XML_DOC_ANY because that's all we allow to be // written into an XML column. setXType(XML_DOC_ANY); } /** * @see DataType#setFrom */ protected void setFrom(DataValueDescriptor theValue) throws StandardException { String strVal = theValue.getString(); if (strVal == null) { xmlStringValue = null; // Null is a valid value for DOCUMENT(ANY) setXType(XML_DOC_ANY); return; } // Here we just store the received value locally. if (xmlStringValue == null) xmlStringValue = new SQLChar(); xmlStringValue.setValue(strVal); /* * Assumption is that if theValue is not an XML * value then the caller is aware of whether or * not theValue constitutes a valid XML(DOCUMENT(ANY)) * and will behave accordingly (see in particular the * XMLQuery method of this class, which calls the * setValue() method of XMLDataValue which in turn * brings us to this method). */ if (theValue instanceof XMLDataValue) { setXType(((XMLDataValue)theValue).getXType()); if (((XMLDataValue)theValue).hasTopLevelAttr()) markAsHavingTopLevelAttr(); } } /** * @see DataValueDescriptor#setValueFromResultSet */ public final void setValueFromResultSet( ResultSet resultSet, int colNumber, boolean isNullable) throws SQLException { if (xmlStringValue == null) xmlStringValue = new SQLChar(); String valAsStr = resultSet.getString(colNumber); /* As there is no guarantee that the specified column within * resultSet is well-formed XML (is there??), we have to try * to parse it in order to set the "xType" field correctly. * This is required to ensure that we only store well-formed * XML on disk (see "normalize()" method of this class). So * create an instance of SqlXmlUtil and use that to see if the * text satisifies the requirements of a well-formed DOCUMENT. * * RESOLVE: If there is anyway to guarantee that the column * is in fact well-formed XML then we can skip all of this * logic and simply set xType to XML_DOC_ANY. But do we * have such a guarantee...? */ if (tmpUtil == null) { try { tmpUtil = new SqlXmlUtil(); } catch (StandardException se) { if (SanityManager.DEBUG) { SanityManager.THROWASSERT( "Failed to instantiate SqlXmlUtil for XML parsing."); } /* If we failed to get a SqlXmlUtil then we can't parse * the string, which means we don't know if it constitutes * a well-formed XML document or not. In this case we * set the value, but intentionally leave xType as -1 * so that the resultant value canNOT be stored on disk. */ xmlStringValue.setValue(valAsStr); setXType(-1); return; } } try { /* The following call parses the string into a DOM and * then serializes it, which is exactly what we do for * normal insertion of XML values. If the parse finishes * with no error then we know the type is XML_DOC_ANY, * so set it. */ valAsStr = tmpUtil.serializeToString(valAsStr); xmlStringValue.setValue(valAsStr); setXType(XML_DOC_ANY); } catch (Throwable t) { /* It's possible that the string value was either 1) an * XML SEQUENCE or 2) not XML at all. We don't know * which one it was, so make xType invalid to ensure this * field doesn't end up on disk. */ xmlStringValue.setValue(valAsStr); setXType(-1); } } /** * Compare two XML DataValueDescriptors. NOTE: This method * should only be used by the database store for the purpose of * index positioning--comparisons of XML type are not allowed * from the language side of things. That said, all store * wants to do is order the NULLs, so we don't actually * have to do a full comparison. Just return an order * value based on whether or not this XML value and the * other XML value are null. As mentioned in the "compare" * method of DataValueDescriptor, nulls are considered * equal to other nulls and less than all other values. * * An example of when this method might be used is if the * user executed a query like: * * select i from x_table where x_col is not null * * @see DataValueDescriptor#compare */ public int compare(DataValueDescriptor other) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(other instanceof XMLDataValue, "Store should NOT have tried to compare an XML value " + "with a non-XML value."); } if (isNull()) { if (other.isNull()) // both null, so call them 'equal'. return 0; // This XML is 'less than' the other. return -1; } if (other.isNull()) // This XML is 'greater than' the other. return 1; // Two non-null values: we shouldn't ever get here, // since that would necessitate a comparsion of XML // values, which isn't allowed. if (SanityManager.DEBUG) { SanityManager.THROWASSERT( "Store tried to compare two non-null XML values, " + "which isn't allowed."); } return 0; } /** * Normalization method - this method will always be called when * storing an XML value into an XML column, for example, when * inserting/updating. We always force normalization in this * case because we need to make sure the qualified type of the * value we're trying to store is XML_DOC_ANY--we don't allow * anything else. * * @param desiredType The type to normalize the source column to * @param source The value to normalize * * @exception StandardException Thrown if source is not * XML_DOC_ANY. */ public void normalize( DataTypeDescriptor desiredType, DataValueDescriptor source) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(source instanceof XMLDataValue, "Tried to store non-XML value into XML column; " + "should have thrown error at compile time."); } if (((XMLDataValue)source).getXType() != XML_DOC_ANY) { throw StandardException.newException( SQLState.LANG_NOT_AN_XML_DOCUMENT); } ((DataValueDescriptor) this).setValue(source); return; } /* **** * Storable interface, implies Externalizable, TypedFormat */ /** * @see TypedFormat#getTypeFormatId * * From the engine's perspective, all XML implementations share * the same format id. */ public int getTypeFormatId() { return StoredFormatIds.XML_ID; } /** * @see Storable#isNull */ public boolean isNull() { return ((xmlStringValue == null) || xmlStringValue.isNull()); } /** * @see Storable#restoreToNull */ public void restoreToNull() { if (xmlStringValue != null) xmlStringValue.restoreToNull(); } /** * Read an XML value from an input stream. * @param in The stream from which we're reading. */ public void readExternal(ObjectInput in) throws IOException { if (xmlStringValue == null) xmlStringValue = new SQLChar(); // Read the XML implementation id. Right now there's // only one implementation (UTF-8 based), so we don't // use this value. But if better implementations come // up in the future, we'll have to use this impl id to // figure out how to read the data. in.readShort(); // Now just read the XML data as UTF-8. xmlStringValue.readExternal(in); // If we read it from disk then it must have type // XML_DOC_ANY because that's all we allow to be // written into an XML column. setXType(XML_DOC_ANY); } /** * Write an XML value. * @param out The stream to which we're writing. */ public void writeExternal(ObjectOutput out) throws IOException { // never called when value is null if (SanityManager.DEBUG) SanityManager.ASSERT(!isNull()); // Write out the XML store impl id. out.writeShort(UTF8_IMPL_ID); // Now write out the data. xmlStringValue.writeExternal(out); } /* **** * StreamStorable interface * */ /** * @see StreamStorable#returnStream */ public InputStream returnStream() { return (xmlStringValue == null) ? null : xmlStringValue.returnStream(); } /** * @see StreamStorable#setStream */ public void setStream(InputStream newStream) { if (xmlStringValue == null) xmlStringValue = new SQLChar(); // The stream that we receive is for an XML data value, // which means it has an XML implementation id stored // at the front (we put it there when we wrote it out). // If we leave that there we'll get a failure when // our underlying SQLChar tries to read from the // stream, because the extra impl id will throw // off the UTF format. So we need to read in (and // ignore) the impl id before using the stream. try { // 2 bytes equal a short, which is what an impl id is. newStream.read(); newStream.read(); } catch (Exception e) { if (SanityManager.DEBUG) SanityManager.THROWASSERT("Failed to read impl id" + "bytes in setStream."); } // Now go ahead and use the stream. xmlStringValue.setStream(newStream); // If we read it from disk then it must have type // XML_DOC_ANY because that's all we allow to be // written into an XML column. setXType(XML_DOC_ANY); } /** * @see StreamStorable#loadStream */ public void loadStream() throws StandardException { getString(); } /* **** * XMLDataValue interface. * */ /** * Method to parse an XML string and, if it's valid, * store the _serialized_ version locally and then return * this XMLDataValue. * * @param stringValue The string value to check. * @param preserveWS Whether or not to preserve * ignorable whitespace. * @param sqlxUtil Contains SQL/XML objects and util * methods that facilitate execution of XML-related * operations * @return If 'text' constitutes a valid XML document, * it has been stored in this XML value and this XML * value is returned; otherwise, an exception is thrown. * @exception StandardException Thrown on error. */ public XMLDataValue XMLParse( StringDataValue stringValue, boolean preserveWS, SqlXmlUtil sqlxUtil) throws StandardException { if (stringValue.isNull()) { setToNull(); return this; } String text = stringValue.getString(); try { if (preserveWS) { // Currently the only way a user can view the contents of // an XML value is by explicitly calling XMLSERIALIZE. // So do a serialization now and just store the result, // so that we don't have to re-serialize every time a // call is made to XMLSERIALIZE. text = sqlxUtil.serializeToString(text); } else { // We don't support this yet, so we shouldn't // get here. if (SanityManager.DEBUG) SanityManager.THROWASSERT("Tried to STRIP whitespace " + "but we shouldn't have made it this far"); } } catch (Throwable t) { /* Couldn't parse the XML document. Throw a StandardException * with the parse exception (or other error) nested in it. * Note: we catch "Throwable" here to catch as many external * errors as possible in order to minimize the chance of an * uncaught JAXP/Xalan error (such as a NullPointerException) * causing Derby to fail in a more serious way. In particular, * an uncaught Java exception like NPE can result in Derby * throwing "ERROR 40XT0: An internal error was identified by * RawStore module" for all statements on the connection after * the failure--which we clearly don't want. If we catch the * error and wrap it, though, the statement will fail but Derby * will continue to run as normal. */ throw StandardException.newException( SQLState.LANG_INVALID_XML_DOCUMENT, t, t.getMessage()); } // If we get here, the text is valid XML so go ahead // and load/store it. setXType(XML_DOC_ANY); if (xmlStringValue == null) xmlStringValue = new SQLChar(); xmlStringValue.setValue(text); return this; } /** * The SQL/XML XMLSerialize operator. * Serializes this XML value into a string with a user-specified * character type, and returns that string via the received * StringDataValue (if the received StringDataValue is non-null * and of the correct type; else, a new StringDataValue is * returned). * * @param result The result of a previous call to this method, * null if not called yet. * @param targetType The string type to which we want to serialize. * @param targetWidth The width of the target type. * @return A serialized (to string) version of this XML object, * in the form of a StringDataValue object. * @exception StandardException Thrown on error */ public StringDataValue XMLSerialize(StringDataValue result, int targetType, int targetWidth, int targetCollationType) throws StandardException { if (result == null) { switch (targetType) { case Types.CHAR: result = new SQLChar(); break; case Types.VARCHAR: result = new SQLVarchar(); break; case Types.LONGVARCHAR: result = new SQLLongvarchar(); break; case Types.CLOB: result = new SQLClob(); break; default: // Shouldn't ever get here, as this check was performed // at bind time. if (SanityManager.DEBUG) { SanityManager.THROWASSERT( "Should NOT have made it to XMLSerialize " + "with a non-string target type: " + targetType); } return null; } // If the collation type is territory based, then we should use // CollatorSQLxxx rather than SQLxxx types for StringDataValue. // eg // CREATE TABLE T_MAIN1 (ID INT GENERATED ALWAYS AS IDENTITY // PRIMARY KEY, V XML); // INSERT INTO T_MAIN1(V) VALUES NULL; // SELECT ID, XMLSERIALIZE(V AS CLOB), XMLSERIALIZE(V AS CLOB) // FROM T_MAIN1 ORDER BY 1; // Following code is for (V AS CLOB) inside XMLSERIALIZE. The // StringDataValue returned for (V AS CLOB) should consider the // passed collation type in determining whether we should // generate SQLChar vs CollatorSQLChar for instance. Keep in mind // that collation applies only to character string types. try { RuleBasedCollator rbs = ConnectionUtil.getCurrentLCC().getDataValueFactory(). getCharacterCollator(targetCollationType); result = ((StringDataValue)result).getValue(rbs); } catch( java.sql.SQLException sqle) { throw StandardException.plainWrapException( sqle); } } // Else we're reusing a StringDataValue. We only reuse // the result if we're executing the _same_ XMLSERIALIZE // call on multiple rows. That means that all rows // must have the same result type (targetType) and thus // we know that the StringDataValue already has the // correct type. So we're set. if (this.isNull()) { // Attempts to serialize a null XML value lead to a null // result (SQL/XML[2003] section 10.13). result.setToNull(); return result; } /* XML serialization rules say that sequence "normalization" * must occur before serialization, and normalization dictates * that a serialization error must be thrown if the XML value * is a sequence with a top-level attribute. We normalized * (and serialized) this XML value when it was first created, * and at that time we took note of whether or not there is * a top-level attribute. So throw the error here if needed. * See SqlXmlUtil.serializeToString() for more on sequence * normalization. */ if (this.hasTopLevelAttr()) { throw StandardException.newException( SQLState.LANG_XQUERY_SERIALIZATION_ERROR); } // Get the XML value as a string. For this UTF-8 impl, // we already have it as a UTF-8 string, so just use // that. result.setValue(getString()); // Seems wrong to trunc an XML document, as it then becomes non- // well-formed and thus useless. So we throw an error (that's // what the "true" in the next line says). result.setWidth(targetWidth, 0, true); return result; } /** * The SQL/XML XMLExists operator. * Checks to see if evaluation of the query expression contained * within the received util object against this XML value returns * at least one item. NOTE: For now, the query expression must be * XPath only (XQuery not supported) because that's what Xalan * supports. * * @param sqlxUtil Contains SQL/XML objects and util * methods that facilitate execution of XML-related * operations * @return True if evaluation of the query expression stored * in sqlxUtil returns at least one node for this XML value; * unknown if the xml value is NULL; false otherwise. * @exception StandardException Thrown on error */ public BooleanDataValue XMLExists(SqlXmlUtil sqlxUtil) throws StandardException { if (this.isNull()) { // if the user specified a context node and that context // is null, result of evaluating the query is null // (per SQL/XML 6.17:General Rules:1.a), which means that we // return "unknown" here (per SQL/XML 8.4:General Rules:2.a). return SQLBoolean.unknownTruthValue(); } // Make sure we have a compiled query (and associated XML // objects) to evaluate. if (SanityManager.DEBUG) { SanityManager.ASSERT( sqlxUtil != null, "Tried to evaluate XML xquery, but no XML objects were loaded."); } try { return new SQLBoolean(null != sqlxUtil.evalXQExpression(this, false, new int[1])); } catch (StandardException se) { // Just re-throw it. throw se; } catch (Throwable xe) { /* Failed somewhere during evaluation of the XML query expression; * turn error into a StandardException and throw it. Note: we * catch "Throwable" here to catch as many Xalan-produced errors * as possible in order to minimize the chance of an uncaught Xalan * error (such as a NullPointerException) causing Derby to fail in * a more serious way. In particular, an uncaught Java exception * like NPE can result in Derby throwing "ERROR 40XT0: An internal * error was identified by RawStore module" for all statements on * the connection after the failure--which we clearly don't want. * If we catch the error and wrap it, though, the statement will * fail but Derby will continue to run as normal. */ throw StandardException.newException( SQLState.LANG_XML_QUERY_ERROR, xe, "XMLEXISTS", xe.getMessage()); } } /** * Evaluate the XML query expression contained within the received * util object against this XML value and store the results into * the received XMLDataValue "result" param (assuming "result" is * non-null; else create a new XMLDataValue). * * @param sqlxUtil Contains SQL/XML objects and util methods that * facilitate execution of XML-related operations * @param result The result of a previous call to this method; null * if not called yet. * @return An XMLDataValue whose content corresponds to the serialized * version of the results from evaluation of the query expression. * Note: this XMLDataValue may not be storable into Derby XML * columns. * @exception StandardException thrown on error */ public XMLDataValue XMLQuery(SqlXmlUtil sqlxUtil, XMLDataValue result) throws StandardException { if (this.isNull()) { // if the context is null, we return null, // per SQL/XML[2006] 6.17:GR.1.a.ii.1. if (result == null) result = (XMLDataValue)getNewNull(); else result.setToNull(); return result; } try { // Return an XML data value whose contents are the // serialized version of the query results. int [] xType = new int[1]; List itemRefs = sqlxUtil.evalXQExpression( this, true, xType); if (result == null) result = new XML(); String strResult = sqlxUtil.serializeToString(itemRefs, result); result.setValue(new SQLChar(strResult)); // Now that we've set the result value, make sure // to indicate what kind of XML value we have. result.setXType(xType[0]); // And finally we return the query result as an XML value. return result; } catch (StandardException se) { // Just re-throw it. throw se; } catch (Throwable xe) { /* Failed somewhere during evaluation of the XML query expression; * turn error into a StandardException and throw it. Note: we * catch "Throwable" here to catch as many Xalan-produced errors * as possible in order to minimize the chance of an uncaught Xalan * error (such as a NullPointerException) causing Derby to fail in * a more serious way. In particular, an uncaught Java exception * like NPE can result in Derby throwing "ERROR 40XT0: An internal * error was identified by RawStore module" for all statements on * the connection after the failure--which we clearly don't want. * If we catch the error and wrap it, though, the statement will * fail but Derby will continue to run as normal. */ throw StandardException.newException( SQLState.LANG_XML_QUERY_ERROR, xe, "XMLQUERY", xe.getMessage()); } } /* **** * Helper classes and methods. * */ /** * Set this XML value's qualified type. */ public void setXType(int xtype) { this.xType = xtype; /* If the target type is XML_DOC_ANY then this XML value * holds a single well-formed Document. So we know that * we do NOT have any top-level attribute nodes. Note: if * xtype is SEQUENCE we don't set "containsTopLevelAttr" * here; assumption is that the caller of this method will * then set the field as appropriate. Ex. see "setFrom()" * in this class. */ if (xtype == XML_DOC_ANY) containsTopLevelAttr = false; } /** * Retrieve this XML value's qualified type. */ public int getXType() { return xType; } /** * Take note of the fact this XML value represents an XML * sequence that has one or more top-level attribute nodes. */ public void markAsHavingTopLevelAttr() { this.containsTopLevelAttr = true; } /** * Return whether or not this XML value represents a sequence * that has one or more top-level attribute nodes. */ public boolean hasTopLevelAttr() { return containsTopLevelAttr; } /** * See if the required JAXP and Xalan classes are in the * user's classpath. Assumption is that we will always * call this method before instantiating an instance of * SqlXmlUtil, and thus we will never get a ClassNotFound * exception caused by missing JAXP/Xalan classes. Instead, * if either is missing we should throw an informative * error indicating what the problem is. * * NOTE: This method only does the checks necessary to * allow successful instantiation of the SqlXmlUtil * class. Further checks (esp. the presence of a JAXP * _implementation_ in addition to the JAXP _interfaces_) * are performed in the SqlXmlUtil constructor. * * @exception StandardException thrown if the required * classes cannot be located in the classpath. */ public static void checkXMLRequirements() throws StandardException { // Only check once; after that, just re-use the result. if (xmlReqCheck == null) { xmlReqCheck = ""; /* If the DocumentBuilderFactory class exists, then we * assume a JAXP implementation is present in * the classpath. If this assumption is incorrect * then we at least know that the JAXP *interface* * exists and thus we'll be able to instantiate * the SqlXmlUtil class. We can then do a check * for an actual JAXP *implementation* from within * the SqlXmlUtil class (see the constructor of * that class). * * Note: The JAXP API and implementation are * provided as part the JVM if it is jdk 1.4 or * greater. */ if (!checkJAXPRequirement()) { xmlReqCheck = "JAXP"; } /* If the XPathFactory class exists, then we assume that * our XML query processor is present in the classpath. */ else if (!checkXPathRequirement()) { xmlReqCheck = "XPath"; } } if (xmlReqCheck.length() != 0) { throw StandardException.newException( SQLState.LANG_MISSING_XML_CLASSES, xmlReqCheck); } } /** * Check if we have a JAXP implementation installed. * * @return {@code true} if JAXP is installed, or {@code false} otherwise */ private static boolean checkJAXPRequirement() { try { Class.forName("javax.xml.parsers.DocumentBuilderFactory"); return true; } catch (Throwable t) { // Oops... Couldn't load the DocumentBuilderFactory class for // some reason. Assume we don't have JAXP. return false; } } /** * Check if XPath is supported on this platform. * * @return {@code true} if XPath is supported, or {@code false} otherwise */ private static boolean checkXPathRequirement() { try { Class.forName("javax.xml.xpath.XPathFactory"); return true; } catch (Throwable t) { // Oops... Something went wrong when checking for XPath // support. Assume we don't have it. return false; } } }
apache-2.0
lamfire/hydra
src/test/java/com/lamfire/hydra/sample/gateway/GatewayServer.java
1091
package com.lamfire.hydra.sample.gateway; import com.lamfire.hydra.*; import com.lamfire.hydra.HydraDestination; import com.lamfire.utils.StringUtils; public class GatewayServer { static void usage(){ System.out.println("com.lamfire.nkit.sample.ConnectionGateway [host] [port] [bind|connect]"); } public static void main(String[] args) { String host = "0.0.0.0"; int port = 8000; String action = "bind"; if(args.length > 0 && "?".equals(args[0])){ usage(); return; } if(args.length == 3){ host = args[0]; port = Integer.valueOf(args[1]); action = (args[2]); } com.lamfire.hydra.Gateway gateway = new com.lamfire.hydra.Gateway(host,port); gateway.setHearbeatIntervalTime(30); gateway.setMaxWaitWithHeartbeat(3); if(StringUtils.equalsIgnoreCase(action, "connect")){ gateway.connect(); }else{ gateway.bind(); } HydraDestination dest = new PollerDestination("0.0.0.0", 8001); dest.bind(); MessageBus bus = new DefaultMessageBus(gateway); bus.addDestination(dest); } }
apache-2.0
x-meta/xworker
xworker_core/src/main/java/xworker/lang/actions/thing/ThingIterator.java
3728
/******************************************************************************* * Copyright 2007-2013 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 xworker.lang.actions.thing; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmeta.Category; import org.xmeta.Thing; import org.xmeta.ThingManager; import org.xmeta.World; @SuppressWarnings("unchecked") public class ThingIterator implements Iterator { private static Logger logger = LoggerFactory.getLogger(ThingIterator.class); World world = World.getInstance(); Thing self = null; String[] paths = null; private boolean hasNext = false; Iterator<Thing> currentIter = null; Thing nextThing = null; int pathIndex = 0; public ThingIterator(Thing self, String paths){ this.self = self; this.paths = paths.split("[,]"); initNext(); } private void initNext(){ if(currentIter != null && currentIter.hasNext()){ hasNext = true; return; } while(true){ if(pathIndex >= paths.length){ hasNext = false; return; } String path = paths[pathIndex].trim(); pathIndex++; if("".equals(path)){ continue; } if(path.indexOf(":") != -1){ String thingManagerName = path.substring(0, path.indexOf(":")); path = path.substring(path.indexOf(":") + 1, path.length()); ThingManager thingManager = world.getThingManager(thingManagerName); if(thingManager == null){ logger.info("ThingCollectionIterator: thingManager is null, name=" + thingManagerName + ",thing=" + self.getMetadata().getPath()); continue; }else{ Category category = thingManager.getCategory(path); if(category != null){ Iterator<Thing> iter = category.iterator(true); if(iter.hasNext()){ hasNext = true; currentIter = iter; return; } }else{ Thing thing = thingManager.getThing(path); if(thing != null){ currentIter = null; nextThing = thing; hasNext = true; return; } } } }else{ Object obj = world.get(path); if(obj == null){ logger.info("ThingCollections: the object of path is null, path=" + path + ",thing=" + self.getMetadata().getPath()); continue; }else if(obj instanceof Category){ Iterator<Thing> iter = ((Category) obj).iterator(true); if(iter.hasNext()){ hasNext = true; nextThing = null; currentIter = iter; return; } }else if(obj instanceof Thing){ currentIter = null; nextThing = (Thing) obj; hasNext = true; return; } } } } @Override public boolean hasNext() { return hasNext; } @Override public Thing next() { if(hasNext){ Thing thing = null; if(currentIter != null){ thing = currentIter.next(); }else{ thing = nextThing; nextThing = null; } initNext(); return thing; }else{ return null; } } @Override public void remove() { } }
apache-2.0
davideas/FlexibleAdapter
flexible-adapter-app/src/main/java/eu/davidea/samples/flexibleadapter/models/ItemModel.java
249
package eu.davidea.samples.flexibleadapter.models; /** * Model item for ItemHolder. * * @author Davide Steduto * @since 19/10/2016 */ public class ItemModel extends AbstractModel { public ItemModel(String id) { super(id); } }
apache-2.0
meclub/MeUI
app/src/main/java/com/me/ui/zhihu/view/view/RecyclerViewItemDecoration.java
1252
package com.me.ui.view.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.View; import com.me.ui.R; /** * Simple RecyclerView Divider * Created by tangqi on 9/16/15. */ public class RecyclerViewItemDecoration extends RecyclerView.ItemDecoration { private Drawable mDivider; public RecyclerViewItemDecoration(Context context) { mDivider = context.getResources().getDrawable(R.drawable.item_divider_black); } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { int left = parent.getPaddingLeft(); int right = parent.getWidth() - parent.getPaddingRight(); int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { View child = parent.getChildAt(i); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); int top = child.getBottom() + params.bottomMargin; int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } }
apache-2.0
shuodata/deeplearning4j
deeplearning4j-nlp-parent/deeplearning4j-nlp-chinese/src/main/java/org/ansj/dic/LearnTool.java
5459
package org.ansj.dic; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.ansj.app.crf.SplitWord; import org.ansj.domain.Nature; import org.ansj.domain.NewWord; import org.ansj.domain.TermNatures; import org.ansj.recognition.arrimpl.AsianPersonRecognition; import org.ansj.recognition.arrimpl.ForeignPersonRecognition; import org.ansj.recognition.impl.NatureRecognition; import org.ansj.util.Graph; import org.nlpcn.commons.lang.tire.domain.Forest; import org.nlpcn.commons.lang.tire.domain.SmartForest; import org.nlpcn.commons.lang.util.CollectionUtil; /** * 新词发现,这是个线程安全的.所以可以多个对象公用一个 * * @author ansj * */ public class LearnTool { private SplitWord splitWord = null; /** * 是否开启学习机 */ public boolean isAsianName = true; public boolean isForeignName = true; /** * 告诉大家你学习了多少个词了 */ public int count; /** * 新词发现的结果集.可以序列化到硬盘.然后可以当做训练集来做. */ private final SmartForest<NewWord> sf = new SmartForest<NewWord>(); /** * 学习新词排除用户自定义词典那中的词语 */ private Forest[] forests; /** * 公司名称学习. * * @param graph */ public void learn(Graph graph, SplitWord splitWord, Forest... forests) { this.splitWord = splitWord; this.forests = forests; // 亚洲人名识别 if (isAsianName) { findAsianPerson(graph); } // 外国人名识别 if (isForeignName) { findForeignPerson(graph); } } private void findAsianPerson(Graph graph) { List<NewWord> newWords = new AsianPersonRecognition().getNewWords(graph.terms); addListToTerm(newWords); } private void findForeignPerson(Graph graph) { List<NewWord> newWords = new ForeignPersonRecognition().getNewWords(graph.terms); addListToTerm(newWords); } // 批量将新词加入到词典中 private void addListToTerm(List<NewWord> newWords) { if (newWords.size() == 0) return; for (NewWord newWord : newWords) { TermNatures termNatures = new NatureRecognition(forests).getTermNatures(newWord.getName()); if (termNatures == TermNatures.NULL) { addTerm(newWord); } } } /** * 增加一个新词到树中 * * @param newWord */ public void addTerm(NewWord newWord) { NewWord temp = null; SmartForest<NewWord> smartForest = null; if ((smartForest = sf.getBranch(newWord.getName())) != null && smartForest.getParam() != null) { temp = smartForest.getParam(); temp.update(newWord.getNature(), newWord.getAllFreq()); } else { count++; if (splitWord == null) { newWord.setScore(-1); } else { newWord.setScore(-splitWord.cohesion(newWord.getName())); } synchronized (sf) { sf.add(newWord.getName(), newWord); } } } public SmartForest<NewWord> getForest() { return this.sf; } /** * 返回学习到的新词. * * @param num 返回数目.0为全部返回 * @return */ public List<Entry<String, Double>> getTopTree(int num) { return getTopTree(num, null); } public List<Entry<String, Double>> getTopTree(int num, Nature nature) { if (sf.branches == null) { return null; } HashMap<String, Double> hm = new HashMap<String, Double>(); for (int i = 0; i < sf.branches.length; i++) { valueResult(sf.branches[i], hm, nature); } List<Entry<String, Double>> sortMapByValue = CollectionUtil.sortMapByValue(hm, -1); if (num == 0) { return sortMapByValue; } else { num = Math.min(num, sortMapByValue.size()); return sortMapByValue.subList(0, num); } } private void valueResult(SmartForest<NewWord> smartForest, HashMap<String, Double> hm, Nature nature) { if (smartForest == null || smartForest.branches == null) { return; } for (int i = 0; i < smartForest.branches.length; i++) { NewWord param = smartForest.branches[i].getParam(); if (smartForest.branches[i].getStatus() == 3) { if (param.isActive() && (nature == null || param.getNature().equals(nature))) { hm.put(param.getName(), param.getScore()); } } else if (smartForest.branches[i].getStatus() == 2) { if (param.isActive() && (nature == null || param.getNature().equals(nature))) { hm.put(param.getName(), param.getScore()); } valueResult(smartForest.branches[i], hm, nature); } else { valueResult(smartForest.branches[i], hm, nature); } } } /** * 尝试激活,新词 * * @param name */ public void active(String name) { SmartForest<NewWord> branch = sf.getBranch(name); if (branch != null && branch.getParam() != null) { branch.getParam().setActive(true); } } }
apache-2.0
reyanshmishra/Rey-MusicPlayer
app/src/main/java/com/reyansh/audio/audioplayer/free/NowPlaying/PlaylistPagerAdapter.java
1769
package com.reyansh.audio.audioplayer.free.NowPlaying; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.view.ViewGroup; import com.reyansh.audio.audioplayer.free.Common; public class PlaylistPagerAdapter extends FragmentStatePagerAdapter { private Common mApp; private NowPlayingActivity mNowPlayingActivity; public PlaylistPagerAdapter(NowPlayingActivity nowPlayingActivity, FragmentManager fm) { super(fm); mNowPlayingActivity = nowPlayingActivity; mApp = (Common) Common.getInstance(); } //This method controls the layout that is shown on each screen. @Override public Fragment getItem(int position) { /* PlaylistPagerFragment.java will be shown on every pager screen. However, * the fragment will check which screen (position) is being shown, and will * update its TextViews and ImageViews to match the song that's being played. */ Fragment fragment = new PlaylistPagerFragment(); Bundle bundle = new Bundle(); bundle.putInt("POSITION", position); fragment.setArguments(bundle); return fragment; } @Override public int getCount() { try { if (mApp.isServiceRunning()) { return mApp.getService().getSongList().size(); } else { return mNowPlayingActivity.mSongs.size(); } } catch (NullPointerException e) { return 0; } } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); } }
apache-2.0
xasx/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/RestartProcessInstancesBatchConfigurationJsonConverter.java
3459
/* * Copyright © 2013-2019 camunda services GmbH and various authors (info@camunda.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.impl; import java.util.List; import org.camunda.bpm.engine.impl.cmd.AbstractProcessInstanceModificationCommand; import org.camunda.bpm.engine.impl.json.JsonObjectConverter; import org.camunda.bpm.engine.impl.json.ModificationCmdJsonConverter; import org.camunda.bpm.engine.impl.util.JsonUtil; import com.google.gson.JsonObject; public class RestartProcessInstancesBatchConfigurationJsonConverter extends JsonObjectConverter<RestartProcessInstancesBatchConfiguration>{ public static final RestartProcessInstancesBatchConfigurationJsonConverter INSTANCE = new RestartProcessInstancesBatchConfigurationJsonConverter(); public static final String PROCESS_INSTANCE_IDS = "processInstanceIds"; public static final String INSTRUCTIONS = "instructions"; public static final String PROCESS_DEFINITION_ID = "processDefinitionId"; public static final String INITIAL_VARIABLES = "initialVariables"; public static final String SKIP_CUSTOM_LISTENERS = "skipCustomListeners"; public static final String SKIP_IO_MAPPINGS = "skipIoMappings"; public static final String WITHOUT_BUSINESS_KEY = "withoutBusinessKey"; @Override public JsonObject toJsonObject(RestartProcessInstancesBatchConfiguration configuration) { JsonObject json = JsonUtil.createObject(); JsonUtil.addListField(json, PROCESS_INSTANCE_IDS, configuration.getIds()); JsonUtil.addField(json, PROCESS_DEFINITION_ID, configuration.getProcessDefinitionId()); JsonUtil.addListField(json, INSTRUCTIONS, ModificationCmdJsonConverter.INSTANCE, configuration.getInstructions()); JsonUtil.addField(json, INITIAL_VARIABLES, configuration.isInitialVariables()); JsonUtil.addField(json, SKIP_CUSTOM_LISTENERS, configuration.isSkipCustomListeners()); JsonUtil.addField(json, SKIP_IO_MAPPINGS, configuration.isSkipIoMappings()); JsonUtil.addField(json, WITHOUT_BUSINESS_KEY, configuration.isWithoutBusinessKey()); return json; } @Override public RestartProcessInstancesBatchConfiguration toObject(JsonObject json) { List<String> processInstanceIds = readProcessInstanceIds(json); List<AbstractProcessInstanceModificationCommand> instructions = JsonUtil.asList(JsonUtil.getArray(json, INSTRUCTIONS), ModificationCmdJsonConverter.INSTANCE); return new RestartProcessInstancesBatchConfiguration(processInstanceIds, instructions, JsonUtil.getString(json, PROCESS_DEFINITION_ID), JsonUtil.getBoolean(json, INITIAL_VARIABLES), JsonUtil.getBoolean(json, SKIP_CUSTOM_LISTENERS), JsonUtil.getBoolean(json, SKIP_IO_MAPPINGS), JsonUtil.getBoolean(json, WITHOUT_BUSINESS_KEY)); } protected List<String> readProcessInstanceIds(JsonObject jsonObject) { return JsonUtil.asStringList(JsonUtil.getArray(jsonObject, PROCESS_INSTANCE_IDS)); } }
apache-2.0
PiValue/Practice
src/personal/leetcode/Test.java
210
package personal.leetcode; import personal.common.LNode; public class Test { public static void main(String[] args) { System.out.println(LNode.buildList(new int[] {1, 2, 3, 4, 5, 6, 7})); } }
apache-2.0
aws/aws-sdk-java-v2
services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/ScanOperation.java
5594
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.operations; import java.util.Map; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils; import software.amazon.awssdk.enhanced.dynamodb.internal.ProjectionExpression; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; @SdkInternalApi public class ScanOperation<T> implements PaginatedTableOperation<T, ScanRequest, ScanResponse>, PaginatedIndexOperation<T, ScanRequest, ScanResponse> { private final ScanEnhancedRequest request; private ScanOperation(ScanEnhancedRequest request) { this.request = request; } public static <T> ScanOperation<T> create(ScanEnhancedRequest request) { return new ScanOperation<>(request); } @Override public OperationName operationName() { return OperationName.SCAN; } @Override public ScanRequest generateRequest(TableSchema<T> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension extension) { Map<String, AttributeValue> expressionValues = null; Map<String, String> expressionNames = null; if (this.request.filterExpression() != null) { expressionValues = this.request.filterExpression().expressionValues(); expressionNames = this.request.filterExpression().expressionNames(); } String projectionExpressionAsString = null; if (this.request.attributesToProject() != null) { ProjectionExpression attributesToProject = ProjectionExpression.create(this.request.nestedAttributesToProject()); projectionExpressionAsString = attributesToProject.projectionExpressionAsString().orElse(null); expressionNames = Expression.joinNames(expressionNames, attributesToProject.expressionAttributeNames()); } ScanRequest.Builder scanRequest = ScanRequest.builder() .tableName(operationContext.tableName()) .limit(this.request.limit()) .segment(this.request.segment()) .totalSegments(this.request.totalSegments()) .exclusiveStartKey(this.request.exclusiveStartKey()) .consistentRead(this.request.consistentRead()) .expressionAttributeValues(expressionValues) .expressionAttributeNames(expressionNames) .projectionExpression(projectionExpressionAsString); if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) { scanRequest = scanRequest.indexName(operationContext.indexName()); } if (this.request.filterExpression() != null) { scanRequest = scanRequest.filterExpression(this.request.filterExpression().expression()); } return scanRequest.build(); } @Override public Page<T> transformResponse(ScanResponse response, TableSchema<T> tableSchema, OperationContext context, DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) { return EnhancedClientUtils.readAndTransformPaginatedItems(response, tableSchema, context, dynamoDbEnhancedClientExtension, ScanResponse::items, ScanResponse::lastEvaluatedKey); } @Override public Function<ScanRequest, SdkIterable<ScanResponse>> serviceCall(DynamoDbClient dynamoDbClient) { return dynamoDbClient::scanPaginator; } @Override public Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) { return dynamoDbAsyncClient::scanPaginator; } }
apache-2.0
vschs007/buck
src-gen/com/facebook/buck/distributed/thrift/MultiGetBuildSlaveEventsResponse.java
15057
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.facebook.buck.distributed.thrift; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2017-03-29") public class MultiGetBuildSlaveEventsResponse implements org.apache.thrift.TBase<MultiGetBuildSlaveEventsResponse, MultiGetBuildSlaveEventsResponse._Fields>, java.io.Serializable, Cloneable, Comparable<MultiGetBuildSlaveEventsResponse> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("MultiGetBuildSlaveEventsResponse"); private static final org.apache.thrift.protocol.TField RESPONSES_FIELD_DESC = new org.apache.thrift.protocol.TField("responses", org.apache.thrift.protocol.TType.LIST, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new MultiGetBuildSlaveEventsResponseStandardSchemeFactory()); schemes.put(TupleScheme.class, new MultiGetBuildSlaveEventsResponseTupleSchemeFactory()); } public List<BuildSlaveEventsRange> responses; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { RESPONSES((short)1, "responses"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // RESPONSES return RESPONSES; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.RESPONSES}; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.RESPONSES, new org.apache.thrift.meta_data.FieldMetaData("responses", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, BuildSlaveEventsRange.class)))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(MultiGetBuildSlaveEventsResponse.class, metaDataMap); } public MultiGetBuildSlaveEventsResponse() { } /** * Performs a deep copy on <i>other</i>. */ public MultiGetBuildSlaveEventsResponse(MultiGetBuildSlaveEventsResponse other) { if (other.isSetResponses()) { List<BuildSlaveEventsRange> __this__responses = new ArrayList<BuildSlaveEventsRange>(other.responses.size()); for (BuildSlaveEventsRange other_element : other.responses) { __this__responses.add(new BuildSlaveEventsRange(other_element)); } this.responses = __this__responses; } } public MultiGetBuildSlaveEventsResponse deepCopy() { return new MultiGetBuildSlaveEventsResponse(this); } @Override public void clear() { this.responses = null; } public int getResponsesSize() { return (this.responses == null) ? 0 : this.responses.size(); } public java.util.Iterator<BuildSlaveEventsRange> getResponsesIterator() { return (this.responses == null) ? null : this.responses.iterator(); } public void addToResponses(BuildSlaveEventsRange elem) { if (this.responses == null) { this.responses = new ArrayList<BuildSlaveEventsRange>(); } this.responses.add(elem); } public List<BuildSlaveEventsRange> getResponses() { return this.responses; } public MultiGetBuildSlaveEventsResponse setResponses(List<BuildSlaveEventsRange> responses) { this.responses = responses; return this; } public void unsetResponses() { this.responses = null; } /** Returns true if field responses is set (has been assigned a value) and false otherwise */ public boolean isSetResponses() { return this.responses != null; } public void setResponsesIsSet(boolean value) { if (!value) { this.responses = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case RESPONSES: if (value == null) { unsetResponses(); } else { setResponses((List<BuildSlaveEventsRange>)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case RESPONSES: return getResponses(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case RESPONSES: return isSetResponses(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof MultiGetBuildSlaveEventsResponse) return this.equals((MultiGetBuildSlaveEventsResponse)that); return false; } public boolean equals(MultiGetBuildSlaveEventsResponse that) { if (that == null) return false; boolean this_present_responses = true && this.isSetResponses(); boolean that_present_responses = true && that.isSetResponses(); if (this_present_responses || that_present_responses) { if (!(this_present_responses && that_present_responses)) return false; if (!this.responses.equals(that.responses)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_responses = true && (isSetResponses()); list.add(present_responses); if (present_responses) list.add(responses); return list.hashCode(); } @Override public int compareTo(MultiGetBuildSlaveEventsResponse other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetResponses()).compareTo(other.isSetResponses()); if (lastComparison != 0) { return lastComparison; } if (isSetResponses()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.responses, other.responses); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("MultiGetBuildSlaveEventsResponse("); boolean first = true; if (isSetResponses()) { sb.append("responses:"); if (this.responses == null) { sb.append("null"); } else { sb.append(this.responses); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class MultiGetBuildSlaveEventsResponseStandardSchemeFactory implements SchemeFactory { public MultiGetBuildSlaveEventsResponseStandardScheme getScheme() { return new MultiGetBuildSlaveEventsResponseStandardScheme(); } } private static class MultiGetBuildSlaveEventsResponseStandardScheme extends StandardScheme<MultiGetBuildSlaveEventsResponse> { public void read(org.apache.thrift.protocol.TProtocol iprot, MultiGetBuildSlaveEventsResponse struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESPONSES if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list162 = iprot.readListBegin(); struct.responses = new ArrayList<BuildSlaveEventsRange>(_list162.size); BuildSlaveEventsRange _elem163; for (int _i164 = 0; _i164 < _list162.size; ++_i164) { _elem163 = new BuildSlaveEventsRange(); _elem163.read(iprot); struct.responses.add(_elem163); } iprot.readListEnd(); } struct.setResponsesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, MultiGetBuildSlaveEventsResponse struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.responses != null) { if (struct.isSetResponses()) { oprot.writeFieldBegin(RESPONSES_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.responses.size())); for (BuildSlaveEventsRange _iter165 : struct.responses) { _iter165.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class MultiGetBuildSlaveEventsResponseTupleSchemeFactory implements SchemeFactory { public MultiGetBuildSlaveEventsResponseTupleScheme getScheme() { return new MultiGetBuildSlaveEventsResponseTupleScheme(); } } private static class MultiGetBuildSlaveEventsResponseTupleScheme extends TupleScheme<MultiGetBuildSlaveEventsResponse> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, MultiGetBuildSlaveEventsResponse struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetResponses()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetResponses()) { { oprot.writeI32(struct.responses.size()); for (BuildSlaveEventsRange _iter166 : struct.responses) { _iter166.write(oprot); } } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, MultiGetBuildSlaveEventsResponse struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list167 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.responses = new ArrayList<BuildSlaveEventsRange>(_list167.size); BuildSlaveEventsRange _elem168; for (int _i169 = 0; _i169 < _list167.size; ++_i169) { _elem168 = new BuildSlaveEventsRange(); _elem168.read(iprot); struct.responses.add(_elem168); } } struct.setResponsesIsSet(true); } } } }
apache-2.0
bmatthews68/inmemdb-maven-plugin
src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/AbstractLoader.java
6684
/* * Copyright 2011-2012 Brian Matthews * * 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.btmatthews.maven.plugins.inmemdb.ldr; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Locale; import com.btmatthews.maven.plugins.inmemdb.Loader; import com.btmatthews.maven.plugins.inmemdb.Source; import com.btmatthews.utils.monitor.Logger; /** * Abstract base class for loaders that implements the {@link * Loader#isSupported(com.btmatthews.utils.monitor.Logger, com.btmatthews.maven.plugins.inmemdb.Source)} method. * * @author <a href="mailto:brian@btmathews.com">Brian Matthews</a> * @version 1.0.0 */ public abstract class AbstractLoader implements Loader { /** * The prefix used to denote that a resource should be loaded from the classpath * rather than the file system. */ protected static final String CLASSPATH_PREFIX = "classpath:"; /** * The length of the classpath: prefix. */ protected static final int CLASSPATH_PREFIX_LENGTH = 10; /** * The message key for the error reported when an error occurs validating a * file. */ protected static final String CANNOT_VALIDATE_FILE = "cannot_validate_file"; /** * Get the extension of the files that the loader will support. * * @return The file extension. */ protected abstract String getExtension(); /** * Check the contents of the file to see if it is valid for this loader. * * @param logger Used to report errors and raise exceptions. * @param source The source data or script. * @return <ul> * <li><code>true</code> if the content is valid.</li> * <li><code>false</code> if the content is invalid.</li> * </ul> */ protected boolean hasValidContent(final Logger logger, final Source source) { return true; } /** * Determine whether or not the data or script can be loaded or executed. * * @param logger Used to report errors and raise exceptions. * @param source The source file containing the data or script. * @return <ul> * <li><code>true</code> if the data or script can be loaded or * executed.</li> * <li><code>false</code>if the data or script cannot be loaded or * executed.</li> * </ul> */ public final boolean isSupported(final Logger logger, final Source source) { boolean result = false; if (source != null) { final Locale locale = Locale.getDefault(); final String name = source.getSourceFile().toLowerCase(locale); if (name.endsWith(getExtension())) { if (source.getSourceFile().startsWith(CLASSPATH_PREFIX)) { result = hasValidContent(logger, source); } else { final File sourceFile = new File(source.getSourceFile()); result = sourceFile.isFile() && hasValidContent(logger, source); } } } return result; } /** * Determine if data set or script source is a file system or class path resource. If the name is prefixed with * classpath: then it is a class path resource. * * @param source The data set or script. * @return {@code true} if the source filename is prefixed with classpath:. Otherwise, {@code false}. */ protected boolean isClasspath(final Source source) { return source.getSourceFile().startsWith("classpath:"); } /** * Get an input stream for the data set or script source. * * @param source The data set or script. * @return An {@link InputStream} or {@code null} if the source cannot be found. * @throws IOException If there was an error creating the input stream. */ protected final InputStream getInputStream(final Source source) throws IOException { if (isClasspath(source)) { final String resource = source.getSourceFile().substring(CLASSPATH_PREFIX_LENGTH); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return classLoader.getResourceAsStream(resource); } else { final File file = new File(source.getSourceFile()); if (file.exists()) { return new FileInputStream(file); } } return null; } /** * Get a reader for the data set or script source. * * @param source The data set or script. * @return A {@link Reader} or {@code null} if the source cannot be found. * @throws IOException If there was an error creating the reader. */ protected final Reader getReader(final Source source) throws IOException { final InputStream inputStream = getInputStream(source); if (inputStream == null) { return null; } else { return new InputStreamReader(inputStream, System.getProperty("file.encoding")); } } public String getTableName(final Source source) { final String path = source.getSourceFile(); final int startIndex; final int endIndex = path.length() - getExtension().length(); if (isClasspath(source)) { final int dotPos = path.lastIndexOf("."); final int slashPos = path.lastIndexOf("/", CLASSPATH_PREFIX_LENGTH); if (slashPos == -1) { startIndex = CLASSPATH_PREFIX_LENGTH; } else { startIndex = slashPos + 1; } } else { final int slashPos = path.lastIndexOf("/"); if (slashPos == -1) { startIndex = 0; } else { startIndex = slashPos + 1; } } return path.substring(startIndex, endIndex); } }
apache-2.0
lpj1986/learn-javase
src/main/java/com/hitsoysauce/designpattern/command/Invoker.java
242
package com.hitsoysauce.designpattern.command; public class Invoker { private Command command; public Invoker(Command command) { this.command = command; } public void doInvokerAction() { command.execute(); } }
apache-2.0
leepc12/BigDataScript
src/org/bds/lang/StatementInclude.java
3584
package org.bds.lang; import java.io.File; import java.io.IOException; import org.antlr.v4.runtime.tree.ParseTree; import org.bds.Config; import org.bds.compile.CompilerMessages; import org.bds.compile.CompilerMessage.MessageType; import org.bds.scope.Scope; /** * Include statement: Get source from another file */ public class StatementInclude extends BlockWithFile { protected String parentFileName; /** * Find the appropriate file * @param includedFilename * @param parent : Parent file (where the 'include' statement is) */ public static File includeFile(String includedFilename, File parent) { File includedFile = new File(includedFilename); if (includedFile.exists() && includedFile.canRead()) return includedFile; // Not an absolute file name? Try to find relative to parent file if (!includedFile.isAbsolute()) { if (parent != null && parent.exists()) includedFile = new File(parent.getParent(), includedFilename); if (includedFile.exists() && includedFile.canRead()) return includedFile; // Try parent's canonical path (e.g. when file is a symLink) File parentCanon = null; try { parentCanon = parent.getCanonicalFile(); if (parentCanon != null && parentCanon.exists()) includedFile = new File(parentCanon.getParent(), includedFilename); if (includedFile.exists() && includedFile.canRead()) return includedFile; } catch (IOException e) { } // Try all include paths for (String incPath : Config.get().getIncludePath()) { File incDir = new File(incPath); includedFile = new File(incDir, includedFilename); if (includedFile.exists() && includedFile.canRead()) return includedFile; // Found the file? } } return null; } /** * Find the appropriate include file name */ public static String includeFileName(String includedFilename) { if (includedFilename.startsWith("\'") || includedFilename.startsWith("\"")) includedFilename = includedFilename.substring(1); // Remove leading quotes if (includedFilename.endsWith("\'") || includedFilename.endsWith("\"")) includedFilename = includedFilename.substring(0, includedFilename.length() - 1).trim(); // Remove trailing quotes if (!includedFilename.endsWith(".bds")) includedFilename += ".bds"; // Append '.bds' if needed (it's optional) return includedFilename; } private static boolean isValidFileName(String fileName) { if (fileName == null || fileName.length() == 0 || !fileName.trim().equals(fileName)) return false; return true; } public StatementInclude(BdsNode parent, ParseTree tree) { super(parent, tree); } public String getParentFileName() { return parentFileName; } @Override protected void parse(ParseTree tree) { setNeedsScope(false); // File name & parent file name: this is merely informational File parentFile = getParent().getFile(); parentFileName = (parentFile != null ? parentFile.toString() : null); fileName = includeFileName(tree.getChild(0).getChild(1).getText()); // Resolve file and read program text File includedFile = StatementInclude.includeFile(fileName, parentFile); setFile(includedFile); super.parse(tree.getChild(0)); // Block parses statement } @Override protected void typeCheck(Scope scope, CompilerMessages compilerMessages) { if (!isValidFileName(fileName)) compilerMessages.add(this, "include: Invalid file name '" + fileName + "'", MessageType.ERROR); super.typeCheck(scope, compilerMessages); } @Override public void typeChecking(Scope scope, CompilerMessages compilerMessages) { super.typeChecking(scope, compilerMessages); } }
apache-2.0
tectronics/gueryframework
src/tests/test/nz/ac/massey/cs/guery/softwareantipatterns/AbstractTest.java
5133
/* * Copyright 2011 Jens Dietrich Licensed under the GNU AFFERO GENERAL PUBLIC LICENSE, Version 3 * (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.gnu.org/licenses/agpl.html 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 test.nz.ac.massey.cs.guery.softwareantipatterns; import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.junit.BeforeClass; import org.junit.runners.Parameterized.Parameters; import com.google.common.base.Function; import com.google.common.collect.Lists; import nz.ac.massey.cs.gql4jung.TypeNode; import nz.ac.massey.cs.gql4jung.TypeRef; import nz.ac.massey.cs.guery.ComputationMode; import nz.ac.massey.cs.guery.GQL; import nz.ac.massey.cs.guery.Motif; import nz.ac.massey.cs.guery.MotifInstance; import nz.ac.massey.cs.guery.MotifReader; import nz.ac.massey.cs.guery.PathFinder; import nz.ac.massey.cs.guery.adapters.jungalt.JungAdapter; import nz.ac.massey.cs.guery.impl.BreadthFirstPathFinder; import nz.ac.massey.cs.guery.impl.GQLImpl; import nz.ac.massey.cs.guery.impl.ccc.CCCPathFinder; import nz.ac.massey.cs.guery.io.dsl.DefaultMotifReader; import nz.ac.massey.cs.guery.util.ResultCollector; import edu.uci.ics.jung.graph.DirectedGraph; /** * Abstract test case. * @author jens dietrich */ public class AbstractTest { protected GQL<TypeNode,TypeRef> engine = new GQLImpl<TypeNode,TypeRef>(); protected PathFinder<TypeNode,TypeRef> pathFinder = new BreadthFirstPathFinder<TypeNode, TypeRef>(false); private static DirectedGraph<TypeNode, TypeRef> graph = null; protected static Motif<TypeNode, TypeRef> cd = null; protected static Motif<TypeNode, TypeRef> awd = null; protected static Motif<TypeNode, TypeRef> stk = null; protected static Motif<TypeNode, TypeRef>[] motifs = null; protected static final String TESTDATADIR = "testdata/"; public AbstractTest(GQL<TypeNode, TypeRef> engine, PathFinder<TypeNode, TypeRef> pathFinder) { super(); this.engine = engine; this.pathFinder = pathFinder; } @BeforeClass public static void readMotifs() throws Exception { // read motifs cd = readMotif(TESTDATADIR + "cd.guery"); awd = readMotif(TESTDATADIR + "awd.guery"); stk = readMotif(TESTDATADIR + "stk.guery"); motifs = new Motif[]{cd,awd,stk}; } private static Motif<TypeNode, TypeRef> readMotif(String f) throws Exception { File file = new File(f); InputStream in = new FileInputStream(file); MotifReader<TypeNode,TypeRef> reader = new DefaultMotifReader<TypeNode,TypeRef>(); Motif<TypeNode, TypeRef> motif = reader.read(in); in.close(); System.out.println("Read motif from " + file.getAbsolutePath()); return motif; } @Parameters public static Collection<Object[]> getConfig() { return Arrays.asList(new Object[][] { new Object[]{new GQLImpl<TypeNode,TypeRef>(),new BreadthFirstPathFinder<TypeNode, TypeRef>(false)}, new Object[]{new GQLImpl<TypeNode,TypeRef>(),new CCCPathFinder<TypeNode, TypeRef>()} }); } protected void checkResults(List<MotifInstance<TypeNode, TypeRef>> results,Collection<Map<String, String>> expectedResultsCd) { Collection<Map<String,String>> resultsAsMaps = new HashSet<Map<String,String>>(); resultsAsMaps.addAll(Lists.transform(results,new Function<MotifInstance<TypeNode, TypeRef>, Map<String,String>>() { @Override public Map<String, String> apply(MotifInstance<TypeNode, TypeRef> mi) { Map<String, String> map = new HashMap<String, String>(); List<String> roles = mi.getMotif().getRoles(); for (String role:roles) { map.put(role,mi.getVertex(role).getFullname()); } return map; } })); // check whether each expected result is computed (completeness) for (Map<String, String> expected:expectedResultsCd) { // for debugging boolean success = resultsAsMaps.contains(expected); if (!success) { System.out.println("The following instance was expected but not computed"); for (Map.Entry<String,String> e:expected.entrySet()) { System.out.print(e.getKey()); System.out.print(" -> "); System.out.println(e.getValue()); } } assertTrue(success); } } protected List<MotifInstance<TypeNode, TypeRef>> query(DirectedGraph<TypeNode, TypeRef> graph,Motif<TypeNode, TypeRef> motif,GQL<TypeNode, TypeRef> gql,PathFinder<TypeNode, TypeRef> pf) { ResultCollector<TypeNode,TypeRef> collector = new ResultCollector<TypeNode,TypeRef>(); gql.query(new JungAdapter<TypeNode,TypeRef>(graph), motif, collector, ComputationMode.ALL_INSTANCES,pf); return collector.getInstances(); } }
apache-2.0