code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2012 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 org.ros.concurrent;
/**
* Decouples specific listener interfaces from the signaling implementation.
*
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
* the type of listener
*/
public interface SignalRunnable<T> {
/**
* This method will be called when the listener should be signaled. Users
* should override this method to call the appropriate listener method(s).
*
* @param listener
* the listener to signal
*/
void run(T listener);
} | Java |
package org.ros.concurrent;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A {@link ScheduledExecutorService} which cannot be shut down. This can be
* safely injected into instances which should not be in control of the
* {@link ExecutorService}'s lifecycle.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public class SharedScheduledExecutorService implements ScheduledExecutorService {
/**
* The scheduledExecutorService {@link ScheduledExecutorService}.
*/
private ScheduledExecutorService scheduledExecutorService;
public SharedScheduledExecutorService(ScheduledExecutorService wrapped) {
this.scheduledExecutorService = wrapped;
}
/**
* @see java.util.concurrent.ExecutorService#awaitTermination(long,
* java.util.concurrent.TimeUnit)
*/
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return scheduledExecutorService.awaitTermination(timeout, unit);
}
/**
* @param command
* @see java.util.concurrent.Executor#execute(java.lang.Runnable)
*/
@Override
public void execute(Runnable command) {
scheduledExecutorService.execute(command);
}
/**
* @see java.util.concurrent.ExecutorService#invokeAll(java.util.Collection,
* long, java.util.concurrent.TimeUnit)
*/
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout,
TimeUnit unit) throws InterruptedException {
return scheduledExecutorService.invokeAll(tasks, timeout, unit);
}
/**
* @see java.util.concurrent.ExecutorService#invokeAll(java.util.Collection)
*/
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
return scheduledExecutorService.invokeAll(tasks);
}
/**
* @see java.util.concurrent.ExecutorService#invokeAny(java.util.Collection,
* long, java.util.concurrent.TimeUnit)
*/
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return scheduledExecutorService.invokeAny(tasks, timeout, unit);
}
/**
* @see java.util.concurrent.ExecutorService#invokeAny(java.util.Collection)
*/
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException,
ExecutionException {
return scheduledExecutorService.invokeAny(tasks);
}
/**
* @see java.util.concurrent.ExecutorService#isShutdown()
*/
@Override
public boolean isShutdown() {
return scheduledExecutorService.isShutdown();
}
/**
* @see java.util.concurrent.ExecutorService#isTerminated()
*/
@Override
public boolean isTerminated() {
return scheduledExecutorService.isTerminated();
}
/**
* @see java.util.concurrent.ScheduledExecutorService#schedule(java.util.concurrent.Callable,
* long, java.util.concurrent.TimeUnit)
*/
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(callable, delay, unit);
}
/**
* @see java.util.concurrent.ScheduledExecutorService#schedule(java.lang.Runnable,
* long, java.util.concurrent.TimeUnit)
*/
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(command, delay, unit);
}
/**
* @see java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate(java.lang.Runnable,
* long, long, java.util.concurrent.TimeUnit)
*/
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period,
TimeUnit unit) {
return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit);
}
/**
* @see java.util.concurrent.ScheduledExecutorService#scheduleWithFixedDelay(java.lang.Runnable,
* long, long, java.util.concurrent.TimeUnit)
*/
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
TimeUnit unit) {
return scheduledExecutorService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
/**
* @see java.util.concurrent.ExecutorService#shutdown()
*/
@Override
public void shutdown() {
throw new UnsupportedOperationException("Cannot shut down service");
}
/**
* @see java.util.concurrent.ExecutorService#shutdownNow()
*/
@Override
public List<Runnable> shutdownNow() {
throw new UnsupportedOperationException("Cannot shut down service");
}
/**
* @see java.util.concurrent.ExecutorService#submit(java.util.concurrent.Callable)
*/
@Override
public <T> Future<T> submit(Callable<T> task) {
return scheduledExecutorService.submit(task);
}
/**
* @see java.util.concurrent.ExecutorService#submit(java.lang.Runnable,
* java.lang.Object)
*/
@Override
public <T> Future<T> submit(Runnable task, T result) {
return scheduledExecutorService.submit(task, result);
}
/**
* @see java.util.concurrent.ExecutorService#submit(java.lang.Runnable)
*/
@Override
public Future<?> submit(Runnable task) {
return scheduledExecutorService.submit(task);
}
} | Java |
/*
* Copyright (C) 2011 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 org.ros.concurrent;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* A {@link WatchdogTimer} expects to receive a {@link #pulse()} at least once
* every {@link #period} {@link #unit}s. Once per every period in which a
* {@link #pulse()} is not received, the provided {@link Runnable} will be
* executed.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class WatchdogTimer {
private final ScheduledExecutorService scheduledExecutorService;
private final long period;
private final TimeUnit unit;
private final Runnable runnable;
private boolean pulsed;
private ScheduledFuture<?> scheduledFuture;
public WatchdogTimer(ScheduledExecutorService scheduledExecutorService, long period,
TimeUnit unit, final Runnable runnable) {
this.scheduledExecutorService = scheduledExecutorService;
this.period = period;
this.unit = unit;
this.runnable = new Runnable() {
@Override
public void run() {
try {
if (!pulsed) {
runnable.run();
}
} finally {
pulsed = false;
}
}
};
pulsed = false;
}
public void start() {
scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(runnable, period, period, unit);
}
public void pulse() {
pulsed = true;
}
public void cancel() {
scheduledFuture.cancel(true);
}
}
| Java |
/*
* Copyright (C) 2011 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 org.ros.concurrent;
import com.google.common.base.Preconditions;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* A mutable object that may contain a value to another object. It is modifiable
* exactly once and must hold a non-null value when the value is inspected.
*
* <p>
* {@link Holder}s are intended for receiving a result from an anonymous class.
*
* <p>
* Note that {@link Holder} is not thread safe. For a thread safe
* implementation, use {@link AtomicReference}. Also note that two different
* {@link Holder} instances are never considered equal.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class Holder<T> {
private final CountDownLatch latch;
private T value;
public static <T> Holder<T> newEmpty() {
return new Holder<T>();
}
private Holder() {
latch = new CountDownLatch(1);
value = null;
}
public T set(T value) {
Preconditions.checkState(this.value == null);
this.value = value;
latch.countDown();
return value;
}
public T get() {
Preconditions.checkNotNull(value);
return value;
}
public void await() throws InterruptedException {
latch.await();
}
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
return latch.await(timeout, unit);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
return false;
}
}
| Java |
/*
* Copyright (C) 2011 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 org.ros.concurrent;
import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.exception.RosRuntimeException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Wraps an {@link ScheduledExecutorService} to execute {@link Callable}s with
* retries.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class RetryingExecutorService {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(RetryingExecutorService.class);
private static final long DEFAULT_RETRY_DELAY = 5;
private static final TimeUnit DEFAULT_RETRY_TIME_UNIT = TimeUnit.SECONDS;
private final ScheduledExecutorService scheduledExecutorService;
private final RetryLoop retryLoop;
private final Map<Callable<Boolean>, CountDownLatch> latches;
private final Map<Future<Boolean>, Callable<Boolean>> callables;
private final CompletionService<Boolean> completionService;
private final Object mutex;
private long retryDelay;
private TimeUnit retryTimeUnit;
private boolean running;
private class RetryLoop extends CancellableLoop {
@Override
public void loop() throws InterruptedException {
Future<Boolean> future = completionService.take();
final Callable<Boolean> callable = callables.remove(future);
boolean retry;
try {
retry = future.get();
} catch (ExecutionException e) {
throw new RosRuntimeException(e.getCause());
}
if (retry) {
if (DEBUG) {
log.info("Retry requested.");
}
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
submit(callable);
}
}, retryDelay, retryTimeUnit);
} else {
latches.get(callable).countDown();
}
}
}
/**
* @param scheduledExecutorService
* the {@link ExecutorService} to wrap
*/
public RetryingExecutorService(ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorService = scheduledExecutorService;
retryLoop = new RetryLoop();
latches = Maps.newConcurrentMap();
callables = Maps.newConcurrentMap();
completionService = new ExecutorCompletionService<Boolean>(scheduledExecutorService);
mutex = new Object();
retryDelay = DEFAULT_RETRY_DELAY;
retryTimeUnit = DEFAULT_RETRY_TIME_UNIT;
running = true;
// TODO(damonkohler): Unify this with the passed in ExecutorService.
scheduledExecutorService.execute(retryLoop);
}
/**
* Submit a new {@link Callable} to be executed. The submitted
* {@link Callable} should return {@code true} to be retried, {@code false}
* otherwise.
*
* @param callable
* the {@link Callable} to execute
* @throws RejectedExecutionException
* if the {@link RetryingExecutorService} is shutting down
*/
public void submit(Callable<Boolean> callable) {
synchronized (mutex) {
if (running) {
Future<Boolean> future = completionService.submit(callable);
latches.put(callable, new CountDownLatch(1));
callables.put(future, callable);
} else {
throw new RejectedExecutionException();
}
}
}
/**
* @param delay
* the delay in units of {@code unit}
* @param unit
* the {@link TimeUnit} of the delay
*/
public void setRetryDelay(long delay, TimeUnit unit) {
retryDelay = delay;
retryTimeUnit = unit;
}
/**
* Stops accepting new {@link Callable}s and waits for all submitted
* {@link Callable}s to finish within the specified timeout.
*
* @param timeout
* the timeout in units of {@code unit}
* @param unit
* the {@link TimeUnit} of {@code timeout}
* @throws InterruptedException
*/
public void shutdown(long timeout, TimeUnit unit) throws InterruptedException {
running = false;
for (CountDownLatch latch : latches.values()) {
latch.await(timeout, unit);
}
retryLoop.cancel();
}
} | Java |
/*
* Copyright (C) 2012 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 org.ros.concurrent;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public interface Rate {
/**
* Sleeps until the configured rate is achieved.
*/
void sleep();
}
| Java |
/*
* Copyright (C) 2012 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 org.ros.concurrent;
/**
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
* the listener type
*/
public class EventDispatcher<T> extends CancellableLoop {
private final T listener;
private final CircularBlockingDeque<SignalRunnable<T>> events;
public EventDispatcher(T listener, int queueCapacity) {
this.listener = listener;
events = new CircularBlockingDeque<SignalRunnable<T>>(queueCapacity);
}
public void signal(final SignalRunnable<T> signalRunnable) {
events.addLast(signalRunnable);
}
@Override
public void loop() throws InterruptedException {
SignalRunnable<T> signalRunnable = events.takeFirst();
signalRunnable.run(listener);
}
} | Java |
/*
* Copyright (C) 2011 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 org.ros.concurrent;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* This wraps a {@link Executors#newCachedThreadPool()} and a
* {@link Executors#newScheduledThreadPool(int)} to provide the functionality of
* both in a single {@link ScheduledExecutorService}. This is necessary since
* the {@link ScheduledExecutorService} uses an unbounded queue which makes it
* impossible to create an unlimited number of threads on demand (as explained
* in the {@link ThreadPoolExecutor} class javadoc.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultScheduledExecutorService implements ScheduledExecutorService {
private static final int CORE_POOL_SIZE = 11;
private final ExecutorService executorService;
private final ScheduledExecutorService scheduledExecutorService;
public DefaultScheduledExecutorService() {
this(Executors.newCachedThreadPool());
}
/**
* This instance will take over the lifecycle of the services.
*
* @param executorService
*/
public DefaultScheduledExecutorService(ExecutorService executorService) {
this(executorService, Executors.newScheduledThreadPool(CORE_POOL_SIZE));
}
/**
* This instance will take over the lifecycle of the services.
*
* @param executorService
* @param scheduledExecutorService
*/
public DefaultScheduledExecutorService(ExecutorService executorService,
ScheduledExecutorService scheduledExecutorService) {
this.executorService = executorService;
this.scheduledExecutorService = scheduledExecutorService;
}
@Override
public void shutdown() {
executorService.shutdown();
scheduledExecutorService.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
List<Runnable> combined = Lists.newArrayList();
combined.addAll(executorService.shutdownNow());
combined.addAll(scheduledExecutorService.shutdownNow());
return combined;
}
@Override
public boolean isShutdown() {
return executorService.isShutdown() && scheduledExecutorService.isShutdown();
}
@Override
public boolean isTerminated() {
return executorService.isTerminated() && scheduledExecutorService.isTerminated();
}
/**
* First calls {@link #awaitTermination(long, TimeUnit)} on the wrapped
* {@link ExecutorService} and then {@link #awaitTermination(long, TimeUnit)}
* on the wrapped {@link ScheduledExecutorService}.
*
* @return {@code true} if both {@link Executor}s terminated, {@code false}
* otherwise
*/
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
boolean executorServiceResult = executorService.awaitTermination(timeout, unit);
boolean scheduledExecutorServiceResult =
scheduledExecutorService.awaitTermination(timeout, unit);
return executorServiceResult && scheduledExecutorServiceResult;
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return executorService.submit(task);
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return executorService.submit(task, result);
}
@Override
public Future<?> submit(Runnable task) {
return executorService.submit(task);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
return executorService.invokeAll(tasks);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout,
TimeUnit unit) throws InterruptedException {
return executorService.invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException,
ExecutionException {
return executorService.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return executorService.invokeAny(tasks, timeout, unit);
}
@Override
public void execute(Runnable command) {
executorService.execute(command);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(command, delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(callable, delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period,
TimeUnit unit) {
return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
TimeUnit unit) {
return scheduledExecutorService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
}
| Java |
/*
* Copyright (C) 2012 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 org.ros.concurrent;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* A group of listeners.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ListenerGroup<T> {
private final static int DEFAULT_QUEUE_CAPACITY = 128;
private final ExecutorService executorService;
private final Collection<EventDispatcher<T>> eventDispatchers;
public ListenerGroup(ExecutorService executorService) {
this.executorService = executorService;
eventDispatchers = Lists.newCopyOnWriteArrayList();
}
/**
* Adds a listener to the {@link ListenerGroup}.
*
* @param listener
* the listener to add
* @param queueCapacity
* the maximum number of events to buffer
* @return the {@link EventDispatcher} responsible for calling the specified
* listener
*/
public EventDispatcher<T> add(T listener, int queueCapacity) {
EventDispatcher<T> eventDispatcher = new EventDispatcher<T>(listener, queueCapacity);
eventDispatchers.add(eventDispatcher);
executorService.execute(eventDispatcher);
return eventDispatcher;
}
/**
* Adds the specified listener to the {@link ListenerGroup} with the queue
* limit set to {@link #DEFAULT_QUEUE_CAPACITY}.
*
* @param listener
* the listener to add
* @return the {@link EventDispatcher} responsible for calling the specified
* listener
*/
public EventDispatcher<T> add(T listener) {
return add(listener, DEFAULT_QUEUE_CAPACITY);
}
/**
* Adds all the specified listeners to the {@link ListenerGroup}.
*
* @param listeners
* the listeners to add
* @param limit
* the maximum number of events to buffer
* @return a {@link Collection} of {@link EventDispatcher}s responsible for
* calling the specified listeners
*/
public Collection<EventDispatcher<T>> addAll(Collection<T> listeners, int limit) {
Collection<EventDispatcher<T>> eventDispatchers = Lists.newArrayList();
for (T listener : listeners) {
eventDispatchers.add(add(listener, limit));
}
return eventDispatchers;
}
/**
* Adds all the specified listeners to the {@link ListenerGroup} with the
* queue capacity for each set to {@link Integer#MAX_VALUE}.
*
* @param listeners
* the listeners to add
* @return a {@link Collection} of {@link EventDispatcher}s responsible for
* calling the specified listeners
*/
public Collection<EventDispatcher<T>> addAll(Collection<T> listeners) {
return addAll(listeners, DEFAULT_QUEUE_CAPACITY);
}
/**
* @return the number of listeners in the group
*/
public int size() {
return eventDispatchers.size();
}
/**
* Signals all listeners.
* <p>
* Each {@link SignalRunnable} is executed in a separate thread.
*/
public void signal(SignalRunnable<T> signalRunnable) {
for (EventDispatcher<T> eventDispatcher : eventDispatchers) {
eventDispatcher.signal(signalRunnable);
}
}
/**
* Signals all listeners and waits for the result.
* <p>
* Each {@link SignalRunnable} is executed in a separate thread. In the event
* that the {@link SignalRunnable} is be dropped from the
* {@link EventDispatcher}'s queue and thus not executed, this method will
* block for the entire specified timeout.
*
* @return {@code true} if all listeners completed within the specified time
* limit, {@code false} otherwise
* @throws InterruptedException
*/
public boolean signal(final SignalRunnable<T> signalRunnable, long timeout, TimeUnit unit)
throws InterruptedException {
Collection<EventDispatcher<T>> copy = Lists.newArrayList(eventDispatchers);
final CountDownLatch latch = new CountDownLatch(copy.size());
for (EventDispatcher<T> eventDispatcher : copy) {
eventDispatcher.signal(new SignalRunnable<T>() {
@Override
public void run(T listener) {
signalRunnable.run(listener);
latch.countDown();
}
});
}
return latch.await(timeout, unit);
}
public void shutdown() {
for (EventDispatcher<T> eventDispatcher : eventDispatchers) {
eventDispatcher.cancel();
}
}
}
| Java |
/*
* Copyright (C) 2012 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.
*/
/**
* Provides the classes for communicating with the master.
*/
package org.ros.master.client; | Java |
/*
* Copyright (C) 2012 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 org.ros.master.client;
import java.util.Collection;
/**
* The state of the ROS graph as understood by the master.
*
* @author Keith M. Hughes
*/
public class SystemState {
/**
* All topics known.
*/
private final Collection<TopicSystemState> topics;
public SystemState(Collection<TopicSystemState> topics) {
this.topics = topics;
}
/**
* Get all topics in the system state.
*
* @return a collection of topics.
*/
public Collection<TopicSystemState> getTopics() {
return topics;
}
}
| Java |
/*
* Copyright (C) 2012 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 org.ros.master.client;
import org.ros.internal.node.client.MasterClient;
import org.ros.internal.node.response.Response;
import org.ros.internal.node.server.master.MasterServer;
import org.ros.internal.node.topic.TopicDeclaration;
import org.ros.node.Node;
import org.ros.node.service.ServiceServer;
import java.net.URI;
import java.util.List;
/**
* A remote client for obtaining system information from a master.
*
* @author Keith M. Hughes
*/
public class MasterStateClient {
/**
* The node doing the calling.
*/
private final Node caller;
/**
* Client for speaking to the master.
*/
private final MasterClient masterClient;
public MasterStateClient(Node caller, URI masterUri) {
this.caller = caller;
masterClient = new MasterClient(masterUri);
}
/**
* @param nodeName
* the name of the {@link Node} to lookup
* @return the {@link URI} of the {@link Node} with the given name
*/
public URI lookupNode(String nodeName) {
Response<URI> response = masterClient.lookupNode(caller.getName(), nodeName);
return response.getResult();
}
/**
* @return the {@link URI} of the {@link MasterServer}
*/
public URI getUri() {
Response<URI> response = masterClient.getUri(caller.getName());
return response.getResult();
}
/**
* @param serviceName
* the name of the {@link ServiceServer} to look up
* @return the {@link URI} of the {@link ServiceServer} with the given name
*/
public URI lookupService(String serviceName) {
Response<URI> result = masterClient.lookupService(caller.getName(), serviceName);
return result.getResult();
}
/**
* @param subgraph
* the subgraph of the topics
* @return a {@link List} of {@link TopicDeclaration}s for published topics
*/
public List<TopicDeclaration> getPublishedTopics(String subgraph) {
// TODO(keith): Figure out what to turn the topic definition into.
throw new UnsupportedOperationException();
}
/**
* @return a {@link List} of {@link TopicType}s known by the master
*/
public List<TopicType> getTopicTypes() {
Response<List<TopicType>> result = masterClient.getTopicTypes(caller.getName());
return result.getResult();
}
/**
* @return the current {@link SystemState}
*/
public SystemState getSystemState() {
Response<SystemState> result = masterClient.getSystemState(caller.getName());
return result.getResult();
}
}
| Java |
/*
* Copyright (C) 2012 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 org.ros.master.client;
import java.util.Set;
/**
* Information about a topic.
*
* @author Keith M. Hughes
*/
public class TopicSystemState {
/**
* Name of the topic.
*/
private final String topicName;
/**
* Node names of all publishers.
*/
private final Set<String> publishers;
/**
* Node names of all subscribers.
*/
private final Set<String> subscribers;
public TopicSystemState(String topicName, Set<String> publishers,
Set<String> subscribers) {
this.topicName = topicName;
this.publishers = publishers;
this.subscribers = subscribers;
}
/**
* @return the topicName
*/
public String getTopicName() {
return topicName;
}
/**
* Get the set of all nodes that publish the topic.
*
* @return the set of node names
*/
public Set<String> getPublishers() {
return publishers;
}
/**
* Get the set of all nodes that subscribe to the topic.
*
* @return the set of node names
*/
public Set<String> getSubscribers() {
return subscribers;
}
}
| Java |
/*
* Copyright (C) 2012 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 org.ros.master.client;
/**
* A simple collection of information about a topic.
*
* @author Keith M. Hughes
*/
public class TopicType {
/**
* Name of the topic.
*/
private final String name;
/**
* Message type of the topic.
*/
private final String messageType;
public TopicType(String name, String messageType) {
this.name = name;
this.messageType = messageType;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the messageType
*/
public String getMessageType() {
return messageType;
}
}
| Java |
/*
* Copyright (C) 2012 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.
*/
/**
* Provides the classes for communicating with and implementing the master.
*
* @see <a href="http://ros.org/wiki/Master">master documentation</a>
*/
package org.ros.master; | Java |
/*
* Copyright (C) 2012 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 org.ros.master.uri;
import com.google.common.collect.Lists;
import org.ros.exception.RosRuntimeException;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* A proxying {@link MasterUriProvider} which can be switched between providers.
*
* <p>
* This class is thread-safe.
*
* @author Keith M. Hughes
*/
public class SwitchableMasterUriProvider implements MasterUriProvider {
private final Object mutex;
/**
* The current provider in use.
*/
private MasterUriProvider provider;
/**
* The list of all pending requests.
*/
private List<ProviderRequest> pending = Lists.newArrayList();
/**
* @param provider
* the initial provider to use
*/
public SwitchableMasterUriProvider(MasterUriProvider provider) {
this.provider = provider;
mutex = new Object();
}
@Override
public URI getMasterUri() throws RosRuntimeException {
MasterUriProvider providerToUse = null;
ProviderRequest requestToUse = null;
synchronized (mutex) {
if (provider != null) {
providerToUse = provider;
} else {
requestToUse = new ProviderRequest();
pending.add(requestToUse);
}
}
if (providerToUse != null) {
return providerToUse.getMasterUri();
} else {
return requestToUse.getMasterUri();
}
}
@Override
public URI getMasterUri(long timeout, TimeUnit unit) {
// We can't really switch providers, but people are willing to wait. It
// seems appropriate to wait rather than to return immediately.
MasterUriProvider providerToUse = null;
synchronized (mutex) {
if (provider != null) {
providerToUse = provider;
}
}
if (providerToUse != null) {
return providerToUse.getMasterUri(timeout, unit);
} else {
try {
Thread.sleep(unit.toMillis(timeout));
} catch (InterruptedException e) {
// Don't care
}
return null;
}
}
/**
* Switch between providers.
*
* @param switcher
* the new provider
*/
public void switchProvider(MasterUriProviderSwitcher switcher) {
synchronized (mutex) {
MasterUriProvider oldProvider = provider;
provider = switcher.switchProvider(oldProvider);
if (oldProvider == null) {
for (ProviderRequest request : pending) {
request.setProvider(provider);
}
pending.clear();
}
}
}
/**
* Perform a switch between {@link MasterUriProvider} instances for the
* {@link SwitchableMasterUriProvider}.
*
* <p>
* This class permits the use of atomic provider switches.
*/
public interface MasterUriProviderSwitcher {
/**
* Switch the provider in use.
*
* @param oldProvider
* a reference to the provider which came before
*
* @return the new provider to use
*/
MasterUriProvider switchProvider(MasterUriProvider oldProvider);
}
/**
* A request for a URI which is blocked until it is available.
*/
private static class ProviderRequest {
/**
* The latch used to wait.
*/
private CountDownLatch latch = new CountDownLatch(1);
/**
* The provider which will give the eventual answer.
*/
private MasterUriProvider provider;
/**
* Get a service.
*
* <p>
* This call can block indefinitely.
*
* @return the master {@link URI}
*/
public URI getMasterUri() {
try {
latch.await();
return provider.getMasterUri();
} catch (InterruptedException e) {
throw new RosRuntimeException("URI provider interrupted", e);
}
}
/**
* Set the provider who will finally process the request.
*
* @param provider
* the {@link MasterUriProvider} to use
*/
public void setProvider(MasterUriProvider provider) {
this.provider = provider;
latch.countDown();
}
}
}
| Java |
/*
* Copyright (C) 2012 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.
*/
/**
* Provides the classes for representing master URIs.
*/
package org.ros.master.uri; | Java |
/*
* Copyright (C) 2011 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 org.ros.master.uri;
import org.ros.exception.RosRuntimeException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
/**
* Provides URLs for a ROS master.
*
* @author Keith M. Hughes
*/
public interface MasterUriProvider {
/**
* Get a master URI.
*
* <p>
* There is no guarantee that calling this class twice will provide the same
* URI.
*
* <p>
* This call may or may not block until a URI is available.
*
* @return a master URI
*
* @throws RosRuntimeException
* this exception may or may not be thrown if there is no master URI
* available
*/
URI getMasterUri() throws RosRuntimeException;
/**
* Get a master URI within a given amount of time.
*
* <p>
* There is no guarantee that calling this class twice will provide the same
* URI.
*
* <p>
* This call may or may not block until a URI is available.
*
* @param timeout
* the amount of time to wait for a URI
* @param unit
* the time unit for the wait time
*
* @return a master URI or {@code null} if none could be obtained within the
* timeout
*/
URI getMasterUri(long timeout, TimeUnit unit);
}
| Java |
/*
* Copyright (C) 2011 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 org.ros.master.uri;
import java.net.URI;
import java.util.concurrent.TimeUnit;
/**
* A {@link MasterUriProvider} which will always return the same URI.
*
* @author Keith M. Hughes
*/
public class StaticMasterUriProvider implements MasterUriProvider {
/**
* The URI which will always be returned.
*/
private final URI uri;
public StaticMasterUriProvider(URI uri) {
this.uri = uri;
}
@Override
public URI getMasterUri() {
return uri;
}
@Override
public URI getMasterUri(long timeout, TimeUnit unit) {
return uri;
}
}
| Java |
package Model;
import java.util.Stack;
public class Messages {
Stack<Message> m_Msgs;
public Messages()
{
m_Msgs = new Stack<Message>();
}
public byte[] pop()
{
return m_Msgs.pop().getBytes();
}
public void push(byte[] payload)
{
m_Msgs.push(new Message(payload));
}
public int size() {
return m_Msgs.size();
}
}
| Java |
package Model;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
public class Data {
private final byte[] NO_DATA_PULL = {1};
// eager initialization is both thread safe and will also load the data from db
private static volatile Data instance = new Data();
private Map<ByteBuffer, Messages> m_Data;
private Data()
{
m_Data = new HashMap<ByteBuffer, Messages>();
}
public static Data getInstance()
{
return instance;
}
public byte[] pull(byte[] id)
{
Messages msgs = m_Data.get(ByteBuffer.wrap(id));
if (msgs == null || msgs.size() == 0)
{
return NO_DATA_PULL;
}
return msgs.pop();
}
public void add(byte[] payload, byte[] key)
{
if (payload == null || payload.length <= 1)
return;
ByteBuffer tokenWrapper = ByteBuffer.wrap(key);
Messages msgs = m_Data.get(tokenWrapper);
if (msgs == null)
{
msgs = new Messages();
m_Data.put(tokenWrapper, msgs);
}
msgs.push(payload);
}
}
| Java |
package Model;
public class Message {
private byte[] m_Payload;
public Message(byte[] payload)
{
m_Payload = payload;
}
public byte[] getBytes()
{
return m_Payload;
}
}
| Java |
package Model;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class RequestHandler
{
private final int SIZE_OF_INT = 4;
private String m_NextAddress;
private Integer m_NextPort;
private byte[] payload;
private String m_Id;
public RequestHandler(byte[] msg)
{
int startFrom = 1;
byte lenOfAddress = msg[0];
byte[] address = Arrays.copyOfRange(msg, startFrom, startFrom + lenOfAddress);
m_NextAddress = new String(address);
startFrom += lenOfAddress;
byte[] port = Arrays.copyOfRange(msg, startFrom, startFrom + SIZE_OF_INT);
m_NextPort = ByteBuffer.wrap(port).getInt();
startFrom += SIZE_OF_INT;
byte lenOfId = msg[startFrom];
startFrom++;
byte[] id = Arrays.copyOfRange(msg, startFrom, startFrom + lenOfId);
m_Id = new String(id);
startFrom += lenOfId;
payload = Arrays.copyOfRange(msg, startFrom, msg.length);
}
public byte[] getMessage()
{
return payload;
}
public void send() {
try {
Socket skt = new Socket(m_NextAddress, m_NextPort);
DataInputStream in = new DataInputStream(skt.getInputStream());
DataOutputStream out = new DataOutputStream(skt.getOutputStream());
byte[] b = getMessage();
out.writeInt(b.length); // write length of the message
out.write(b);
// get client's request
byte[] message = null;
int length = in.readInt(); // read length of incoming message
if(length>0) {
message = new byte[length];
in.readFully(message, 0, message.length); // read the message
}
out.close();
in.close();
skt.close();
Data.getInstance().add(message, getMapKey());
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public byte[] getMapKey()
{
return arraysConcatenation(m_Id.getBytes(), m_NextAddress.getBytes());
}
private byte[] arraysConcatenation(Object... arrays)
{
int size = 0;
for (int i = 0; i < arrays.length; i++)
{
size += ((byte[])arrays[i]).length;
}
byte[] array = new byte[size];
int counter = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, array, counter, ((byte[])arrays[i]).length);
counter += ((byte[])arrays[i]).length;
}
return array;
}
}
| Java |
package Model;
import java.security.Key;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
public class Encryption
{
private String KEY;
private Cipher cipher;
public Encryption(String key)
{
try
{
KEY = key;
// Create key and cipher
Key aesKey = new SecretKeySpec(KEY.getBytes(), "AES");
cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
}
catch(Exception e)
{}
}
public byte[] decrypt(byte[] b) throws IllegalBlockSizeException, BadPaddingException
{
if (b == null || b.length == 0 || (b.length == 1 && b[0] == 1))
return b;
return cipher.doFinal(b);
}
} | Java |
package Controller;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import Model.Data;
import Model.Encryption;
import Model.RequestHandler;
public class Request extends Thread
{
private Socket m_Socket;
private Encryption m_Enc;
public Request(Socket connSocket, Encryption enc)
{
m_Socket = connSocket;
m_Enc = enc;
}
@Override
public void run()
{
DataInputStream in = null;
DataOutputStream out = null;
try
{
// client's input/output
in = new DataInputStream(m_Socket.getInputStream());
out = new DataOutputStream(m_Socket.getOutputStream());
// get client's request
byte[] message = null;
int length = in.readInt();
if(length>0) {
message = new byte[length];
in.readFully(message, 0, message.length);
}
// process request
byte[] msg = m_Enc.decrypt(message);
RequestHandler handler = new RequestHandler(msg);
byte[] result = m_Enc.decrypt(Data.getInstance().pull(handler.getMapKey()));
// send data back
out.writeInt(result.length);
out.write(result);
// add new data
handler.send();
}
catch(Exception e)
{
}
finally
{
try
{
out.close();
}
catch(Exception e)
{
}
try
{
in.close();
}
catch(Exception e)
{
}
try
{
m_Socket.close();
}
catch(Exception e)
{
}
}
}
}
| Java |
package Controller;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import Model.Encryption;
public class Server
{
private int m_Port;
public Server(int port)
{
m_Port = port;
}
public void start()
{
ServerSocket serverSocket = null;
Socket connSocket = null;
String key = null;
switch (m_Port)
{
case 3333:
key = "Bar12345Bar12345";
break;
case 4444:
key = "Bar12346Bar12345";
break;
case 5555:
key = "Bar12347Bar12345";
break;
case 6666:
key = "Bar12348Bar12345";
break;
default:
break;
}
Encryption enc = new Encryption(key);
try
{
System.out.println("starting mix at: " + m_Port);
// start listening
serverSocket = new ServerSocket(m_Port);
while (true)
{
// accept connections
connSocket = serverSocket.accept();
// create separate thread for each request
Request request = new Request(connSocket, enc);
request.start();
}
}
catch(Exception e)
{
}
finally
{
try
{
connSocket.close();
}
catch (IOException e)
{
}
try
{
serverSocket.close();
}
catch (IOException e)
{
}
}
}
}
| Java |
package Controller;
public class Start
{
public static void main(String[] args)
{
// start the server - on a specific port
Server server = new Server(3333);
//Server server = new Server(4444);
//Server server = new Server(5555);
//Server server = new Server(6666);
server.start();
}
}
| Java |
package Model;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Mixes
{
List<Mix> m_Mixes;
public Mixes()
{
m_Mixes = new ArrayList<Mix>();
try {
List<String> lines = Files.readAllLines(Paths.get("src/mixes.txt"), Charset.defaultCharset());
for (String line : lines) {
String[] params = line.split(" ");
m_Mixes.add(new Mix(params[0], params[1], params[2]));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Stack<Mix> get(Integer... indexes)
{
Stack<Mix> sublist = new Stack<Mix>();
for (Integer index : indexes) {
sublist.add(m_Mixes.get(index));
}
return sublist;
}
}
| Java |
package Model;
import java.nio.ByteBuffer;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Mix {
private String m_Address;
private Integer m_Port;
private String m_Key;
byte[] uuid;
private Cipher cipher;
public Mix(String address, String port, String key) {
m_Address = address;
m_Port = Integer.parseInt(port);
m_Key = key;
uuid = java.util.UUID.randomUUID().toString().getBytes();
try
{
// Create key and cipher
Key aesKey = new SecretKeySpec(m_Key.getBytes(), "AES");
cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
}
catch (Exception e) {
System.out.println("Invalid Key:" + e.getMessage());
return;
}
}
public byte[] encrypt(byte[] b, String nextAddress, Integer nextPort) {
try
{
byte[] address = nextAddress.getBytes();
byte[] port = ByteBuffer.allocate(4).putInt(nextPort).array();
byte[] len = new byte[1];
len[0] = (byte)address.length;
byte[] uuidLen = new byte[1];
uuidLen[0] = (byte)uuid.length;
return cipher.doFinal(arraysConcatenation(len, address, port, uuidLen, uuid, b));
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public byte[] encrypt(byte[] b) {
try
{
return cipher.doFinal(b);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private byte[] arraysConcatenation(Object... arrays)
{
int size = 0;
for (int i = 0; i < arrays.length; i++)
{
size += ((byte[])arrays[i]).length;
}
byte[] array = new byte[size];
int counter = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, array, counter, ((byte[])arrays[i]).length);
counter += ((byte[])arrays[i]).length;
}
return array;
}
public String getAddress() {
return m_Address;
}
public Integer getPort() {
return m_Port;
}
}
| Java |
package Model;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import bl.*;
public class TokenManager
{
enum eFlags
{
SimplePush((byte)1),
SimplePull((byte)2),
PushWithProof((byte)3),
PullWithProof((byte)4);
private final byte m_byte;
private eFlags(byte i)
{
m_byte = i;
}
public byte getByte()
{
return m_byte;
}
}
PublicParametersI m_ppClient;
TokenClassesManagerI m_manager;
VEBTokensGeneratorI m_ClientSideTokenGenerator;
FriendClientDataI m_clientDetails;
int m_epoch;
static SecureRandom sr = new SecureRandom();
byte[] m_clientPullTokenBytes;
byte[] m_clientProofBytes;
public TokenManager()
{
m_epoch = sr.nextInt(18376498);
// via the this interface you create instances of the relevant methods.
m_manager = new IntegersTokenClassesManager();
}
public void setPublicParameters(byte[] ppBytes) throws Exception
{
/*// verify the length of the public parameters bytes representation
if (ppBytes.length != ppPO.GetPublicParametersLengthBytes())
throw new Exception("The byte[] representation of the public parameters is different from the data in the public information");*/
m_ppClient = m_manager.CreatePublicParameters(ppBytes);
generateMyKies();
}
public void generateMyKies() throws IneligibleTypeException
{
// The client knows the public parameters and also his own secret key and the details of its friends.
// In this example, the client knows the "public" part of the identity (like in the simple scenario).
m_ClientSideTokenGenerator = m_manager.CreateVEBTokenGenerator(m_ppClient);
// Generate Secret Key (for the PRF, and possibly for messages encryption), and create identity for the client (both secret and "public" parameters)
m_clientDetails = m_manager.GenerateNewClient(m_ppClient);
// first create the token
VEBTokenI clientPullToken = m_ClientSideTokenGenerator.CreateToken(m_epoch, m_clientDetails);
m_clientPullTokenBytes = clientPullToken.getBytes(m_ppClient);
// then create the proof
NIZKproofI clientProof = m_ClientSideTokenGenerator.CreateProof(clientPullToken, m_clientDetails.getClientData());
m_clientProofBytes = clientProof.GetBytes();
}
public byte[] getMyToken()
{
return m_clientPullTokenBytes;
}
public String getMyTokenString()
{
StringBuilder sb=new StringBuilder();
for(byte s: m_clientPullTokenBytes)
sb.append(s + " ");
return sb.toString();
}
public byte[] getPullDummyToken()
{
return m_clientPullTokenBytes;
}
public byte[] getPushDummyToken()
{
return m_clientPullTokenBytes;
}
public byte[] getProof()
{
return m_clientProofBytes;
}
public byte[] getPushWithProofMessage(String message, byte[] token)
{
byte[] bMessage = message.getBytes();
return arraysConcatenation(eFlags.PushWithProof.getByte(), bMessage, token);
}
public byte[] getPushMessage(byte[] message, byte[] token)
{
return arraysConcatenation(token, message);
}
public byte[] getPullMessage(byte[] token)
{
return arraysConcatenation(eFlags.SimplePull.getByte(), token);
}
public byte[] getPullMessage(byte[] bs, byte[] bs2, Integer index)
{
return arraysConcatenation(new byte[]{eFlags.PullWithProof.getByte()}, bs, ByteBuffer.allocate(4).putInt(index).array(), bs2);
}
public byte[] getSimplePushSimplePull(byte[] message, byte[] token)
{
return arraysConcatenation(getPushMessage(message, token), getPullMessage(getMyToken()));
}
public byte[] arraysConcatenation(Object... arrays)
{
int size = 0;
for (int i = 0; i < arrays.length; i++)
{
size += ((byte[])arrays[i]).length;
}
byte[] array = new byte[size];
int counter = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, array, counter, ((byte[])arrays[i]).length);
counter += ((byte[])arrays[i]).length;
}
return array;
}
public byte[] getPubliParamsMessage()
{
byte[] b = new byte[1];
b[0] = 0;
return b;
}
public byte[] getPushAndPullMessage(byte[] token, byte[] proof, int index) {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package Controller;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Stack;
import Model.Mix;
import Model.Mixes;
import Model.TokenManager;
import View.Screen;
public class Sender
{
private final byte[] DUMMY_PUSH = {1};
private int index;
private int currentIndex;
private TokenManager m_Manager;
private Mixes m_Mixes;
@SuppressWarnings("unused")
private Screen m_Screen;
public Sender()
{
index = 0;
currentIndex = index;
m_Manager = new TokenManager();
setPublicParams();
m_Mixes = new Mixes();
m_Screen = new Screen(this);
}
private byte[] send(byte[] msg, String host, Integer port) {
try {
Socket skt = new Socket(host, port);
DataInputStream in = new DataInputStream(skt.getInputStream());
DataOutputStream out = new DataOutputStream(skt.getOutputStream());
byte[] b = msg;
out.writeInt(b.length); // write length of the message
out.write(b);
// get client's request
byte[] message = null;
int length = in.readInt(); // read length of incoming message
if(length>0) {
message = new byte[length];
in.readFully(message, 0, message.length); // read the message
}
out.close();
in.close();
skt.close();
boolean isMessageExists = message.length > 0;
if (isMessageExists)
{
return message;
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
return null;
}
private byte[] send(byte[] msg)
{
return send(msg, "localhost", 1234);
}
public void setPublicParams()
{
byte[] response = send(m_Manager.getPubliParamsMessage());
try {
m_Manager.setPublicParameters(response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private byte[] buildEncryptedMessage(byte[] b, Stack<Mix> mixes, String poAddress, int poPort)
{
byte[] msg = b;
Mix prev = mixes.pop();
msg = prev.encrypt(msg, poAddress, poPort);
while (!mixes.isEmpty())
{
Mix mix = mixes.pop();
msg = mix.encrypt(msg, prev.getAddress(), prev.getPort());
prev = mix;
}
return msg;
}
private byte[] buildEncryptedMessage(byte[] b, Stack<Mix> mixes)
{
byte[] msg = b;
Mix prev = mixes.pop();
msg = prev.encrypt(msg);
while (!mixes.isEmpty())
{
Mix mix = mixes.pop();
msg = mix.encrypt(msg);
prev = mix;
}
return msg;
}
public String pushPull(byte[] pushToken, String msg, byte[] pullToken)
{
Stack<Mix> pathBack = m_Mixes.get(3,2,1,0);
//Stack<Mix> pathBack = m_Mixes.get(0);
byte[] bMessage = DUMMY_PUSH;
if (!msg.isEmpty())
{
bMessage = buildEncryptedMessage(msg.getBytes(), pathBack);
}
byte[] bPush = m_Manager.getPushMessage(bMessage, pushToken);
byte[] bPull = m_Manager.getPullMessage(pullToken, m_Manager.getProof(), currentIndex);
//currentIndex = -1;
byte[] b = m_Manager.arraysConcatenation(bPull, bPush);
Stack<Mix> path = m_Mixes.get(0,1,2,3);
//Stack<Mix> path = m_Mixes.get(0);
byte[] message = buildEncryptedMessage(b, path, "localhost", 1234);
Mix firstMix = m_Mixes.get(0).get(0);
byte[] response = send(message, firstMix.getAddress(), firstMix.getPort());
String res = "";
if (response != null && response.length > 1)
{
res = new String(response);
index++;
currentIndex = index;
}
return res;
}
public String getMyPublicToken()
{
return m_Manager.getMyTokenString();
}
}
| Java |
package Controller;
public class Start
{
public static void main(String[] args)
{
new Sender();
}
}
| Java |
package View;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import Controller.Sender;
@SuppressWarnings("serial")
public class Screen extends JFrame
{
private String START = "Start";
private JPanel pnlMain;
private JButton btnStart;
private JTextField tbxMessage;
private JTextField tbxPushToken;
private JTextField tbxPullToken;
private JLabel lblMessageTitle;
private JLabel lblPushToken;
private JLabel lblPullToken;
private JLabel lblPulledMessage;
private JLabel lblPulledMessageTitle;
private Sender m_Sender;
byte[] pushToken;
byte[] pullToken;
int index;
String[] data;
public Screen(Sender sender)
{
super();
m_Sender = sender;
pnlMain = new JPanel(new GridLayout(0,1));
btnStart = new JButton(START);
tbxMessage = new JTextField();
tbxPullToken = new JTextField();
tbxPushToken = new JTextField();
lblPullToken = new JLabel();
lblPushToken = new JLabel();
lblMessageTitle = new JLabel();
lblPulledMessage = new JLabel();
lblPulledMessageTitle = new JLabel();
lblMessageTitle.setText("Message:");
lblPullToken.setText("Pull token:");
lblPushToken.setText("Push token:");
tbxMessage.setText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
tbxPullToken.setText(m_Sender.getMyPublicToken());
tbxPushToken.setText(m_Sender.getMyPublicToken());
lblPulledMessageTitle.setText("Message pulled: ");
setBounds(100,100,300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
con.add(pnlMain);
pnlMain.add(lblPushToken);
pnlMain.add(tbxPushToken);
pnlMain.add(lblPullToken);
pnlMain.add(tbxPullToken);
pnlMain.add(lblMessageTitle);
pnlMain.add(tbxMessage);
pnlMain.add(btnStart);
pnlMain.add(lblPulledMessageTitle);
pnlMain.add(lblPulledMessage);
btnStart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0)
{
pushToken = tokenFromString(tbxPushToken.getText());
pullToken = tokenFromString(tbxPullToken.getText());
data = tbxMessage.getText().split(" ");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
String msg = "";
if (index < data.length)
{
msg = data[index++];
}
String response = m_Sender.pushPull(pushToken, msg, pullToken);
if (!response.equals(""))
{
lblPulledMessage.setText(lblPulledMessage.getText() + " " + response);
}
}
}, 0, 100);
}
});
setVisible(true);
}
private byte[] tokenFromString(String t)
{
String[] temp = t.split(" ");
byte[] token = new byte[temp.length];
int i = 0;
for (String s : temp)
{
token[i++] = Byte.parseByte(s);
}
return token;
}
}
| Java |
package bl;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class IntegersFriendClientData implements FriendClientDataI {
public final static int BLOCK_SIZE = 16;
public final static String ENC_ALG = "AES/CBC/NoPadding"; // "AES/CBC/PKCS5Padding";
// // ;
public final static int keyLengthBits = 128;
SecretKey commonSecretKey;
IntegersClientData clientData;
public IntegersFriendClientData(SecretKey sc, IntegersClientData clientData) {
this.commonSecretKey = sc;
this.clientData = clientData;
}
public IntegersFriendClientData(IntegersPublicParameters ipp) {
this.clientData = new IntegersClientData(ipp);
// Generate (AES) key:
KeyGenerator keyGen = null;
try {
keyGen = KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
keyGen.init(keyLengthBits);
this.commonSecretKey = keyGen.generateKey();
}
public IntegersFriendClientData(SecretKey sc,
BigInteger identityPublicParameter) {
this.commonSecretKey = sc;
this.clientData = new IntegersClientData(identityPublicParameter);
}
public IntegersFriendClientData(SecretKey sc,
BigInteger identityPublicParameter,
BigInteger identitySecretParameter) {
this.commonSecretKey = sc;
this.clientData = new IntegersClientData(identityPublicParameter,
identitySecretParameter);
}
@Override
public Object getCommonSecretKey() {
return this.commonSecretKey;
}
@Override
public Object getIdentityPublicParameter() {
return this.clientData.getIdentityPublicParameter();
}
@Override
public Object getIdentitySecretParameter() {
return this.clientData.getIdentitySecretParameter();
}
@Override
public ClientDataI getClientData() {
return this.clientData;
}
}
| Java |
package bl;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Arrays;
public class IntegersPublicParameters implements PublicParametersI {
BigInteger G; // A prime number, represents the group Z*_G
BigInteger q; // The order of the group G
BigInteger g; // A generator for the group
int bitLength;
/**
* @param bitLength
* @throws Exception
* If the bitLengh parameter is not a positive number divided by 8.
*/
public IntegersPublicParameters(int bitLength) throws Exception {
SecureRandom sr = new SecureRandom();
if (bitLength % 8 != 0 || bitLength <= 0) {
throw new Exception(
"bitLength must be a positive number divided by 8.");
}
this.bitLength = bitLength;
/*
* To make sure that in the BigIntegers in both the proof and the tokens
* bitLength/8 bytes will be enough (the MSB must be zero, and if in
* unsigned representation it should be 1, another byte is necessary).
*/
this.G = BigInteger.probablePrime(bitLength - 1, sr);
this.q = this.G.subtract(BigInteger.ONE);
do {
this.g = new BigInteger(bitLength, sr);
} while (this.g.compareTo(G) >= 0);
}
public IntegersPublicParameters(byte[] bytes) throws Exception {
if (bytes.length % 3 != 0 || bytes.length == 0)
throw new Exception(
"The bytes array must be of a positive length divided by 3.");
int third = bytes.length / 3;
this.G = new BigInteger(Arrays.copyOfRange(bytes, 0, third));
this.q = new BigInteger(Arrays.copyOfRange(bytes, third, 2*third));
this.g = new BigInteger(Arrays.copyOfRange(bytes, 2*third, bytes.length));
this.bitLength = third * 8;
}
/*
@Override
public Object GetGroup() {
return G;
}
@Override
public BigInteger GetOrder() {
return q;
}
@Override
public Object GetGenerator() {
return g;
}
*/
@Override
public int GetTokenLengthBytes() {
return bitLength / 8;
}
@Override
public int GetProofLengthBytes() {
return bitLength / 4;
}
@Override
public int GetBitLength() {
return bitLength;
}
@Override
public byte[] GetBytes() {
int byteLength = this.bitLength / 8;
return Common.concat( Common.CreatePaddedBigIntegerBytes(this.G, byteLength), Common.concat(
Common.CreatePaddedBigIntegerBytes(this.q, byteLength),
Common.CreatePaddedBigIntegerBytes(this.g, byteLength)));
}
@Override
public int GetPublicParametersLengthBytes() {
return (this.bitLength * 3) / 8;
}
}
| Java |
package bl;
import java.math.BigInteger;
import javax.crypto.SecretKey;
public class IntegersTokenClassesManager implements TokenClassesManagerI {
@Override
public PublicParametersI CreatePublicParameters(int bitLength)
throws Exception {
return new IntegersPublicParameters(bitLength);
}
@Override
public VEBTokensGeneratorI CreateVEBTokenGenerator(PublicParametersI ipp)
throws IneligibleTypeException {
if (!(ipp instanceof IntegersPublicParameters)) {
throw new IneligibleTypeException();
}
return new IntegersVEBTokensGenerator((IntegersPublicParameters) ipp);
}
@Override
public FriendClientDataI CreateFriendClientDataI(ClientDataI clientData,
Object... objects) throws IneligibleTypeException {
if (objects.length == 1 && clientData instanceof IntegersClientData
&& objects[0] instanceof SecretKey) {
return new IntegersFriendClientData((SecretKey) objects[0],
(IntegersClientData) clientData);
} else {
throw new IneligibleTypeException();
}
}
@Override
public ClientDataI CreateClientDataI(Object... objects)
throws IneligibleTypeException {
if (objects.length == 1 && objects[0] instanceof BigInteger) {
return new IntegersClientData((BigInteger) objects[0]);
}
if (objects.length == 2 && objects[0] instanceof BigInteger
&& objects[0] instanceof BigInteger) {
return new IntegersClientData((BigInteger) objects[0],
(BigInteger) objects[1]);
} else {
throw new IneligibleTypeException();
}
}
@Override
public FriendClientDataI GenerateNewClient(PublicParametersI pp)
throws IneligibleTypeException {
if (!(pp instanceof IntegersPublicParameters)) {
throw new IneligibleTypeException();
}
return new IntegersFriendClientData((IntegersPublicParameters) pp);
}
@Override
public PublicParametersI CreatePublicParameters(byte[] ppBytes) throws Exception {
return new IntegersPublicParameters(ppBytes);
}
}
| Java |
package bl;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class IntegersVEBTokensGenerator implements VEBTokensGeneratorI {
private IntegersPublicParameters ipp;
public IntegersVEBTokensGenerator(IntegersPublicParameters ipp) {
this.ipp = ipp;
}
@Override
public PublicParametersI GetPublicParameters() {
return ipp;
}
public BigInteger CreateEBToken(int epoch, FriendClientDataI client)
throws IneligibleTypeException {
if (!(client instanceof IntegersFriendClientData)) {
throw new IneligibleTypeException();
}
IntegersFriendClientData ifcd = (IntegersFriendClientData) client;
BigInteger publicIdentityParam = (BigInteger) ifcd
.getIdentityPublicParameter();
// TEST:
BigInteger b1 = PRF(ifcd.commonSecretKey, epoch, publicIdentityParam);
BigInteger b2 = PRF(ifcd.commonSecretKey, epoch, publicIdentityParam);
if (b1.compareTo(b2) != 0)
System.out.println("ERRRO");
// //
return PRF(ifcd.commonSecretKey, epoch, publicIdentityParam);
}
@Override
public VEBTokenI CreateToken(int epoch, FriendClientDataI client)
throws IneligibleTypeException {
if (!(client instanceof IntegersFriendClientData)) {
throw new IneligibleTypeException();
}
IntegersFriendClientData ifcd = (IntegersFriendClientData) client;
BigInteger publicIdentityParam = (BigInteger) ifcd
.getIdentityPublicParameter();
// BigInteger secretIdentityParam =
// (BigInteger)ifcd.getIdentitySecretParameter();
BigInteger tec = PRF(ifcd.commonSecretKey, epoch, publicIdentityParam);
// TEST:
BigInteger b1 = PRF(ifcd.commonSecretKey, epoch, publicIdentityParam);
BigInteger b2 = PRF(ifcd.commonSecretKey, epoch, publicIdentityParam);
if (b1.compareTo(b2) != 0)
System.out.println("ERRRO");
// //
return new IntegersVEBToken(
publicIdentityParam.modPow(tec, this.ipp.G), tec);
}
private BigInteger PRF(SecretKey sc, int epoch, BigInteger identity) {
byte[] output = null;
try {
Cipher enc = Cipher.getInstance(IntegersFriendClientData.ENC_ALG);
enc.init(Cipher.ENCRYPT_MODE, sc, new IvParameterSpec(
new byte[IntegersFriendClientData.BLOCK_SIZE]));
byte[] epochBytes = ByteBuffer.allocate(4).putInt(epoch).array();
byte[] identityBytes = Common.CreatePaddedBigIntegerBytes(identity,
this.ipp.GetBitLength() / 8);
byte[] input = Common.concat(identityBytes, epochBytes);
// Add 0-byte bytes, so the number of bytes is divided by 16:
int rem = input.length % IntegersFriendClientData.BLOCK_SIZE;
if (rem > 0) {
input = Common.concat(input,
new byte[IntegersFriendClientData.BLOCK_SIZE - rem]);
}
output = enc.doFinal(input);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (new BigInteger(output)).mod(this.ipp.G);
}
@Override
public NIZKproofI CreateProof(VEBTokenI vtoken, ClientDataI client)
throws IneligibleTypeException {
if (!(vtoken instanceof IntegersVEBToken)
|| !(client instanceof IntegersClientData)) {
throw new IneligibleTypeException();
}
return new IntegersNIZKproof(this.ipp, (IntegersVEBToken) vtoken,
((IntegersClientData) client).identitySecretParameter);
}
@Override
public VEBTokenI ParseTokenBytes(byte[] bytes) {
if (bytes.length != ipp.GetTokenLengthBytes()) {
throw new InvalidParameterException("Expected to get "
+ ipp.GetTokenLengthBytes() + " bytes. Received instead "
+ bytes.length);
}
return new IntegersVEBToken(bytes, this.ipp);
}
@Override
public NIZKproofI ParseProofBytes(byte[] bytes) {
if (bytes.length != ipp.GetProofLengthBytes()) {
throw new InvalidParameterException("Expected to get "
+ ipp.GetProofLengthBytes() + " bytes. Received instead "
+ bytes.length);
}
return new IntegersNIZKproof(bytes, ipp);
}
}
| Java |
package bl;
import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.util.Arrays;
public class IntegersNIZKproof implements NIZKproofI {
BigInteger p1;
BigInteger p2;
private int byteLength;
public IntegersNIZKproof(BigInteger p1, BigInteger p2, int byteLengh) {
this.p1 = p1;
this.p2 = p2;
if (byteLengh % 2 == 1) {
throw new InvalidParameterException("byteLength must be even");
}
this.byteLength = byteLengh;
}
public IntegersNIZKproof(IntegersPublicParameters ipp,
IntegersVEBToken vtoken, BigInteger sc)
throws IneligibleTypeException {
// choose random rho
BigInteger rho = Common.randBigInteger(ipp.G, ipp.GetBitLength());
this.p1 = ipp.g.modPow(rho, ipp.G);
BigInteger h = vtoken.CalculateH(p1, ipp);
// because we use p2 only as the exponent of the generator in G, we can
// send it modulu the order of G, which is q.
this.p2 = ((((h.multiply(sc)).mod(ipp.q)).multiply(vtoken.EBtoken))
.mod(ipp.q)).add(rho).mod(ipp.q);
this.byteLength = ipp.GetProofLengthBytes();
}
public IntegersNIZKproof(byte[] bytes, IntegersPublicParameters ipp) {
this.byteLength = ipp.GetProofLengthBytes();
int arrayMidIndex = ipp.GetProofLengthBytes() / 2;
byte[] p1Bytes = Arrays.copyOfRange(bytes, 0, arrayMidIndex);
byte[] p2Bytes = Arrays.copyOfRange(bytes, arrayMidIndex,
ipp.GetProofLengthBytes());
this.p1 = new BigInteger(p1Bytes);
this.p2 = new BigInteger(p2Bytes);
}
@Override
public byte[] GetBytes() {
return Common.concat(
Common.CreatePaddedBigIntegerBytes(p1, this.byteLength / 2),
Common.CreatePaddedBigIntegerBytes(p2, this.byteLength / 2));
}
}
| Java |
package bl;
import java.math.BigInteger;
public class IntegersClientData implements ClientDataI {
BigInteger identityPublicParameter;
BigInteger identitySecretParameter;
public IntegersClientData(IntegersPublicParameters ipp) {
// Generate secret identity parameter:
this.identitySecretParameter = Common.randBigInteger(ipp.G,
ipp.bitLength - 1);
this.identityPublicParameter = ipp.g.modPow(
this.identitySecretParameter, ipp.G);
}
public IntegersClientData(BigInteger identityPublicParameter) {
this.identityPublicParameter = identityPublicParameter;
this.identitySecretParameter = null;
}
public IntegersClientData(BigInteger identityPublicParameter,
BigInteger identitySecretParameter) {
this.identityPublicParameter = identityPublicParameter;
this.identitySecretParameter = identitySecretParameter;
}
@Override
public Object getIdentityPublicParameter() {
return this.identityPublicParameter;
}
@Override
public Object getIdentitySecretParameter() {
return this.identitySecretParameter;
}
}
| Java |
package bl;
import java.math.BigInteger;
import java.security.InvalidParameterException;
public class IntegersVEBToken implements VEBTokenI {
public BigInteger EBtoken;
private BigInteger token;
public IntegersVEBToken(BigInteger veb, BigInteger eb) {
this.token = veb;
this.EBtoken = eb;
}
public IntegersVEBToken(byte[] bytes, IntegersPublicParameters ipp) {
this.EBtoken = null;
this.token = new BigInteger(bytes);
if (this.token.compareTo(BigInteger.ZERO) < 0
|| this.token.compareTo(ipp.G) >= 0) {
this.token = null;
throw new InvalidParameterException(
"Token value must be between 0 to the group order");
}
}
public BigInteger CalculateH(BigInteger bi, IntegersPublicParameters ipp)
throws IneligibleTypeException {
return new BigInteger(Common.SHA256(Common.concat(this.getBytes(ipp),
bi.toByteArray())));
}
@Override
public boolean Verify(NIZKproofI p, PublicParametersI pp)
throws IneligibleTypeException {
if (!(pp instanceof IntegersPublicParameters)
|| !(p instanceof IntegersNIZKproof)) {
throw new IneligibleTypeException();
}
IntegersNIZKproof proof = (IntegersNIZKproof) p;
IntegersPublicParameters ipp = (IntegersPublicParameters) pp;
BigInteger p1 = proof.p1;
BigInteger p2 = proof.p2;
// VERIFICATION GOES HERE
BigInteger h = this.CalculateH(p1, ipp);
BigInteger val1 = ipp.g.modPow(p2, ipp.G);
BigInteger val2 = (this.token.modPow(h, ipp.G)).multiply(p1).mod(ipp.G);
return val1.compareTo(val2) == 0;
}
@Override
public byte[] getBytes(PublicParametersI ipp)
throws IneligibleTypeException {
if (!(ipp instanceof IntegersPublicParameters)) {
throw new IneligibleTypeException();
}
return Common.CreatePaddedBigIntegerBytes(this.token,
((IntegersPublicParameters) ipp).GetTokenLengthBytes());
}
@Override
public boolean Compare(VEBTokenI t2) throws IneligibleTypeException {
if (!(t2 instanceof IntegersVEBToken)) {
throw new IneligibleTypeException();
}
return this.token.compareTo(((IntegersVEBToken) t2).token) == 0;
}
}
| Java |
package bl;
public class UnknownSecretParameterException extends Exception {
/**
*
*/
private static final long serialVersionUID = -5525670307705581428L;
}
| Java |
package bl;
public interface VEBTokensGeneratorI {
public PublicParametersI GetPublicParameters();
public VEBTokenI CreateToken(int epoch, FriendClientDataI client)
throws IneligibleTypeException;
public NIZKproofI CreateProof(VEBTokenI token, ClientDataI client)
throws IneligibleTypeException;
public VEBTokenI ParseTokenBytes(byte[] bytes);
public NIZKproofI ParseProofBytes(byte[] bytes);
}
| Java |
package bl;
import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class Common {
static SecureRandom sc = new SecureRandom();
static public byte[] concat(byte[] a, byte[] b) {
byte[] output = new byte[a.length + b.length];
System.arraycopy(a, 0, output, 0, a.length);
System.arraycopy(b, 0, output, a.length, b.length);
return output;
}
static public BigInteger randBigInteger(BigInteger max, int bitLength) {
BigInteger output;
do {
output = new BigInteger(bitLength, sc);
} while (output.compareTo(max) >= 0);
return output;
}
static public byte[] SHA256(byte[] input) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return digest.digest(input);
}
public static byte[] CreatePaddedBigIntegerBytes(BigInteger bi,
int bytesLength) {
byte[] bytes = bi.toByteArray();
if (bytes.length == bytesLength) {
return bytes;
} else if (bytes.length > bytesLength) {
throw new InvalidParameterException(
"The BigInteger value is represneted in more than bytesLength bytes. The bytesLength parameter value is "
+ bytesLength);
} else // need to pad with zero bytes
{
return Common.concat(new byte[bytesLength - bytes.length], bytes);
}
}
}
| Java |
package bl;
public interface FriendClientDataI {
// client details
public ClientDataI getClientData();
// Cryptographic information
public Object getCommonSecretKey();
public Object getIdentityPublicParameter();
public Object getIdentitySecretParameter();
}
| Java |
package bl;
public class IneligibleTypeException extends Exception {
/**
*
*/
private static final long serialVersionUID = -5525670307705581428L;
}
| Java |
package bl;
public interface NIZKproofI {
public byte[] GetBytes();
}
| Java |
package bl;
public interface TokenClassesManagerI {
public PublicParametersI CreatePublicParameters(int bitLength)
throws Exception;
public PublicParametersI CreatePublicParameters(byte[] ppBytes) throws Exception;
public VEBTokensGeneratorI CreateVEBTokenGenerator(PublicParametersI pp)
throws IneligibleTypeException;
public FriendClientDataI CreateFriendClientDataI(ClientDataI clientData,
Object... objects) throws IneligibleTypeException;
public ClientDataI CreateClientDataI(Object... objects)
throws IneligibleTypeException;
public FriendClientDataI GenerateNewClient(PublicParametersI pp)
throws IneligibleTypeException;
}
| Java |
package bl;
public interface ClientDataI {
// Cryptographic information
Object getIdentityPublicParameter();
Object getIdentitySecretParameter();
}
| Java |
package bl;
public interface VEBTokenI {
boolean Verify(NIZKproofI proof, PublicParametersI pp)
throws IneligibleTypeException;
byte[] getBytes(PublicParametersI pp) throws IneligibleTypeException;
boolean Compare(VEBTokenI t2) throws IneligibleTypeException;
}
| Java |
package bl;
public interface PublicParametersI {
/*
public Object GetGroup();
public BigInteger GetOrder();
public Object GetGenerator();
*/
/**
* @return the bit-length parameter
*/
public int GetBitLength();
/**
* @return the length of a token in bytes
*/
public int GetTokenLengthBytes();
/**
* @return the length of a NIZK proof in bytes
*/
public int GetProofLengthBytes();
/**
* @return the length of a public parameters in bytes representation (which is returned by the GetBytes() method)
*/
public int GetPublicParametersLengthBytes();
/**
* @return the public parameters as a bytes array
*/
public byte[] GetBytes();
}
| Java |
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Arrays;
import bl.IntegersTokenClassesManager;
public class main {
static SecureRandom sr = new SecureRandom();
static void testBigIntegerAndBytesCastings() throws Exception
{
// choose random BigInteger
SecureRandom sc = new SecureRandom();
int counter = 0;
for (int i = 0; i < 1000; i++)
{
BigInteger x = new BigInteger(104, sc);
byte[] bytes = Common.CreatePaddedBigIntegerBytes(x, 128);
if (bytes.length > 128 && bytes[0]!=0)
counter++;
BigInteger y = new BigInteger(bytes);
if (y.compareTo(x)!=0)
throw new Exception("X !+ Y");
}
System.out.println(counter);
}
static boolean TestIntegersTokens() throws Exception
{
int epoch = sr.nextInt(18376498);
// via the this interface you create instances of the relevant methods.
TokenClassesManagerI manager = new IntegersTokenClassesManager(); // SPECIFIES THE IMPLEMENTATION OF THE VEB TOKENS (notice that from here, you won't see the word Integers)
// contains the public parameters
PublicParametersI ppPO = manager.CreatePublicParameters(1024);
// The PO knows only the public parameters
VEBTokensGeneratorI POsideTokenGenerator = manager.CreateVEBTokenGenerator(ppPO);
/*
* The scenario:
* 0. The PO generates bytes that represent the public parameters, and the clients pull them and create a PublicParameterI object.
* 1. The friend pushes message to the client. In this test, only the bytes of the token are being sent.
* 2. The PO receives pull request from the client. The client sends the token, and a NIZK proof. (all are sent in bytes)
* 3. The test verify that both the friend and the client created the same VEB token.
* 4. The PO verify the proof against the token.
*/
// 0. The client and her friend pull the public parameters as byte[] representation and generate the public-parameters as an object.
byte[] ppBytes = ppPO.GetBytes();
// verify the length of the public parameters bytes representation
if (ppBytes.length != ppPO.GetPublicParametersLengthBytes())
throw new Exception("The byte[] representation of the public parameters is different from the data in the public information");
PublicParametersI ppClient = manager.CreatePublicParameters(ppBytes);
PublicParametersI ppFriend = manager.CreatePublicParameters(ppBytes);
// The client knows the public parameters and also his own secret key and the details of its friends.
// In this example, the client knows the "public" part of the identity (like in the simple scenario).
VEBTokensGeneratorI ClientSideTokenGenerator = manager.CreateVEBTokenGenerator(ppClient);
// Generate Secret Key (for the PRF, and possibly for messages encryption), and create identity for the client (both secret and "public" parameters)
FriendClientDataI clientDetails = manager.GenerateNewClient(ppClient);
// Create the data of the client that is sent to its friends, by sharing the key and the public identity:
ClientDataI publicClientData = manager.CreateClientDataI(clientDetails.getIdentityPublicParameter());
FriendClientDataI clientAsFriend = manager.CreateFriendClientDataI(publicClientData, clientDetails.getCommonSecretKey());
// Create the friend's token generator
VEBTokensGeneratorI FriendSideTokenGenerator = manager.CreateVEBTokenGenerator(ppFriend);
// 1. The friend pushes message to the client using the
VEBTokenI friendToClientToken = FriendSideTokenGenerator.CreateToken(epoch, clientAsFriend);
byte[] friendToClientTokenBytes = friendToClientToken.getBytes(ppFriend);
// Assume that the PO received the bytes of the token with a message
// 2. The client sends pull request to pull the message with a proof
// first create the token
VEBTokenI clientPullToken = ClientSideTokenGenerator.CreateToken(epoch, clientDetails);
byte[] clientPullTokenBytes = clientPullToken.getBytes(ppClient);
// then create the proof
NIZKproofI clientProof = ClientSideTokenGenerator.CreateProof(clientPullToken, clientDetails.getClientData());
byte[] clientProofBytes = clientProof.GetBytes();
// 3. Verify that the tokens that were sent by both the client and her friend are identical
// bytes comparison:
if (!Arrays.equals(friendToClientTokenBytes, clientPullTokenBytes))
throw new Exception("Sender and recipient tokens are not identical in byte[] representation");
// verify the length of the token bytes representation
if (friendToClientTokenBytes.length != ppFriend.GetTokenLengthBytes())
throw new Exception("The byte[] representation of the token is different from the data in the public information");
// verify the length of the proof bytes representation
if (clientProofBytes.length != ppClient.GetProofLengthBytes())
throw new Exception("The byte[] representation of the proof is different from the data in the public information");
// tokens reproduced by the PO comparison
VEBTokenI senderToken = POsideTokenGenerator.ParseTokenBytes(friendToClientTokenBytes);
VEBTokenI recipientToken = POsideTokenGenerator.ParseTokenBytes(clientPullTokenBytes);
if (!senderToken.Compare(recipientToken))
throw new Exception("Tokens used for push and pull are not identical");
// 4. The PO verifies the proof against the token
NIZKproofI proofReceivedByPO = POsideTokenGenerator.ParseProofBytes(clientProofBytes);
if (!recipientToken.Verify(proofReceivedByPO, ppClient))
throw new Exception("Verification of token faild");
// ADD here comparison between two proofs, similarly to the comaprison between two VEBToken.
return true;
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int testsCounter = 5000;
int successesCounter = 0;
for (int i = 0; i < testsCounter; i++)
{
if (TestIntegersTokens())
{
successesCounter++;
}
}
if (successesCounter == testsCounter)
{
System.out.println("Test succeeded");
}
}
}
| Java |
package Model;
import java.util.HashMap;
import java.util.Map;
public class Messages
{
private final byte[] NOT_EXISTS_PULL = null;
private Map<Integer, byte[]> m_Data;
private int m_NextIndex;
public Messages()
{
m_Data = new HashMap<Integer, byte[]>();
m_NextIndex = 0;
}
// add data - from message
public synchronized int append(byte[] msg)
{
int i = m_NextIndex++;
m_Data.put(i, msg);
return i;
}
// add data - from DB
public void append(byte[] message, int index)
{
m_Data.put(index, message);
if (m_NextIndex <= index)
{
m_NextIndex = index + 1;
}
}
public byte[] pull(int index)
{
if (m_Data.containsKey(index))
{
return m_Data.get(index);
}
return NOT_EXISTS_PULL;
}
}
| Java |
package Model;
import java.nio.ByteBuffer;
import java.util.Map;
public class Data
{
private final byte[] NO_DATA_PULL = null;
// eager initialization is both thread safe and will also load the data from db
private static volatile Data instance = new Data();
private Map<ByteBuffer, Messages> m_Data;
private DB m_Db;
private Data()
{
// load previous state from database
m_Db = new DB();
m_Data = m_Db.load();
}
public static Data getInstance()
{
return instance;
}
public byte[] pull(byte[] token, int index)
{
Messages msgs = null;
if(index > -1)
{
msgs = m_Data.get(ByteBuffer.wrap(token));
}
if (msgs == null)
{
return NO_DATA_PULL;
}
return msgs.pull(index);
}
public void push(byte[] token, byte[] msg)
{
ByteBuffer tokenWrapper = ByteBuffer.wrap(token);
Messages msgs = m_Data.get(tokenWrapper);
if (msgs == null)
{
msgs = new Messages();
m_Data.put(tokenWrapper, msgs);
}
int index = msgs.append(msg);
m_Db.append(token, msg, index);
}
}
| Java |
package Model;
public class Message
{
private String m_Data;
private int m_Index;
public Message(String data)
{
m_Data = data;
}
public Message(String data, int index)
{
m_Data = data;
m_Index = index;
}
public String getMessage()
{
return m_Data;
}
public void setIndex(int index)
{
m_Index = index;
}
public int getIndex()
{
return m_Index;
}
}
| Java |
package Model;
import java.util.Arrays;
/*
* According to the message flags create a sub-class of BaseMessage
* and handle its push/pull operations
* */
public class RequestHandler
{
// relevant sub-class according to flags
private BaseMessage m_Message;
public RequestHandler(byte[] b)
{
// extract first byte - that byte is for the flags
byte[] rest = Arrays.copyOfRange(b, 1, b.length);
switch (b[0])
{
// retrieve the PO public params
case 0:
m_Message = new PPMessage();
break;
// push and pull message (including dummies)
default:
m_Message = new PushAndPullMessage(rest);
break;
}
}
public byte[] pull()
{
return m_Message.pull();
}
public void push()
{
m_Message.push();
}
}
| Java |
package Model;
public class PPMessage extends BaseMessage
{
@Override
public byte[] pull()
{
// Send the PO's public params
TokenManager token = TokenManager.getInstance();
return build(eCode.Success, token.getPublicParams());
}
}
| Java |
package Model;
public class BaseMessage
{
private byte[] NO_DATA = {1};
protected enum eCode
{
Success((byte)1), Error((byte)1);
byte m_Value;
private eCode(byte i)
{
m_Value = i;
}
public byte getCode()
{
return m_Value;
}
}
protected static byte[] build(eCode code, Object... arrays)
{
int size = 0;
for (int i = 0; i < arrays.length; i++)
{
size += ((byte[])arrays[i]).length;
}
byte[] array = new byte[size];
int counter = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, array, counter, ((byte[])arrays[i]).length);
counter += ((byte[])arrays[i]).length;
}
return array;
}
// default pull - do nothing
public byte[] pull()
{
return build(eCode.Success, NO_DATA);
}
// default push - do nothing
public void push(){}
}
| Java |
package Model;
import bl.*;
public class TokenManager
{
TokenClassesManagerI m_manager;
PublicParametersI m_ppPO;
VEBTokensGeneratorI m_POsideTokenGenerator;
byte[] m_ppBytes;
private static TokenManager m_Instance;
private TokenManager()
{
// via the this interface you create instances of the relevant methods.
m_manager = new IntegersTokenClassesManager();
// contains the public parameters
try {
m_ppPO = m_manager.CreatePublicParameters(1024);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// The PO knows only the public parameters
try {
m_POsideTokenGenerator = m_manager.CreateVEBTokenGenerator(m_ppPO);
} catch (IneligibleTypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 0. The client and her friend pull the public parameters as byte[] representation and generate the public-parameters as an object.
m_ppBytes = m_ppPO.GetBytes();
}
public static TokenManager getInstance()
{
if (m_Instance == null)
{
m_Instance = new TokenManager();
}
return m_Instance;
}
public byte[] getPublicParams()
{
return m_ppBytes;
}
public int getTokenLength()
{
return m_ppPO.GetTokenLengthBytes();
}
public int getMessageLength()
{
return 1024;
}
public int getProofLength()
{
return m_ppPO.GetProofLengthBytes();
}
public boolean isProofValid(byte[] clientProofBytes, byte[] clientPullTokenBytes) throws IneligibleTypeException
{
NIZKproofI proofReceivedByPO = m_POsideTokenGenerator.ParseProofBytes(clientProofBytes);
VEBTokenI recipientToken = m_POsideTokenGenerator.ParseTokenBytes(clientPullTokenBytes);
if (recipientToken.Verify(proofReceivedByPO, m_ppPO))
{
return true;
}
return false;
}
}
| Java |
package Model;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class PushAndPullMessage extends BaseMessage
{
private final int SIZE_OF_INT = 4;
private byte[] m_PullToken;
private byte[] m_Proof;
private int m_Index;
private byte[] m_PushToken;
private byte[] m_Message;
TokenManager manager;
public PushAndPullMessage(byte[] request)
{
manager = TokenManager.getInstance();
int startFrom = 0;
// extract all from the message
m_PullToken = Arrays.copyOfRange(request, startFrom, manager.getTokenLength());
startFrom += manager.getTokenLength();
byte[] tempForInt = Arrays.copyOfRange(request, startFrom, startFrom + SIZE_OF_INT);
m_Index = ByteBuffer.wrap(tempForInt).getInt();
startFrom += SIZE_OF_INT;
m_Proof = Arrays.copyOfRange(request, startFrom, startFrom + manager.getProofLength());
startFrom += manager.getProofLength();
m_PushToken = Arrays.copyOfRange(request, startFrom, startFrom + manager.getTokenLength());
startFrom += manager.getTokenLength();
m_Message = Arrays.copyOfRange(request, startFrom, request.length);
}
@Override
public byte[] pull()
{
Data data = Data.getInstance();
try
{
// validate proof and pull the data
if (manager.isProofValid(m_Proof, m_PullToken))
{
return build(eCode.Success, data.pull(m_PullToken, m_Index));
}
}
catch(Exception e)
{}
return build(eCode.Error);
}
@Override
public void push()
{
// push the data
Data data = Data.getInstance();
data.push(m_PushToken,m_Message);
}
}
| Java |
package Model;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class DB
{
private final String DB_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
private final String DB_CONNECTION = "jdbc:derby:AnonPoP;create=true";
// TODO: Move queries to file?
private final String CREATE_DB_QUERY = "CREATE TABLE Messages\n"+
"(Message_Token varchar(300) NOT NULL, Message varchar(300) not null, Index int not null)";
private final String SELECT_ALL_MESSAGES = "select * from Messages order by Message_Token,index";
private final String INSERT_NEW_MESSAGE = "insert into Messages values ('%s','%s',%d)";
private final String CLEAR_DATABASE = "truncate table Messages";
public DB()
{
createDb();
}
private Connection getConnection() throws ClassNotFoundException, SQLException
{
// TODO: I think the following line can be at the constructor
Class.forName(DB_DRIVER);
return DriverManager.getConnection(DB_CONNECTION);
}
private void executeQuery(String query)
{
Connection connection = null;
try
{
connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.executeUpdate();
}
catch( Exception e )
{
}
finally
{
try
{
connection.close();
}
catch (SQLException e) {}
}
}
private HashMap<ByteBuffer, Messages> resultSetQuery(String query)
{
Connection connection = null;
try
{
connection = getConnection();
PreparedStatement pstmt = connection.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
HashMap<ByteBuffer, Messages> map = new HashMap<ByteBuffer, Messages>();
if (rs != null && rs.next())
{
String lastToken = rs.getString("Message_Token");
Messages msgs = new Messages();
do
{
String token = rs.getString("Message_Token");
String message = rs.getString("Message");
int index = rs.getInt("Index");
if (!lastToken.equals(token))
{
map.put(ByteBuffer.wrap(lastToken.getBytes()), msgs);
lastToken = token;
msgs = new Messages();
}
msgs.append(message.getBytes(), index);
}
while (rs.next());
map.put(ByteBuffer.wrap(lastToken.getBytes()), msgs);
}
return map;
}
catch( Exception e )
{
}
finally
{
try
{
connection.close();
}
catch (SQLException e) {}
}
return null;
}
public void createDb()
{
executeQuery(CREATE_DB_QUERY);
}
public Map<ByteBuffer, Messages> load()
{
return resultSetQuery(SELECT_ALL_MESSAGES);
}
public void remove(String token, int index)
{
}
public void append(byte[] token, byte[] msg, int index)
{
executeQuery(String.format(INSERT_NEW_MESSAGE, token,msg,index));
}
public void clear()
{
executeQuery(CLEAR_DATABASE);
}
}
| Java |
package Controller;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import Model.RequestHandler;
/*
* Analyze the message -
* pull data if not dummy (reperesented by -1 index)
* push data if not dummy
* */
public class Request extends Thread
{
// when there is no data to pull, send this
private byte[] DUMMY_PULL = {1};
private Socket m_Socket;
public Request(Socket connSocket)
{
m_Socket = connSocket;
}
@Override
public void run()
{
DataInputStream in = null;
DataOutputStream out = null;
try
{
// client's input/output
in = new DataInputStream(m_Socket.getInputStream());
out = new DataOutputStream(m_Socket.getOutputStream());
// get client's request
byte[] message = null;
int length = in.readInt();
if(length>0)
{
message = new byte[length];
in.readFully(message, 0, message.length);
}
// process request
RequestHandler handler = new RequestHandler(message);
// acquire pull data
byte[] result = handler.pull();
if (result == null || result.length <= 1)
{
result = DUMMY_PULL;
}
// send data back
out.writeInt(result.length);
out.write(result);
// store new data
handler.push();
}
catch(Exception e)
{
}
finally
{
// close connections
try
{
out.close();
}
catch(Exception e)
{
}
try
{
in.close();
}
catch(Exception e)
{
}
try
{
m_Socket.close();
}
catch(Exception e)
{
}
}
}
}
| Java |
package Controller;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import Model.Data;
import Model.TokenManager;
/* Recieve all the messages and handle them */
public class Server
{
// which port the server listens to
private final int INCOMING_PORT = 1234;
public void start()
{
// init data
Data.getInstance();
TokenManager.getInstance();
ServerSocket serverSocket = null;
Socket connSocket = null;
try
{
// start listening
serverSocket = new ServerSocket(INCOMING_PORT);
while (true)
{
// accept connections
connSocket = serverSocket.accept();
// create separate thread for each request
Request request = new Request(connSocket);
request.start();
}
}
catch(Exception e)
{
}
finally
{
try
{
connSocket.close();
}
catch (IOException e)
{
}
try
{
serverSocket.close();
}
catch (IOException e)
{
}
}
}
}
| Java |
package Controller;
public class Start
{
public static void main(String[] args)
{
System.out.println("Server is up");
// start the server
Server server = new Server();
server.start();
}
}
| Java |
package com.clwillingham.socket.io;
import org.json.JSONObject;
public interface MessageCallback {
public void on(String event, JSONObject... data);
public void onMessage(String message);
public void onMessage(JSONObject json);
public void onConnect();
public void onDisconnect();
}
| Java |
package com.clwillingham.socket.io;
public class Message extends IOMessage{
public Message(String message){
super(IOMessage.MESSAGE, -1, "", message);
}
}
| Java |
// MODIFIED TO REDUCE LOGGING
package com.clwillingham.socket.io;
public class IOMessage {
public static final int DISCONNECT = 0;
public static final int CONNECT = 1;
public static final int HEARTBEAT = 2;
public static final int MESSAGE = 3;
public static final int JSONMSG = 4;
public static final int EVENT = 5;
public static final int ACK = 6;
public static final int ERROR = 7;
private int type;
private int id = -1;
private String endpoint = "";
private String messageData;
public IOMessage(int type, int id, String endpoint, String data){
this.type = type;
this.id = id;
this.endpoint = endpoint;
this.messageData = data;
}
public IOMessage(int type, String endpoint, String data) {
this.type = type;
this.endpoint = endpoint;
this.messageData = data;
}
public IOMessage(){
}
public static IOMessage parseMsg(String message){
String[] content = message.split(":", 4);
IOMessage msg = new IOMessage();
msg.setType(Integer.parseInt(content[0]));
if(message.endsWith("::")){
msg.setId(-1);
msg.setMessageData("");
msg.setEndpoint("");
return msg;
}
if(!content[1].equals("")){
msg.setId(Integer.parseInt(content[1]));
}
if(!content[2].equals("")){
msg.setEndpoint(content[2]);
}
if(content.length > 3 && !content[3].equals("")){
msg.setMessageData(content[3]);
}
return msg;
}
public String toString(){
if(id == -1 && endpoint.equals("") && messageData.equals("")){
return type+"::";
}
else if(id == -1 && endpoint.equals("")){
return type+":::"+messageData;
}
else if(id > -1){
return type+":"+id+":"+endpoint+":"+messageData;
}
else{
return type+"::"+endpoint+":"+messageData;
}
}
public void setType(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getEndpoint() {
return endpoint;
}
public void setMessageData(String messageData) {
this.messageData = messageData;
}
public String getMessageData() {
return messageData;
}
}
| Java |
// MODIFIED TO REDUCE LOGGING
package com.clwillingham.socket.io;
import java.io.IOException;
import java.net.URI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.tootallnate.websocket.WebSocketClient;
public class IOWebSocket extends WebSocketClient{
private MessageCallback callback;
private IOSocket ioSocket;
private static int currentID = 0;
private String namespace;
public IOWebSocket(URI arg0, IOSocket ioSocket, MessageCallback callback) {
super(arg0);
this.callback = callback;
this.ioSocket = ioSocket;
}
@Override
public void onIOError(IOException arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMessage(String arg0) {
IOMessage message = IOMessage.parseMsg(arg0);
switch (message.getType()) {
case IOMessage.HEARTBEAT:
try {
send("2::");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case IOMessage.MESSAGE:
callback.onMessage(message.getMessageData());
break;
case IOMessage.JSONMSG:
try {
callback.onMessage(new JSONObject(message.getMessageData()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case IOMessage.EVENT:
try {
JSONObject event = new JSONObject(message.getMessageData());
JSONArray args = event.getJSONArray("args");
JSONObject[] argsArray = new JSONObject[args.length()];
for (int i = 0; i < args.length(); i++) {
argsArray[i] = args.getJSONObject(i);
}
String eventName = event.getString("name");
callback.on(eventName, argsArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case IOMessage.CONNECT:
ioSocket.onConnect();
break;
case IOMessage.ACK:
case IOMessage.ERROR:
case IOMessage.DISCONNECT:
//TODO
break;
}
}
@Override
public void onOpen() {
try {
if (namespace != "")
init(namespace);
} catch (IOException e) {
e.printStackTrace();
}
ioSocket.onOpen();
}
@Override
public void onClose() {
ioSocket.onClose();
ioSocket.onDisconnect();
}
public void init(String path) throws IOException{
send("1::"+path);
}
public void init(String path, String query) throws IOException{
this.send("1::"+path+"?"+query);
}
public void sendMessage(IOMessage message) throws IOException{
send(message.toString());
}
public void sendMessage(String message) throws IOException{
send(new Message(message).toString());
}
public static int genID(){
currentID++;
return currentID;
}
public void setNamespace(String ns) {
namespace = ns;
}
public String getNamespace() {
return namespace;
}
}
| Java |
// MODIFIED TO USE END POINTS IN OUTGOING MESSAGES
// MODIFIED TO REDUCE LOGGING
package com.clwillingham.socket.io;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class IOSocket {
private IOWebSocket webSocket;
private URL connection;
private String sessionID;
private int heartTimeOut;
private int closingTimeout;
private String[] protocals;
private String webSocketAddress;
private MessageCallback callback;
private boolean connecting;
private boolean connected;
private boolean open;
public IOSocket(String address, MessageCallback callback){
webSocketAddress = address;
this.callback = callback;
}
public void connect() throws IOException {
// check for socket.io namespace
String namespace = "";
int i = webSocketAddress.lastIndexOf("/");
if (webSocketAddress.charAt(i-1) != '/') {
namespace = webSocketAddress.substring(i);
webSocketAddress = webSocketAddress.substring(0, i);
}
// perform handshake
String url = webSocketAddress.replace("ws://", "http://");
URL connection = new URL(url+"/socket.io/1/"); //handshake url
InputStream stream = connection.openStream();
Scanner in = new Scanner(stream);
String response = in.nextLine(); //pull the response
// process handshake response
// example: 4d4f185e96a7b:15:10:websocket,xhr-polling
if(response.contains(":")) {
String[] data = response.split(":");
setSessionID(data[0]);
setHeartTimeOut(Integer.parseInt(data[1]));
setClosingTimeout(Integer.parseInt(data[2]));
setProtocals(data[3].split(","));
}
connecting = true;
webSocket = new IOWebSocket(URI.create(webSocketAddress+"/socket.io/1/websocket/"+sessionID), this, callback);
webSocket.setNamespace(namespace);
webSocket.connect();
}
public void emit(String event, JSONObject... message) throws IOException {
try {
JSONObject data = new JSONObject();
JSONArray args = new JSONArray();
for (JSONObject arg : message) {
args.put(arg);
}
data.put("name", event);
data.put("args", args);
IOMessage packet = new IOMessage(IOMessage.EVENT, webSocket.getNamespace(), data.toString());
webSocket.sendMessage(packet);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send(String message) throws IOException {
IOMessage packet = new IOMessage(IOMessage.MESSAGE, webSocket.getNamespace(), message);
webSocket.sendMessage(packet);
}
public synchronized void disconnect() {
if (connected) {
try {
if (open) {
webSocket.sendMessage(new IOMessage(IOMessage.DISCONNECT, webSocket.getNamespace(), ""));
}
} catch (IOException e) {
e.printStackTrace();
}
onDisconnect();
}
}
synchronized void onOpen() {
open = true;
}
synchronized void onClose() {
open = false;
}
synchronized void onConnect() {
if (!connected) {
connected = true;
connecting = false;
callback.onConnect();
}
}
synchronized void onDisconnect() {
boolean wasConnected = connected;
connected = false;
connecting = false;
if (open) {
try {
webSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (wasConnected) {
callback.onDisconnect();
//TODO: reconnect
}
}
public void setConnection(URL connection) {
this.connection = connection;
}
public URL getConnection() {
return connection;
}
public void setHeartTimeOut(int heartTimeOut) {
this.heartTimeOut = heartTimeOut;
}
public int getHeartTimeOut() {
return heartTimeOut;
}
public void setClosingTimeout(int closingTimeout) {
this.closingTimeout = closingTimeout;
}
public int getClosingTimeout() {
return closingTimeout;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public String getSessionID() {
return sessionID;
}
public void setProtocals(String[] protocals) {
this.protocals = protocals;
}
public String[] getProtocals() {
return protocals;
}
}
| Java |
package wasd;
import grits.wasd.R;
import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.clwillingham.socket.io.IOSocket;
import com.clwillingham.socket.io.MessageCallback;
/**
* Main activity for the Grits WASD controller.
*/
public class WasdActivity extends Activity {
/**
* Tag used for logging.
*/
public static final String TAG = WasdActivity.class.getName();
/**
* Local IP address for testing with the dev_appserver.
*/
private static final String LOCAL_IP = "192.168.21.28";
/**
* The production origin.
*/
private static final String ORIGIN_GRITSGAME_APPSPOT_COM = "http://gritsgame.appspot.com";
/**
* The dev_appserver origin.
*/
private static final String ORIGIN_LOCAL = "http://" + LOCAL_IP + ":8080";
// private static final String HTTPS_WWW_GOOGLEAPIS_COM_PLUS_V1_PEOPLE_ME = "https://www.googleapis.com/plus/v1/people/me";
/**
* The user info API endpoint, which allows us to retrieve the same user id as is returned by App
* Engine's OAuth2 API for the {@value SCOPE_USERINFO_EMAIL} scope.
*/
private static final String HTTPS_WWW_GOOGLEAPIS_COM_OAUTH2_V1_USERINFO = "https://www.googleapis.com/oauth2/v1/userinfo";
/**
* Preference key where the current account is stored.
*/
private static final String PREF_ACCOUNT_NAME = "ACCOUNT_NAME";
/**
* Preference key prefix where the OAuth2 {@value SCOPE_USERINFO_EMAIL} scope access token is
* stored.
*/
private static final String PREF_OAUTH2_EMAIL_ACCESS_TOKEN_ = "OAUTH2_EMAIL_ACCESS_TOKEN_";
/**
* Preference key prefix where the OAuth2 {@value SCOPE_USERINFO_PROFILE} scope access token is
* stored.
*/
private static final String PREF_OAUTH2_PROFILE_ACCESS_TOKEN_ = "OAUTH2_PROFILE_ACCESS_TOKEN_";
/**
* Preference key where the preferred game origin is stored.
*/
protected static final String PREF_GAME_ORIGIN = "GAME_ORIGIN";
/**
* Determines accelerometer sensitivity, i.e. how far the device must be tilted from level before
* a directional change is detected.
*/
public static final float SENSOR_THRESHOLD = 2f;
/**
* Limits flip flopping of the accelerometer directional state, by requiring a lower sensor
* reading to turn off a particular directional input than is required to enable the same
* directional input.
*/
private static final float SENSOR_STICKINESS = 0.3f;
// private static final String SCOPE_PLUS_ME = "oauth2:https://www.googleapis.com/auth/plus.me";
/**
* OAuth2 scope which provides access to the user id and email address.
*/
private static final String SCOPE_USERINFO_EMAIL = "oauth2:https://www.googleapis.com/auth/userinfo.email";
/**
* OAuth2 scope which provides access to the user's basic profile information, although not the
* email address.
*/
private static final String SCOPE_USERINFO_PROFILE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";
private SensorManager sensorManager;
private Display display;
private SensorListener sensorListener;
private View upView;
private View leftView;
private View rightView;
private View downView;
public boolean left;
public boolean right;
public boolean up;
public boolean down;
private Button reconnectButton;
private Button accountButton;
private SharedPreferences prefs;
private AccountManager accountManager;
private GameAsyncTask gameAsyncTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountManager = AccountManager.get(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
prefs = getSharedPreferences("grits", MODE_PRIVATE);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
sensorListener = new SensorListener();
setContentView(R.layout.wasd);
upView = (View) findViewById(R.id.button_up);
leftView = (View) findViewById(R.id.button_left);
rightView = (View) findViewById(R.id.button_right);
downView = (View) findViewById(R.id.button_down);
reconnectButton = (Button) findViewById(R.id.reconnect_button);
accountButton = (Button) findViewById(R.id.account_button);
reconnectButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
chooseEndpoint();
}
});
reconnectButton.setText(prefs.getString(PREF_GAME_ORIGIN, ORIGIN_GRITSGAME_APPSPOT_COM));
accountButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
chooseAccount();
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "************* onStart()");
setAccountFromPref();
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "************* onStop()");
if (gameAsyncTask != null) {
gameAsyncTask.disconnect();
}
}
@Override
protected void onResume() {
super.onResume();
sensorListener.start();
}
@Override
protected void onPause() {
super.onPause();
sensorListener.stop();
}
/**
* Disconnect an existing websocket connection and attempt to reconnect.
*/
protected void reconnect() {
Log.i(TAG, "********************* reconnect()");
if (gameAsyncTask != null) {
gameAsyncTask.disconnect();
}
gameAsyncTask = new GameAsyncTask();
gameAsyncTask.execute();
}
/**
* Allow the user to select a websocket endpoint to connect to.
*/
private void chooseEndpoint() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an endpoint");
final String[] origins = new String[] {ORIGIN_GRITSGAME_APPSPOT_COM, ORIGIN_LOCAL};
builder.setItems(origins, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putString(PREF_GAME_ORIGIN, origins[which]).apply();
reconnectButton.setText(origins[which]);
reconnect();
}
});
AlertDialog dialog = builder.create();
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
reconnect();
}
});
dialog.show();
}
/**
* Set the current account based on the stored shared preference.
*/
private void setAccountFromPref() {
Account[] accounts = accountManager.getAccountsByType("com.google");
String accountName = prefs.getString(PREF_ACCOUNT_NAME, null);
for (Account account : accounts) {
if (account.name.equals(accountName)) {
setAccount(account);
return;
}
}
// default to first account
setAccount(accounts[0]);
}
/**
* Prompt the user for which account they'd like connect with.
*/
protected void chooseAccount() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select a Google account");
final Account[] accounts = accountManager.getAccountsByType("com.google");
final int size = accounts.length;
String[] names = new String[size];
for (int i = 0; i < size; i++) {
names[i] = accounts[i].name;
}
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putString(PREF_ACCOUNT_NAME, accounts[which].name).apply();
setAccountFromPref();
}
});
AlertDialog dialog = builder.create();
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// if pref is not set, a new dialog will appear
setAccountFromPref();
}
});
dialog.show();
}
/**
* Set the specified account to be the current one, request new OAuth2 access tokens, and
* reconnect to the websocket endpoint.
*
* @param account the new account to use
*/
protected void setAccount(final Account account) {
accountButton.setText(account.name);
requestAccessToken(account, PREF_OAUTH2_EMAIL_ACCESS_TOKEN_, SCOPE_USERINFO_EMAIL,
new Runnable() {
@Override
public void run() {
requestAccessToken(account, PREF_OAUTH2_PROFILE_ACCESS_TOKEN_, SCOPE_USERINFO_PROFILE,
new Runnable() {
@Override
public void run() {
reconnect();
}
});
}
});
}
/**
* Asynchronously request a new OAuth2 access token.
*
* @param account the account for which to request an access token
* @param prefPrefix the shared prefs prefix under which the access tokens are kept
* @param scope the OAuth2 scope for which to request a token
* @param cmd the runnable comamnd to execute once the token has been retrieved
*/
private void requestAccessToken(final Account account, final String prefPrefix,
final String scope, final Runnable cmd) {
invalidateAccessTokens(account, prefPrefix);
// TODO Update server code to avoid http://en.wikipedia.org/wiki/Confused_deputy_problem
accountManager.getAuthToken(account, scope, null, this, new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
try {
String accessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
toast("Got OAuth2 access token for " + account.name + ":\n" + accessToken);
prefs.edit().putString(prefPrefix + account.name, accessToken).apply();
cmd.run();
} catch (OperationCanceledException e) {
toast("The user has denied you access to the " + scope);
} catch (Exception e) {
toast(e.toString());
Log.w("Exception: ", e);
}
}
}, null);
}
/**
* In order to hedge against potentially expired OAuth2 access token, we simply invalidate all the
* token we've received for the account.
*
* @param account the account for which to expire access token
* @param prefPrefix the shared prefs prefix under which the access tokens are kept
*/
private void invalidateAccessTokens(Account account, String prefPrefix) {
String accessToken = prefs.getString(prefPrefix + account.name, null);
if (accessToken != null) {
accountManager.invalidateAuthToken(account.type, accessToken);
prefs.edit().remove(prefPrefix + account.name).apply();
}
}
/**
* An {@link AsyncTask} which is used to request the necessary OAuth2 access tokens, invoke the
* {@code findGame} grits service, and finally connect to and maintain a websocket connection to
* the games server. We use an {@link AsyncTask} to avoid running slow network calls on the main
* UI thread.
*/
private final class GameAsyncTask extends AsyncTask<Void, String, Void> {
private IOSocket socket;
private boolean okayToRun = true;
protected Void doInBackground(Void... params) {
String profileAccessToken = prefs.getString(
PREF_OAUTH2_PROFILE_ACCESS_TOKEN_ + accountButton.getText(), null);
String emailAccessToken = prefs.getString(
PREF_OAUTH2_EMAIL_ACCESS_TOKEN_ + accountButton.getText(), null);
PlayerGame pg = findGame(profileAccessToken, emailAccessToken);
if (pg == null) {
// toast message already sent to user, so just return
return null;
}
connect(pg);
return null;
}
/**
* Convenience method for publishing progress updates which involve exceptions
*
* @param msg the message to display
* @param e the exception which was raised
*/
private void publishProgress(String msg, Exception e) {
Log.e(TAG, msg, e);
publishProgress(msg + "\n" + e);
}
@Override
protected void onProgressUpdate(String... messages) {
for (String msg : messages) {
toast(msg);
}
}
@Override
protected void onCancelled(Void result) {
if (socket != null) {
socket.disconnect();
}
}
/**
* Acquire the necessary OAuth2 tokens and invoke the grits {@code findGame} service.
*
* @param profileAccessToken OAuth2 access token for the {@value SCOPE_USERINFO_PROFILE} scope
* @param emailAccessToken OAuth2 access token for the {@value SCOPE_USERINFO_EMAIL} scope
* @return
*/
private PlayerGame findGame(String profileAccessToken, String emailAccessToken) {
JSONObject userInfo = get(HTTPS_WWW_GOOGLEAPIS_COM_OAUTH2_V1_USERINFO, profileAccessToken);
if (userInfo == null) {
// toast message already sent to user, so just return
return null;
}
String userID;
try {
userID = userInfo.getString("id");
} catch (JSONException e) {
publishProgress("failed to extract id from userInfo:" + userInfo, e);
return null;
}
String endpoint = prefs.getString(PREF_GAME_ORIGIN, ORIGIN_GRITSGAME_APPSPOT_COM);
// Note: the userID is only used in the dev_appserver
String findGameUrl = endpoint + "/grits/findGame?userID=" + userID;
JSONObject json = post(findGameUrl, emailAccessToken);
if (json == null) {
// toast message already sent to user, so just return
return null;
}
PlayerGame pg = extractPlayerGame(json);
return pg;
}
/**
* Extract player game data from a response to the Grits {@code findGame} service.
*
* @param json the {@link JSONObject} returned from thr {@code findGame} service.
* @return the {@link PlayerGame} data or {@ocde null}
*/
private PlayerGame extractPlayerGame(JSONObject json) {
try {
if (!json.has("game")) {
publishProgress("result does not contain game: " + json.toString(4));
return null;
}
JSONObject game = json.getJSONObject("game");
String player_game_key = json.getString("player_game_key");
String userID = json.getString("userID");
String gameURL = game.getString("gameURL");
JSONObject game_state = game.getJSONObject("game_state");
JSONObject players = game_state.getJSONObject("players");
publishProgress("LOOKING UP userID " + userID);
String player_name = players.getString(userID);
if ("TBD".equals(player_name)) {
publishProgress("Please first login at gritsgame.appspot.com with the same id.");
return null;
}
Log.d(TAG, "player_name = " + player_name);
gameURL = gameURL.replace("127.0.0.1", LOCAL_IP);
gameURL = gameURL + player_name;
Log.d(TAG, "gameUrl = " + gameURL);
return new PlayerGame(gameURL, player_game_key, player_name);
} catch (JSONException e) {
publishProgress("failed to extract player game from json: " + json, e);
return null;
}
}
/**
* Send HTTP GET request and return the response as a {@link JSONObject}.
*
* @param url the resource to connect to
* @param accessToken the OAuth2 bearer access token
* @return the {@link JSONObject} response
*/
private JSONObject get(String url, String accessToken) {
Log.d(TAG, "Connecting to " + url);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Log.d(TAG, "Authorization: Bearer " + accessToken);
httpGet.addHeader("Authorization", "Bearer " + accessToken);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String json;
try {
json = httpClient.execute(httpGet, responseHandler);
} catch (HttpResponseException e) {
publishProgress("failed to reach " + url + " due HTTP status " + e.getStatusCode() + ": "
+ e.getMessage());
return null;
} catch (Exception e) {
publishProgress("failed to reach " + url, e);
return null;
}
Log.d(TAG, url + " -> " + json);
try {
JSONObject result = (JSONObject) new JSONTokener(json).nextValue();
return result;
} catch (JSONException e) {
publishProgress("failed to digest result as JSON " + json, e);
return null;
}
}
/**
* Send HTTP POST request and return the response as a {@link JSONObject}.
*
* @param url the resource to connect to
* @param accessToken the OAuth2 bearer access token
* @return the {@link JSONObject} response
*/
private JSONObject post(String url, String accessToken) {
Log.d(TAG, "Connecting to " + url);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Log.d(TAG, "Authorization: Bearer " + accessToken);
httpPost.addHeader("Authorization", "Bearer " + accessToken);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String json;
try {
json = httpClient.execute(httpPost, responseHandler);
} catch (HttpHostConnectException e) {
publishProgress("failed to reach " + e.getHost() + ": " + e.getMessage());
return null;
} catch (HttpResponseException e) {
publishProgress("failed to reach " + url + " due HTTP status " + e.getStatusCode() + ": "
+ e.getMessage());
return null;
} catch (Exception e) {
Log.e(TAG, "failed to reach " + url, e);
publishProgress("failed to reach " + url, e);
return null;
}
Log.d(TAG, url + " -> " + json);
try {
JSONObject result = (JSONObject) new JSONTokener(json).nextValue();
return result;
} catch (JSONException e) {
publishProgress("failed to digest result as JSON " + json, e);
return null;
}
}
public void disconnect() {
cancel(true);
okayToRun = false;
}
private void connect(final PlayerGame pg) {
socket = new IOSocket(pg.gameURL, new MessageCallback() {
@Override
public void on(String event, JSONObject... data) {
// JSON message; not used
Log.i(TAG, "on(" + event + ", JSONObject: " + data + ")");
}
@Override
public void onMessage(String message) {
if (!message.startsWith("ack")) {
Log.i(TAG, "\nonMessage(String " + message + "):");
}
String m = (up ? "Y" : "N") + (left ? "Y" : "N") + (down ? "Y" : "N")
+ (right ? "Y" : "N");
send(m);
}
private void send(String m) {
if (!okayToRun) {
socket.disconnect();
return;
}
try {
socket.send(m);
} catch (Exception e) {
publishProgress("failed to send", e);
// prevent continuous failures
socket.disconnect();
}
}
@Override
public void onMessage(JSONObject message) {
// JSON message; not used
Log.i(TAG, "onMessage(JSONObject: " + message + ")");
}
@Override
public void onConnect() {
publishProgress("onConnect(): Connection established - Yay!");
send("init{ \"player_game_key\": \"" + pg.player_game_key + "\", \"player_name\": \""
+ pg.player_name + "\"}");
}
@Override
public void onDisconnect() {
publishProgress("onDisconnect(): Boo!");
}
});
try {
socket.connect();
} catch (IOException e) {
publishProgress("failed to connect", e);
}
}
}
/**
* Simple bag of properties for passing around.
*/
private static class PlayerGame {
private final String gameURL;
private final String player_game_key;
private final String player_name;
public PlayerGame(String gameURL, String player_game_key, String player_name) {
this.gameURL = gameURL;
this.player_game_key = player_game_key;
this.player_name = player_name;
}
}
/**
* Convenience method for displaying brief messages to the user.
*
* @param msg the message to display
*/
private void toast(String msg) {
Toast.makeText(WasdActivity.this, msg, Toast.LENGTH_SHORT).show();
Log.d(TAG, msg);
}
private void updateDirections(float sensorX, float sensorY) {
if (sensorX > SENSOR_THRESHOLD) {
left = true;
} else if (sensorX < SENSOR_THRESHOLD - SENSOR_STICKINESS) {
left = false;
}
if (sensorX < -SENSOR_THRESHOLD) {
right = true;
} else if (sensorX > -SENSOR_THRESHOLD + SENSOR_STICKINESS) {
right = false;
}
if (sensorY > SENSOR_THRESHOLD) {
down = true;
} else if (sensorY < SENSOR_THRESHOLD - SENSOR_STICKINESS) {
down = false;
}
if (sensorY < -SENSOR_THRESHOLD) {
up = true;
} else if (sensorY > -SENSOR_THRESHOLD + SENSOR_STICKINESS) {
up = false;
}
upView.setBackgroundColor(up ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
downView.setBackgroundColor(down ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
leftView.setBackgroundColor(left ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
rightView.setBackgroundColor(right ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
}
/**
* Class dedicated to listening for accelerometer events. The results are published to few boolean
* fields in the parent class. We're lazy, so we also update the UI directional indicators here.
*/
class SensorListener implements SensorEventListener {
private Sensor accelerometer;
private float sensorX;
private float sensorY;
public SensorListener() {
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
/**
* Start listening for accelerometer events. Call from {@link Activity#onResume()}.
*/
public void start() {
// plenty fast; you can always try SENSOR_DELAY_GAME
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
}
/**
* Start listening for accelerometer events. Call from {@link Activity#onPause()}.
*/
public void stop() {
sensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
switch (display.getRotation()) {
case Surface.ROTATION_0:
sensorX = event.values[0];
sensorY = event.values[1];
break;
case Surface.ROTATION_90:
sensorX = -event.values[1];
sensorY = event.values[0];
break;
case Surface.ROTATION_180:
sensorX = -event.values[0];
sensorY = -event.values[1];
break;
case Surface.ROTATION_270:
sensorX = event.values[1];
sensorY = -event.values[0];
break;
}
// Log.d(TAG, "rotation=" + display.getRotation() + "; x=" + sensorX + "; y=" + sensorY);
updateDirections(sensorX, sensorY);
}
}
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
/**
* Implemented by <tt>WebSocketClient</tt> and <tt>WebSocketServer</tt>.
* The methods within are called by <tt>WebSocket</tt>.
* @author Nathan Rajlich
*/
interface WebSocketListener {
/**
* Called when the socket connection is first established, and the WebSocket
* handshake has been recieved. This method should parse the
* <var>handshake</var>, and return a boolean indicating whether or not the
* connection is a valid WebSocket connection.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param handshake The entire UTF-8 decoded handshake from the connection.
* @return <var>true</var> if the handshake is valid, and <var>onOpen</var>
* should be immediately called afterwards. <var>false</var> if the
* handshake was invalid, and the connection should be terminated.
* @throws NoSuchAlgorithmException
*/
public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] handShakeBody) throws IOException, NoSuchAlgorithmException;
/**
* Called when an entire text frame has been recieved. Do whatever you want
* here...
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param message The UTF-8 decoded message that was recieved.
*/
public void onMessage(WebSocket conn, String message);
/**
* Called after <var>onHandshakeRecieved</var> returns <var>true</var>.
* Indicates that a complete WebSocket connection has been established,
* and we are ready to send/recieve data.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
*/
public void onOpen(WebSocket conn);
/**
* Called after <tt>WebSocket#close</tt> is explicity called, or when the
* other end of the WebSocket connection is closed.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
*/
public void onClose(WebSocket conn);
/**
* Triggered on any IOException error. This method should be overridden for custom
* implementation of error handling (e.g. when network is not available).
* @param ex
*/
public void onIOError(IOException ex);
/**
* Called to retrieve the Draft of this listener.
*/
public WebSocketDraft getDraft();
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
/**
* <tt>WebSocketServer</tt> is an abstract class that only takes care of the
* HTTP handshake portion of WebSockets. It's up to a subclass to add
* functionality/purpose to the server.
* @author Nathan Rajlich
*/
public abstract class WebSocketServer implements Runnable, WebSocketListener {
// CONSTANTS ///////////////////////////////////////////////////////////////
/**
* The value of <var>handshake</var> when a Flash client requests a policy
* file on this server.
*/
private static final String FLASH_POLICY_REQUEST = "<policy-file-request/>\0";
// INSTANCE PROPERTIES /////////////////////////////////////////////////////
/**
* Holds the list of active WebSocket connections. "Active" means WebSocket
* handshake is complete and socket can be written to, or read from.
*/
private final CopyOnWriteArraySet<WebSocket> connections;
/**
* The port number that this WebSocket server should listen on. Default is
* WebSocket.DEFAULT_PORT.
*/
private int port;
/**
* The socket channel for this WebSocket server.
*/
private ServerSocketChannel server;
/**
* The 'Selector' used to get event keys from the underlying socket.
*/
private Selector selector;
/**
* The Draft of the WebSocket protocol the Server is adhering to.
*/
private WebSocketDraft draft;
// CONSTRUCTORS ////////////////////////////////////////////////////////////
/**
* Nullary constructor. Creates a WebSocketServer that will attempt to
* listen on port WebSocket.DEFAULT_PORT.
*/
public WebSocketServer() {
this(WebSocket.DEFAULT_PORT, WebSocketDraft.AUTO);
}
/**
* Creates a WebSocketServer that will attempt to listen on port
* <var>port</var>.
* @param port The port number this server should listen on.
*/
public WebSocketServer(int port) {
this(port, WebSocketDraft.AUTO);
}
/**
* Creates a WebSocketServer that will attempt to listen on port <var>port</var>,
* and comply with <tt>WebSocketDraft</tt> version <var>draft</var>.
* @param port The port number this server should listen on.
* @param draft The version of the WebSocket protocol that this server
* instance should comply to.
*/
public WebSocketServer(int port, WebSocketDraft draft) {
this.connections = new CopyOnWriteArraySet<WebSocket>();
this.draft = draft;
setPort(port);
}
/**
* Starts the server thread that binds to the currently set port number and
* listeners for WebSocket connection requests.
*/
public void start() {
(new Thread(this)).start();
}
/**
* Closes all connected clients sockets, then closes the underlying
* ServerSocketChannel, effectively killing the server socket thread and
* freeing the port the server was bound to.
* @throws IOException When socket related I/O errors occur.
*/
public void stop() throws IOException {
for (WebSocket ws : connections) {
ws.close();
}
this.server.close();
}
/**
* Sends <var>text</var> to all currently connected WebSocket clients.
* @param text The String to send across the network.
* @throws IOException When socket related I/O errors occur.
*/
public void sendToAll(String text) throws IOException {
for (WebSocket c : this.connections) {
c.send(text);
}
}
/**
* Sends <var>text</var> to all currently connected WebSocket clients,
* except for the specified <var>connection</var>.
* @param connection The {@link WebSocket} connection to ignore.
* @param text The String to send to every connection except <var>connection</var>.
* @throws IOException When socket related I/O errors occur.
*/
public void sendToAllExcept(WebSocket connection, String text) throws IOException {
if (connection == null) {
throw new NullPointerException("'connection' cannot be null");
}
for (WebSocket c : this.connections) {
if (!connection.equals(c)) {
c.send(text);
}
}
}
/**
* Sends <var>text</var> to all currently connected WebSocket clients,
* except for those found in the Set <var>connections</var>.
* @param connections
* @param text
* @throws IOException When socket related I/O errors occur.
*/
public void sendToAllExcept(Set<WebSocket> connections, String text) throws IOException {
if (connections == null) {
throw new NullPointerException("'connections' cannot be null");
}
for (WebSocket c : this.connections) {
if (!connections.contains(c)) {
c.send(text);
}
}
}
/**
* Returns a WebSocket[] of currently connected clients.
* @return The currently connected clients in a WebSocket[].
*/
public WebSocket[] connections() {
return this.connections.toArray(new WebSocket[0]);
}
/**
* Sets the port that this WebSocketServer should listen on.
* @param port The port number to listen on.
*/
public void setPort(int port) {
this.port = port;
}
/**
* Gets the port number that this server listens on.
* @return The port number.
*/
public int getPort() {
return this.port;
}
public WebSocketDraft getDraft() {
return this.draft;
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
try {
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new java.net.InetSocketAddress(port));
selector = Selector.open();
server.register(selector, server.validOps());
} catch (IOException ex) {
onIOError(ex);
return;
}
while(true) {
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()) {
SelectionKey key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if (key.isAcceptable()) {
SocketChannel client = server.accept();
client.configureBlocking(false);
WebSocket c = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
client.register(selector, SelectionKey.OP_READ, c);
}
// if isReadable == true
// then the server is ready to read
if (key.isReadable()) {
WebSocket conn = (WebSocket)key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if (key.isValid() && key.isWritable()) {
WebSocket conn = (WebSocket)key.attachment();
if (conn.handleWrite()) {
conn.socketChannel().register(selector,
SelectionKey.OP_READ, conn);
}
}
}
for (WebSocket conn : this.connections) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
if (conn.hasBufferedData()) {
conn.socketChannel().register(selector,
SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn);
}
}
} catch (IOException ex) {
onIOError(ex);
} catch (RuntimeException ex) {
ex.printStackTrace();
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
//System.err.println("WebSocketServer thread ended!");
}
/**
* Gets the XML string that should be returned if a client requests a Flash
* security policy.
*
* The default implementation allows access from all remote domains, but
* only on the port that this WebSocketServer is listening on.
*
* This is specifically implemented for gitime's WebSocket client for Flash:
* http://github.com/gimite/web-socket-js
*
* @return An XML String that comforms to Flash's security policy. You MUST
* not include the null char at the end, it is appended automatically.
*/
protected String getFlashSecurityPolicy() {
return "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\""
+ getPort() + "\" /></cross-domain-policy>";
}
// WebSocketListener IMPLEMENTATION ////////////////////////////////////////
/**
* Called by a {@link WebSocket} instance when a client connection has
* finished sending a handshake. This method verifies that the handshake is
* a valid WebSocket cliend request. Then sends a WebSocket server handshake
* if it is valid, or closes the connection if it is not.
* @param conn The {@link WebSocket} instance who's handshake has been recieved.
* @param handshake The entire UTF-8 decoded handshake from the connection.
* @return True if the client sent a valid WebSocket handshake and this server
* successfully sent a WebSocket server handshake, false otherwise.
* @throws IOException When socket related I/O errors occur.
* @throws NoSuchAlgorithmException
*/
public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] key3) throws IOException, NoSuchAlgorithmException {
// If a Flash client requested the Policy File...
if (FLASH_POLICY_REQUEST.equals(handshake)) {
String policy = getFlashSecurityPolicy() + "\0";
conn.socketChannel().write(ByteBuffer.wrap(policy.getBytes(WebSocket.UTF8_CHARSET)));
return false;
}
String[] requestLines = handshake.split("\r\n");
boolean isWebSocketRequest = true;
String line = requestLines[0].trim();
String path = null;
if (!(line.startsWith("GET") && line.endsWith("HTTP/1.1"))) {
isWebSocketRequest = false;
} else {
String[] firstLineTokens = line.split(" ");
path = firstLineTokens[1];
}
// 'p' will hold the HTTP headers
Properties p = new Properties();
for (int i = 1; i < requestLines.length; i++) {
line = requestLines[i];
int firstColon = line.indexOf(":");
if (firstColon != -1) {
p.setProperty(line.substring(0, firstColon).trim(), line.substring(firstColon+1).trim());
}
}
String prop = p.getProperty("Upgrade");
if (prop == null || !prop.equals("WebSocket")) {
isWebSocketRequest = false;
}
prop = p.getProperty("Connection");
if (prop == null || !prop.equals("Upgrade")) {
isWebSocketRequest = false;
}
String key1 = p.getProperty("Sec-WebSocket-Key1");
String key2 = p.getProperty("Sec-WebSocket-Key2");
String headerPrefix = "";
byte[] responseChallenge = null;
switch (this.draft) {
case DRAFT75:
if (key1 != null || key2 != null || key3 != null) {
isWebSocketRequest = false;
}
break;
case DRAFT76:
if (key1 == null || key2 == null || key3 == null) {
isWebSocketRequest = false;
}
break;
}
if (isWebSocketRequest) {
if (key1 != null && key2 != null && key3 != null) {
headerPrefix = "Sec-";
byte[] part1 = this.getPart(key1);
byte[] part2 = this.getPart(key2);
byte[] challenge = new byte[16];
challenge[0] = part1[0];
challenge[1] = part1[1];
challenge[2] = part1[2];
challenge[3] = part1[3];
challenge[4] = part2[0];
challenge[5] = part2[1];
challenge[6] = part2[2];
challenge[7] = part2[3];
challenge[8] = key3[0];
challenge[9] = key3[1];
challenge[10] = key3[2];
challenge[11] = key3[3];
challenge[12] = key3[4];
challenge[13] = key3[5];
challenge[14] = key3[6];
challenge[15] = key3[7];
MessageDigest md5 = MessageDigest.getInstance("MD5");
responseChallenge = md5.digest(challenge);
}
String responseHandshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n";
responseHandshake += headerPrefix+"WebSocket-Origin: " + p.getProperty("Origin") + "\r\n";
responseHandshake += headerPrefix+"WebSocket-Location: ws://" + p.getProperty("Host") + path + "\r\n";
if (p.containsKey(headerPrefix+"WebSocket-Protocol")) {
responseHandshake += headerPrefix+"WebSocket-Protocol: " + p.getProperty("WebSocket-Protocol") + "\r\n";
}
if (p.containsKey("Cookie")){
responseHandshake += "Cookie: " + p.getProperty("Cookie")+"\r\n";
}
responseHandshake += "\r\n"; // Signifies end of handshake
//Can not use UTF-8 here because we might lose bytes in response during conversion
conn.socketChannel().write(ByteBuffer.wrap(responseHandshake.getBytes()));
//Only set when Draft 76
if(responseChallenge!=null){
conn.socketChannel().write(ByteBuffer.wrap(responseChallenge));
}
return true;
}
// If we got to here, then the client sent an invalid handshake, and we
// return false to make the WebSocket object close the connection.
return false;
}
public void onMessage(WebSocket conn, String message) {
onClientMessage(conn, message);
}
public void onOpen(WebSocket conn) {
if (this.connections.add(conn)) {
onClientOpen(conn);
}
}
public void onClose(WebSocket conn) {
if (this.connections.remove(conn)) {
onClientClose(conn);
}
}
private byte[] getPart(String key) {
long keyNumber = Long.parseLong(key.replaceAll("[^0-9]",""));
long keySpace = key.split("\u0020").length - 1;
long part = new Long(keyNumber / keySpace);
return new byte[] {
(byte)( part >> 24 ),
(byte)( (part << 8) >> 24 ),
(byte)( (part << 16) >> 24 ),
(byte)( (part << 24) >> 24 )
};
}
// ABTRACT METHODS /////////////////////////////////////////////////////////
public abstract void onClientOpen(WebSocket conn);
public abstract void onClientClose(WebSocket conn);
public abstract void onClientMessage(WebSocket conn, String message);
public abstract void onIOError(IOException ex);
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
/**
* The <tt>WebSocketClient</tt> is an abstract class that expects a valid
* "ws://" URI to connect to. When connected, an instance recieves important
* events related to the life of the connection. A subclass must implement
* <var>onOpen</var>, <var>onClose</var>, and <var>onMessage</var> to be
* useful. An instance can send messages to it's connected server via the
* <var>send</var> method.
* @author Nathan Rajlich
*/
public abstract class WebSocketClient implements Runnable, WebSocketListener {
// INSTANCE PROPERTIES /////////////////////////////////////////////////////
/**
* The URI this client is supposed to connect to.
*/
private URI uri = null;
/**
* The WebSocket instance this client object wraps.
*/
private WebSocket conn = null;
/**
* The SocketChannel instance this client uses.
*/
private SocketChannel client = null;
/**
* The 'Selector' used to get event keys from the underlying socket.
*/
private Selector selector = null;
/**
* Keeps track of whether or not the client thread should continue running.
*/
private boolean running = false;
/**
* The Draft of the WebSocket protocol the Client is adhering to.
*/
private WebSocketDraft draft = null;
/**
* Number 1 used in handshake
*/
private int number1 = 0;
/**
* Number 2 used in handshake
*/
private int number2 = 0;
/**
* Key3 used in handshake
*/
private byte[] key3 = null;
// CONSTRUCTORS ////////////////////////////////////////////////////////////
public WebSocketClient(URI serverURI) {
this(serverURI, WebSocketDraft.DRAFT76);
}
/**
* Constructs a WebSocketClient instance and sets it to the connect to the
* specified URI. The client does not attampt to connect automatically. You
* must call <var>connect</var> first to initiate the socket connection.
* @param serverUri The <tt>URI</tt> of the WebSocket server to connect to.
* @throws IllegalArgumentException If <var>draft</var>
* is <code>WebSocketDraft.AUTO</code>
*/
public WebSocketClient(URI serverUri, WebSocketDraft draft) {
this.uri = serverUri;
if (draft == WebSocketDraft.AUTO) {
throw new IllegalArgumentException(draft + " is meant for `WebSocketServer` only!");
}
this.draft = draft;
}
// PUBLIC INSTANCE METHODS /////////////////////////////////////////////////
/**
* Gets the URI that this WebSocketClient is connected to.
* @return The <tt>URI</tt> for this WebSocketClient.
*/
public URI getURI() {
return uri;
}
@Override
public WebSocketDraft getDraft() {
return draft;
}
/**
* Starts a background thread that attempts and maintains a WebSocket
* connection to the URI specified in the constructor or via <var>setURI</var>.
* <var>setURI</var>.
*/
public void connect() {
if (!running) {
this.running = true;
(new Thread(this)).start();
}
}
/**
* Calls <var>close</var> on the underlying SocketChannel, which in turn
* closes the socket connection, and ends the client socket thread.
* @throws IOException When socket related I/O errors occur.
*/
public void close() throws IOException
{
if (running)
{
selector.wakeup();
conn.close();
}
}
/**
* Sends <var>text</var> to the connected WebSocket server.
* @param text The String to send to the WebSocket server.
* @throws IOException When socket related I/O errors occur.
*/
public void send(String text) throws IOException {
if (conn != null)
{
conn.send(text);
}
}
/**
* Reinitializes and prepares the class to be used for reconnect.
* @return
*/
public void releaseAndInitialize()
{
conn = null;
client = null;
selector = null;
running = false;
draft = null;
number1 = 0;
number2 = 0;
key3 = null;
}
private boolean tryToConnect(InetSocketAddress remote) {
// The WebSocket constructor expects a SocketChannel that is
// non-blocking, and has a Selector attached to it.
try {
client = SocketChannel.open();
client.configureBlocking(false);
client.connect(remote);
selector = Selector.open();
this.conn = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
// At first, we're only interested in the 'CONNECT' keys.
client.register(selector, SelectionKey.OP_CONNECT);
} catch (IOException ex) {
onIOError(conn, ex);
return false;
}
return true;
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
running = tryToConnect(new InetSocketAddress(uri.getHost(), getPort()));
while (this.running) {
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while (i.hasNext()) {
SelectionKey key = i.next();
i.remove();
if (key.isConnectable()) {
finishConnect();
}
if (key.isReadable()) {
conn.handleRead();
}
}
} catch (IOException ex) {
onIOError(conn, ex);
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
//System.err.println("WebSocketClient thread ended!");
}
private int getPort() {
int port = uri.getPort();
return port == -1 ? WebSocket.DEFAULT_PORT : port;
}
private void finishConnect() throws IOException {
if (client.isConnectionPending()) {
client.finishConnect();
}
// Now that we're connected, re-register for only 'READ' keys.
client.register(selector, SelectionKey.OP_READ);
sendHandshake();
}
private void sendHandshake() throws IOException {
String path = uri.getPath();
if (path.indexOf("/") != 0) {
path = "/" + path;
}
int port = getPort();
String host = uri.getHost() + (port != WebSocket.DEFAULT_PORT ? ":" + port : "");
String origin = null; // TODO: Make 'origin' configurable
String request = "GET " + path + " HTTP/1.1\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n" +
"Host: " + host + "\r\n" +
"Origin: " + origin + "\r\n";
if (this.draft == WebSocketDraft.DRAFT76) {
request += "Sec-WebSocket-Key1: " + this.generateKey() + "\r\n";
request += "Sec-WebSocket-Key2: " + this.generateKey() + "\r\n";
this.key3 = new byte[8];
(new Random()).nextBytes(this.key3);
}
request += "\r\n";
if (this.key3 != null) {
conn.socketChannel().write(new ByteBuffer[] {
ByteBuffer.wrap(request.getBytes(WebSocket.UTF8_CHARSET)),
ByteBuffer.wrap(this.key3)
});
}
else
{
conn.socketChannel().write(ByteBuffer.wrap(request.getBytes(WebSocket.UTF8_CHARSET)));
}
}
private String generateKey() {
Random r = new Random();
long maxNumber = 4294967295L;
long spaces = r.nextInt(12) + 1;
int max = new Long(maxNumber / spaces).intValue();
max = Math.abs(max);
int number = r.nextInt(max) + 1;
if (this.number1 == 0) {
this.number1 = number;
}
else {
this.number2 = number;
}
long product = number * spaces;
String key = Long.toString(product);
//always insert atleast one random character
int numChars = r.nextInt(12)+1;
for (int i=0; i < numChars; i++){
int position = r.nextInt(key.length());
position = Math.abs(position);
char randChar = (char)(r.nextInt(95) + 33);
//exclude numbers here
if(randChar >= 48 && randChar <= 57){
randChar -= 15;
}
key = new StringBuilder(key).insert(position, randChar).toString();
}
for (int i = 0; i < spaces; i++){
int position = r.nextInt(key.length() - 1) + 1;
position = Math.abs(position);
key = new StringBuilder(key).insert(position,"\u0020").toString();
}
return key;
}
// WebSocketListener IMPLEMENTATION ////////////////////////////////////////
/**
* Parses the server's handshake to verify that it's a valid WebSocket
* handshake.
* @param conn The {@link WebSocket} instance who's handshake has been recieved.
* In the case of <tt>WebSocketClient</tt>, this.conn == conn.
* @param handshake The entire UTF-8 decoded handshake from the connection.
* @return <var>true</var> if <var>handshake</var> is a valid WebSocket server
* handshake, <var>false</var> otherwise.
* @throws IOException When socket related I/O errors occur.
* @throws NoSuchAlgorithmException
*/
public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] reply) throws IOException, NoSuchAlgorithmException {
// TODO: Do some parsing of the returned handshake, and close connection
// (return false) if we recieved anything unexpected.
if(this.draft == WebSocketDraft.DRAFT76) {
if (reply == null) {
return false;
}
byte[] challenge = new byte[] {
(byte)( this.number1 >> 24 ),
(byte)( (this.number1 << 8) >> 24 ),
(byte)( (this.number1 << 16) >> 24 ),
(byte)( (this.number1 << 24) >> 24 ),
(byte)( this.number2 >> 24 ),
(byte)( (this.number2 << 8) >> 24 ),
(byte)( (this.number2 << 16) >> 24 ),
(byte)( (this.number2 << 24) >> 24 ),
this.key3[0],
this.key3[1],
this.key3[2],
this.key3[3],
this.key3[4],
this.key3[5],
this.key3[6],
this.key3[7]
};
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] expected = md5.digest(challenge);
for (int i = 0; i < reply.length; i++) {
if (expected[i] != reply[i]) {
return false;
}
}
}
return true;
}
/**
* Calls subclass' implementation of <var>onMessage</var>.
* @param conn
* @param message
*/
public void onMessage(WebSocket conn, String message) {
onMessage(message);
}
/**
* Calls subclass' implementation of <var>onOpen</var>.
* @param conn
*/
public void onOpen(WebSocket conn) {
onOpen();
}
/**
* Calls subclass' implementation of <var>onClose</var>.
* @param conn
*/
public void onClose(WebSocket conn)
{
if (running)
{
onClose();
}
releaseAndInitialize();
}
/**
* Calls subclass' implementation of <var>onIOError</var>.
* @param conn
*/
public void onIOError(WebSocket conn, IOException ex)
{
releaseAndInitialize();
onIOError(ex);
}
// ABTRACT METHODS /////////////////////////////////////////////////////////
public abstract void onMessage(String message);
public abstract void onOpen();
public abstract void onClose();
public abstract void onIOError(IOException ex);
}
| Java |
package net.tootallnate.websocket;
/**
* Enum for WebSocket Draft
*/
public enum WebSocketDraft {
AUTO,
DRAFT75,
DRAFT76
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.BlockingQueue;
/**
* Represents one end (client or server) of a single WebSocket connection.
* Takes care of the "handshake" phase, then allows for easy sending of
* text frames, and recieving frames through an event-based model.
*
* This is an inner class, used by <tt>WebSocketClient</tt> and
* <tt>WebSocketServer</tt>, and should never need to be instantiated directly
* by your code. However, instances are exposed in <tt>WebSocketServer</tt>
* through the <i>onClientOpen</i>, <i>onClientClose</i>,
* <i>onClientMessage</i> callbacks.
* @author Nathan Rajlich
*/
public final class WebSocket {
// CONSTANTS ///////////////////////////////////////////////////////////////
/**
* The default port of WebSockets, as defined in the spec. If the nullary
* constructor is used, DEFAULT_PORT will be the port the WebSocketServer
* is binded to. Note that ports under 1024 usually require root permissions.
*/
public static final int DEFAULT_PORT = 80;
/**
* The WebSocket protocol expects UTF-8 encoded bytes.
*/
public static final String UTF8_CHARSET = "UTF-8";
/**
* The byte representing CR, or Carriage Return, or \r
*/
public static final byte CR = (byte)0x0D;
/**
* The byte representing LF, or Line Feed, or \n
*/
public static final byte LF = (byte)0x0A;
/**
* The byte representing the beginning of a WebSocket text frame.
*/
public static final byte START_OF_FRAME = (byte)0x00;
/**
* The byte representing the end of a WebSocket text frame.
*/
public static final byte END_OF_FRAME = (byte)0xFF;
// INSTANCE PROPERTIES /////////////////////////////////////////////////////
/**
* The <tt>SocketChannel</tt> instance to use for this server connection.
* This is used to read and write data to.
*/
private final SocketChannel socketChannel;
/**
* Internally used to determine whether to recieve data as part of the
* remote handshake, or as part of a text frame.
*/
private boolean handshakeComplete;
/**
* The listener to notify of WebSocket events.
*/
private WebSocketListener wsl;
/**
* The 1-byte buffer reused throughout the WebSocket connection to read data.
*/
private ByteBuffer buffer;
/**
* Buffer where data is read to from the socket
*/
private ByteBuffer socketBuffer;
/**
* The bytes that make up the remote handshake.
*/
private ByteBuffer remoteHandshake;
/**
* The bytes that make up the current text frame being read.
*/
private ByteBuffer currentFrame;
/**
* Queue of buffers that need to be sent to the client.
*/
private BlockingQueue<ByteBuffer> bufferQueue;
/**
* Lock object to ensure that data is sent from the bufferQueue in
* the proper order.
*/
private Object bufferQueueMutex = new Object();
private boolean readingState = false;
// CONSTRUCTOR /////////////////////////////////////////////////////////////
/**
* Used in {@link WebSocketServer} and {@link WebSocketClient}.
* @param socketChannel The <tt>SocketChannel</tt> instance to read and
* write to. The channel should already be registered
* with a Selector before construction of this object.
* @param bufferQueue The Queue that we should use to buffer data that
* hasn't been sent to the client yet.
* @param listener The {@link WebSocketListener} to notify of events when
* they occur.
*/
WebSocket(SocketChannel socketChannel, BlockingQueue<ByteBuffer> bufferQueue, WebSocketListener listener) {
this.socketChannel = socketChannel;
this.bufferQueue = bufferQueue;
this.handshakeComplete = false;
this.remoteHandshake = this.currentFrame = null;
this.socketBuffer = ByteBuffer.allocate(8192);
this.buffer = ByteBuffer.allocate(1);
this.wsl = listener;
}
/**
* Should be called when a Selector has a key that is writable for this
* WebSocket's SocketChannel connection.
* @throws IOException When socket related I/O errors occur.
* @throws NoSuchAlgorithmException
*/
void handleRead() throws IOException, NoSuchAlgorithmException {
int bytesRead = -1;
try {
socketBuffer.rewind();
bytesRead = this.socketChannel.read(this.socketBuffer);
} catch(Exception ex) {}
if (bytesRead == -1) {
close();
} else if (bytesRead > 0) {
for(int i = 0; i < bytesRead; i++) {
buffer.rewind();
buffer.put(socketBuffer.get(i));
this.buffer.rewind();
if (!this.handshakeComplete)
recieveHandshake();
else
recieveFrame();
}
}
}
// PUBLIC INSTANCE METHODS /////////////////////////////////////////////////
/**
* Closes the underlying SocketChannel, and calls the listener's onClose
* event handler.
* @throws IOException When socket related I/O errors occur.
*/
public void close() throws IOException {
this.socketChannel.close();
this.wsl.onClose(this);
}
/**
* @return True if all of the text was sent to the client by this thread.
* False if some of the text had to be buffered to be sent later.
*/
public boolean send(String text) throws IOException {
if (!this.handshakeComplete) throw new NotYetConnectedException();
if (text == null) throw new NullPointerException("Cannot send 'null' data to a WebSocket.");
// Get 'text' into a WebSocket "frame" of bytes
byte[] textBytes = text.getBytes(UTF8_CHARSET);
ByteBuffer b = ByteBuffer.allocate(textBytes.length + 2);
b.put(START_OF_FRAME);
b.put(textBytes);
b.put(END_OF_FRAME);
b.rewind();
// See if we have any backlog that needs to be sent first
if (handleWrite()) {
// Write the ByteBuffer to the socket
this.socketChannel.write(b);
}
// If we didn't get it all sent, add it to the buffer of buffers
if (b.remaining() > 0) {
if (!this.bufferQueue.offer(b)) {
throw new IOException("Buffers are full, message could not be sent to" +
this.socketChannel.socket().getRemoteSocketAddress());
}
return false;
}
return true;
}
boolean hasBufferedData() {
return !this.bufferQueue.isEmpty();
}
/**
* @return True if all data has been sent to the client, false if there
* is still some buffered.
*/
boolean handleWrite() throws IOException {
synchronized (this.bufferQueueMutex) {
ByteBuffer buffer = this.bufferQueue.peek();
while (buffer != null) {
this.socketChannel.write(buffer);
if (buffer.remaining() > 0) {
return false; // Didn't finish this buffer. There's more to send.
} else {
this.bufferQueue.poll(); // Buffer finished. Remove it.
buffer = this.bufferQueue.peek();
}
}
return true;
}
}
public SocketChannel socketChannel() {
return this.socketChannel;
}
// PRIVATE INSTANCE METHODS ////////////////////////////////////////////////
private void recieveFrame() {
byte newestByte = this.buffer.get();
if (newestByte == START_OF_FRAME && !readingState) { // Beginning of Frame
this.currentFrame = null;
readingState = true;
} else if (newestByte == END_OF_FRAME && readingState) { // End of Frame
readingState = false;
String textFrame = null;
// currentFrame will be null if END_OF_FRAME was send directly after
// START_OF_FRAME, thus we will send 'null' as the sent message.
if (this.currentFrame != null) {
try {
textFrame = new String(this.currentFrame.array(), UTF8_CHARSET);
} catch (UnsupportedEncodingException ex) {
// TODO: Fire an 'onError' handler here
ex.printStackTrace();
textFrame = "";
}
}
this.wsl.onMessage(this, textFrame);
} else { // Regular frame data, add to current frame buffer
ByteBuffer frame = ByteBuffer.allocate((this.currentFrame != null ? this.currentFrame.capacity() : 0) + this.buffer.capacity());
if (this.currentFrame != null) {
this.currentFrame.rewind();
frame.put(this.currentFrame);
}
frame.put(newestByte);
this.currentFrame = frame;
}
}
private void recieveHandshake() throws IOException, NoSuchAlgorithmException {
ByteBuffer ch = ByteBuffer.allocate((this.remoteHandshake != null ? this.remoteHandshake.capacity() : 0) + this.buffer.capacity());
if (this.remoteHandshake != null) {
this.remoteHandshake.rewind();
ch.put(this.remoteHandshake);
}
ch.put(this.buffer);
this.remoteHandshake = ch;
byte[] h = this.remoteHandshake.array();
// If the ByteBuffer contains 16 random bytes, and ends with
// 0x0D 0x0A 0x0D 0x0A (or two CRLFs), then the client
// handshake is complete for Draft 76 Client.
if((h.length >= 20 && h[h.length-20] == CR
&& h[h.length-19] == LF
&& h[h.length-18] == CR
&& h[h.length-17] == LF)) {
completeHandshake(new byte[] {
h[h.length-16],
h[h.length-15],
h[h.length-14],
h[h.length-13],
h[h.length-12],
h[h.length-11],
h[h.length-10],
h[h.length-9],
h[h.length-8],
h[h.length-7],
h[h.length-6],
h[h.length-5],
h[h.length-4],
h[h.length-3],
h[h.length-2],
h[h.length-1]
});
// If the ByteBuffer contains 8 random bytes,ends with
// 0x0D 0x0A 0x0D 0x0A (or two CRLFs), and the response
// contains Sec-WebSocket-Key1 then the client
// handshake is complete for Draft 76 Server.
} else if ((h.length>=12 && h[h.length-12] == CR
&& h[h.length-11] == LF
&& h[h.length-10] == CR
&& h[h.length-9] == LF) && new String(this.remoteHandshake.array(), UTF8_CHARSET).contains("Sec-WebSocket-Key1")) {
completeHandshake(new byte[] {
h[h.length-8],
h[h.length-7],
h[h.length-6],
h[h.length-5],
h[h.length-4],
h[h.length-3],
h[h.length-2],
h[h.length-1]
});
// Consider Draft 75, and the Flash Security Policy
// Request edge-case.
} else if ((h.length>=4 && h[h.length-4] == CR
&& h[h.length-3] == LF
&& h[h.length-2] == CR
&& h[h.length-1] == LF) && !(new String(this.remoteHandshake.array(), UTF8_CHARSET).contains("Sec")) ||
(h.length==23 && h[h.length-1] == 0) ) {
completeHandshake(null);
}
}
private void completeHandshake(byte[] handShakeBody) throws IOException, NoSuchAlgorithmException {
byte[] handshakeBytes = this.remoteHandshake.array();
String handshake = new String(handshakeBytes, UTF8_CHARSET);
this.handshakeComplete = true;
if (this.wsl.onHandshakeRecieved(this, handshake, handShakeBody)) {
this.wsl.onOpen(this);
} else {
close();
}
}
}
| Java |
package com.example.androideye;
import java.io.DataInputStream;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.util.Log;
public class PrincipalComponentAnalysis implements FaceDescriptor{
private static double WIDTH = 75.0;
private static double HEIGHT = 150.0;
float feats[] = null;
float trasformMatrix[][] = null;
float mean[]=null;
int rgbpixels[] = null;
float pixels[] = null;
String fileName = null;
long time;
public PrincipalComponentAnalysis(){
initialize(new File(Database.BASE_DIR, "PCA_95.dat").getAbsolutePath());
}
public PrincipalComponentAnalysis(File transformFile){
initialize(transformFile.getAbsolutePath());
}
public PrincipalComponentAnalysis(String transformFile){
initialize(transformFile);
}
private void initialize(String transformFile){
fileName = transformFile;
readPCA();
}
/**
* Read the transformation Matrix from file
*/
private void readPCA(){
Log.v("PCA", "Reading File "+fileName);
DataInputStream dis = FileUtils.readBinaryFile(fileName);
mean = FileUtils.readFloatArray(dis);
trasformMatrix = FileUtils.readFloatMatrix(dis);
}
/**
* PCA transform (Mean remove and Matrix multiplication).
* Store in feats var.
* @param a One dimension Matrix containing image.
*/
private void transform(float a[]){
Log.v("PCA", "PCA transform.");
//remove mean
for (int i = 0; i < a.length; i++) {
a[i]-=mean[i];
}
Log.v("PCA", "Mean removed.");
int nrow = trasformMatrix.length;
int ncol = trasformMatrix[0].length;
assert(nrow==a.length):"Matrix multiplication dimensions must agree.";
if(feats==null){
feats = new float[ncol];
}
for (int i = 0; i < feats.length; i++) {
feats[i]=0.0f;
}
Log.v("PCA", "Matrix multiplication");
//Log.v("PCA", ""+a.length);
//matrix multiplication
for (int k = 0; k < nrow; k++) {
for (int j = 0; j < ncol; j++) {
feats[j]+=a[k]*trasformMatrix[k][j];
}
//Log.v("PCA", ""+k + " of "+a.length + " and " + trasformMatrix.length);
}
//Log.v("PCA", "Transform applied.");
}
public Collection<Double> getDescriptor(Bitmap img) {
// TODO Auto-generated method stub
time = System.currentTimeMillis();
Bitmap resImg = FaceImage.resizeBitmap(img, WIDTH/img.getWidth(), HEIGHT/img.getHeight());
img.recycle();
Log.v("PCA", "Img size: "+resImg.getWidth() + " " + resImg.getHeight());
int lenght = resImg.getWidth()*resImg.getHeight();
if(rgbpixels==null || rgbpixels.length<lenght)
rgbpixels = new int[lenght];
if(pixels==null || pixels.length<lenght)
pixels = new float[lenght];
FaceImage.getPixelArray(resImg, rgbpixels);
Log.v("PCA", ""+pixels.length);
for (int i = 0; i < rgbpixels.length; i++) {
pixels[i] = (float)FaceImage.rgb2gray(rgbpixels[i]);
}
transform(pixels);
LinkedList<Double> descriptor = new LinkedList<Double>();
for (double d : feats) {
descriptor.addLast(d);
}
time = System.currentTimeMillis() - time;
return descriptor;
}
public double timeElapsed() {
// TODO Auto-generated method stub
return ((double)(time))/1000.0;
}
public double distance(Collection<Double> c1, Collection<Double> c2) {
// TODO Auto-generated method stub
return MathUtils.euclideanDistance(c1, c2);
}
}
| Java |
package com.example.androideye;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.Rect;
/**
* Face Detector interface
* @author Everton Fernandes da Silva
* @author Alan Zanoni Peixinho
*
*/
public interface FaceDetect {
/**
* Find all the faces in the image.
* @param img Image submitted to face detection.
* @return Return a list containing the boxes that contain each face found.
*/
public List<Rect> findFaces(Bitmap img);
/**
* Time elapsed in face detection.
* @return Return the time spent in face detection.
*/
public double timeElapsed();//return the time elapsed in the last face detection
public int normalSize();
public Bitmap normalizeSize(Bitmap b);
}
| Java |
package com.example.androideye;
import android.graphics.Rect;
/**
* Wrap some image functions using OpenCV Library.
*
* @author André Marcelo Farina
*/
public class OpenCV {
static{
System.loadLibrary("opencv");
}
public static native byte[] findContours(int[] data, int w, int h);
public static native byte[] getSourceImage();
public static native boolean setSourceImage(int[] data, int w, int h);
public static native byte[] buscaFace();
public static native boolean initFaceDetection(String cascadePath);
public static native void releaseFaceDetection();
public static native boolean highlightFaces();
public static native Rect[] findAllFaces();
public static native Rect findSingleFace();
public static native void learn(Object []arr);
public static native void recognize();
public static native int recognizePicture();
public static native void save(int[] photoData, int width, int height, String filePath);
public static native boolean saveImage(int[] photoData, int width, int height, String filePath, boolean census);
public static native boolean buildTrainFile(String dirPath);
} | Java |
package com.example.androideye;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;
/**
* Verify if it is the first time the App is running.
* @author Alan Zanoni Peixinho
*
*/
public class StartupChoiceActivity extends Activity {
public static final String TAG = "StartupChoice";
private static boolean DEBUG = false;
private static final int CHECK_CODE = 12;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(DEBUG){
startActivity(new Intent(this, ExperimentRun.class));
//startActivity(new Intent(this, Tutorial.class));
finish();
return;
}
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, CHECK_CODE);
}
private void callStartActivity()
{
SharedPreferences mPrefs = getSharedPreferences(Globals.PersistentInfo.PREFERENCES_FILE, Context.MODE_PRIVATE);
if(!mPrefs.getBoolean(Globals.PersistentInfo.HAS_STARTED, false)) {
// Do what ever you want to do the first time the app is run
Log.v(TAG, "This is the first time the app is running.");
startActivity(new Intent(this, Tutorial.class));
finish();
//Do what ever we want to do on a normal startup. This is pretty much always mean starting a new activity
} else {
Log.i(TAG, "We've already started the app at least once");
//Do what ever we want to do on a normal startup. This is pretty much always mean starting a new activity
startActivity(new Intent(this, UserInterface.class));
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
callStartActivity();
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("There is an error in the Text To Speech Software.");
alert.show();
alert.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
}
}
}
}
| Java |
package com.example.androideye;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Collection;
import java.util.LinkedList;
public class FileUtils {
public static final int BUFFER_SIZE = 2*1024;//2K
/**
* In the freaking Java we need a 100 code lines to read a simple file.
* @param fileName The file to be read.
* @return Return the file content.
*/
public static String readFile(String fileName){
try{
FileReader in = new FileReader(fileName);
StringBuilder contents = new StringBuilder();
char[] buffer = new char[4096];
int read = 0;
do {
contents.append(buffer, 0, read);
read = in.read(buffer);
} while (read >= 0);
in.close();
return contents.toString();
}catch(Exception e){
e.printStackTrace();
}
//in fail case
return null;
}
/**
* In the freaking Java we need a 100 code lines to read a simple file.
* @param file The file to be read.
* @return Return the file content.
*/
public static String readFile(File file){
return readFile(file.getAbsolutePath());
}
/**
* Open a binary file to read.
* @param filename File to be opened.
* @return Return a data input stream.
*/
public static DataInputStream readBinaryFile(String filename){
try{
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream filein = null;
System.gc();
fis = new FileInputStream(filename);
bis = new BufferedInputStream(fis, BUFFER_SIZE);
filein = new DataInputStream(bis);//buffer-100k
return filein;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;//error
}
/**
* Open a binary file to read.
* @param filename File to be opened.
* @return Return a data input stream.
*/
public static DataInputStream readBinaryFile(File file){
return readBinaryFile(file.getAbsolutePath());
}
public static DataOutputStream writeBinaryFile(String filename){
try{
FileOutputStream fos = null;
BufferedOutputStream bos = null;
DataOutputStream fileout = null;
System.gc();
fos = new FileOutputStream(filename);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
fileout = new DataOutputStream(bos);//buffer-100k
return fileout;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;//error
}
public static DataOutputStream writeBinaryFile(File file){
return writeBinaryFile(file.getAbsolutePath());
}
public static float[] readFloatArray(DataInputStream dis){
try{
int sz = dis.readInt();
float a[] = new float[sz];
for (int i = 0; i < sz; i++) {
float f = dis.readFloat();
a[i] = f;
}
return a;
}catch(Exception e){
e.printStackTrace();
}
return null;//error
}
public static void writeFloatArray(DataOutputStream dout, float a[]){
try{
dout.writeInt(a.length);
for (float f : a) {
dout.writeFloat(f);
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static Collection<Double> readFloatCollection(DataInputStream dis){
try{
int sz = dis.readInt();
LinkedList<Double> c = new LinkedList<Double>();
for (int i = 0; i < sz; i++) {
float f = dis.readFloat();
c.addLast((double)f);
}
return c;
}catch(Exception e){
e.printStackTrace();
}
return null;//error
}
@SuppressWarnings("unchecked")
public static void writeFloatCollection(DataOutputStream dout, Collection<Double> c){
try{
dout.writeInt(c.size());
for (Number d : c) {
dout.writeFloat(d.floatValue());
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static float[][] readFloatMatrix(DataInputStream dis){
try{
int nrows=dis.readInt();
int ncols=dis.readInt();
float [][]f = new float[nrows][ncols];
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
f[i][j] = dis.readFloat();
}
}
return f;
}catch(Exception e){
e.printStackTrace();
}
return null;//error
}
public static void writeFloatMatrix(DataOutputStream dos, float [][]f){
int nrows=f.length;
int ncols=f[0].length;
try{
dos.writeInt(nrows);
dos.writeInt(ncols);
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
dos.writeFloat(f[i][j]);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
| Java |
package com.example.androideye;
import java.util.Collection;
import android.graphics.Bitmap;
/**
* Face Descriptor interface.
* @author Alan Zanoni Peixinho
*
*/
public interface FaceDescriptor {
/**
* Extract descriptor from a face image.
* @param img Face image.
* @return Return the face descriptor.
*/
public Collection<Double> getDescriptor(Bitmap img);
/**
* Time spent in features extraction.
* @return Return the time elapsed in the feature extraction.
*/
public double timeElapsed();
/**
* Compute the distance between descriptor samples.
* @param c1
* @param c2
* @return
*/
public double distance(Collection<Double> c1, Collection<Double> c2);
}
| Java |
package com.example.androideye;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
/**
* Image utilities for face recognition.
* @author Alan Zanoni Peixinho.
* @author Everton Fernandes da Silva.
*
*/
public class FaceImage {
/**
* Load an image. Duuhr.
* @param filename File containing image.
* @return Return the image.
*/
public static Bitmap loadImage(String filename)
{
Bitmap b = BitmapFactory.decodeFile(filename);
return b;
}
/**
* Load an image. Duuhr.
* @param filename File containing image.
* @return Return the image.
*/
public static Bitmap loadImage(File f)
{
return loadImage(f.getAbsolutePath());
}
/**
* Resize a bitmap in the indicated scale.
* @param bm Image to be resized.
* @param scale Scale used in resize.
* @return Return a scaled image.
*/
public static Bitmap resizeBitmap(Bitmap bm, double scale) {
return resizeBitmap(bm, scale, scale);
}
/**
* Resize a bitmap in the indicated scale width and height.
* @param bm Image to be resized.
* @param scaleWidth Scale width used in resize.
* @param scaleHeight Scale height used in resize.
* @return Return a scaled image.
*/
public static Bitmap resizeBitmap(Bitmap bm, double scaleWidth, double scaleHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale((float)scaleWidth, (float)scaleHeight);
Log.v("Scale","Matrix ready");
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
Log.v("Scale", "Bitmap resized");
return resizedBitmap;
}
/**
* Resize a rect size.
* @param r Rect to be resized.
* @param scale Scale used in resize.
* @return Return a scaled Rect.
*/
public static Rect resizeRect(Rect r, double scale){
return new Rect((int)(r.left*scale), (int)(r.top*scale), (int)(r.right*scale), (int)(r.bottom*scale));
}
/**
* Save an image in file.
* @param b Image to be saved.
* @param filename File to store image.
*/
public static void saveImage(Bitmap b, String filename)
{
saveImage(b, new File(filename));
}
/**
* Save an image in file.
* @param b Image to be saved.
* @param file File to store image.
*/
public static void saveImage(Bitmap bitmap, File file) {
// TODO Auto-generated method stub
if(file.exists()){
try {
file.delete();
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//uma saga epica para apenas salvar a imagem apos marcar a face
try {
FileOutputStream fout = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Crop a region of the image.
* @param b Image to be cropped.
* @param r Region to crop.
* @return Return a cropped image.
*/
public static Bitmap cropFace(Bitmap b, Rect r)
{
Log.v("Croping", "Rect: ("+r.left+", "+r.top+") ("+r.right+", "+r.bottom+")");
Log.v("Croping", "Image: ("+b.getWidth()+", "+b.getHeight()+")");
return Bitmap.createBitmap(b, r.left, r.top, r.width(), r.height());
}
/**
* Draw a rect in an image (Usefull to see the region in the image).
* @param b Image to be drawn.
* @param r Rect to be drawn.
* @param color Color of drawn rectangle.
* @return
*/
public static Bitmap drawRect(Bitmap b, Rect r, int color){
Bitmap bitmap = Bitmap.createBitmap(b.getWidth(), b.getHeight(), b.getConfig());
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(b, new Matrix(), null);
Paint paint = new Paint();
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
canvas.drawRect(r, paint);
return bitmap;
}
/**
* Draw a rect in an image (Usefull to see the region in the image).
* @param b Image to be drawn.
* @param r List of rects to be drawn.
* @param color Color of drawn rectangle.
* @return
*/
public static Bitmap drawRects(Bitmap b, Collection<Rect> r, int color){
Bitmap bitmap = Bitmap.createBitmap(b.getWidth(), b.getHeight(), b.getConfig());
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(b, new Matrix(), null);
Paint paint = new Paint();
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
for (Iterator<Rect> iterator = r.iterator(); iterator.hasNext();) {
Rect rect = (Rect) iterator.next();
canvas.drawRect(rect, paint);
}
return bitmap;
}
/**
* Get a pixel array from image.
* @param img Image
* @param outArray Output array.
*/
public static void getPixelArray(Bitmap img, int outArray[]){
int width = img.getWidth();
int height = img.getHeight();
assert(outArray.length>=width*height):"The array is too small.";
img.getPixels(outArray, 0, width, 0, 0, width, height);
}
/**
* Get a pixel array from image.
* @param img Image.
* @return Output array.
*/
public static int[] getPixelArray(Bitmap img){
int []a = new int[img.getWidth()*img.getHeight()];
getPixelArray(img, a);
return a;
}
/**
* Converts a RGB image to grayscale.
* @param pixels Image in array format.
*/
public static void rgb2gray(int pixels[]){
for (int i = 0; i < pixels.length; i++) {
pixels[i] = (int)rgb2gray(pixels[i]);
}
}
/**
* Converts a RGB color to grayscale.
* @param color RGB color.
* @return Return the corresponding grayscale color.
*/
public static double rgb2gray(int color)
{
return Math.min(0.2126*Color.red(color)+0.7152*Color.green(color)+0.0722*Color.blue(color), 256.0);
}
}
| Java |
package com.example.androideye;
import java.util.Locale;
import android.content.Context;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.widget.Toast;
/**
* Wrapper to the Text to Speech Android tool
* @author Alan Zanoni Peixinho
*
*/
public class Speaker implements OnInitListener{
private TextToSpeech tts;
Context c = null;
String fs = null;
/**
* Initialize text to speech
* @param context Activity Context.
*/
private void initialize(Context context){
c = context;
Log.v("Speaker", "Creating Text To Speech");
tts = new TextToSpeech(c, this);
Log.v("Speaker", "TTS variable: " + tts);
}
/**
* Initialize text to speech
* @param context Activity Context.
* @param firstSpeak String spoken after text to speech initialization.
*/
public Speaker(Context context, String firstSpeak)
{
fs = new String(firstSpeak);
initialize(context);
}
/**
* Initialize text to speech
* @param context context Activity Context.
*/
public Speaker(Context context)
{
initialize(context);
}
/**
* Count the number of words in a string.
* @param s String to be count.
* @return Return the number of words in the string.
*/
private int wordCount(String s){//fast words number estimate
int sz = s.length();
int count=1;
for (int i = 0; i < sz; i++) {
if(Character.isSpace(s.charAt(i)))
count++;
}
return count;
}
/**
* Speak a string.
* @param text String to be spoken.
*/
public void speak(String text)
{
Log.v("Speaker", "Saying: "+text);
int words = wordCount(text);
int time;
if(words>=5)
time = Toast.LENGTH_LONG;
else
time=Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(c, text, time);
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
toast.show();
}
@Override
public void onInit(int initStatus) {
// TODO Auto-generated method stub
Log.v("Speaker", "Initializing ...");
tts.setLanguage(Locale.US);
Log.v("Speaker", "It seems its working ...");
if(fs!=null)
speak(fs);
fs = null;//free to garbage collector
}
}
| Java |
package com.example.androideye;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
/**
* Get information of the phone contacts.
* @author Everton Fernandes da Silva
*
*/
public class ContactPicker {
ContentResolver resolver = null;
Cursor cursor = null;
private final int PICK_CONTACT = 1;
Intent intentContact = null;
int cont;
int maxSamples;
private BufferedReader r1;
private BufferedReader r2;
/**
* Creates an instance of ContactPicker.
* @param cr ContentResolver.
* @param maxSamples Maximum number of samples stored in database.
*/
public ContactPicker(ContentResolver cr, int maxSamples) {
// TODO Auto-generated constructor stub
resolver = cr;
this.maxSamples = Math.max(maxSamples, 1);
Log.v("ContactPicker", "Creating intent");
intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
Log.v("ContactPicker", "Getting uri");
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
Log.v("ContactPicker", "OK");
cont = 0;
//Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
//Cursor cursor = resolver.query(intent.getData(), null, null, null, null);
Log.v("cp", "Executing query ...");
cursor = resolver.query(uri, projection, selection, selectionArgs, sortOrder);
Log.v("cp", "OK");
}
/**
* Call the next contact.
* @return Return <code>false</code> if the contact list is over.
*/
public boolean nextContact(){
if(cont==0){
if(!cursor.moveToFirst()){
return false;
}
}
long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
loadContactPhoto(resolver,contactId);
File dir = new File(Globals.BASE_DIR, Long.toString(contactId));
File nameFile = new File(dir, "name.txt");
if(!nameFile.exists())
{
try {
nameFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(nameFile));
out.write(name);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.v("ContactPicker", name);
cont++;
return cursor.moveToNext();
}
/**
* Get the index of current contact.
* @return Return the index of the current contact.
*/
public int curContact(){
return cursor.getPosition();
}
/**
* Get the number of contacts.
* @return Return the number of contacts.
*/
public int contactsNumber(){
return cursor.getCount();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
getContacts(intent);
//getContactPhoto();
}
}
/**
* Load a contact photo and store in the database.
* @param cr
* @param id
*/
private void loadContactPhoto(ContentResolver cr, long id)
{
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input == null) {
return;
}
try {
File d = new File(Globals.BASE_DIR, Long.toString(id));
if (!d.exists()) {
d.mkdir();
}
long time = System.currentTimeMillis();
File f = new File(d, Long.toString(time)+".jpg");
if(!f.exists()){
f.createNewFile();
}
FileOutputStream fout = new FileOutputStream(f);
BitmapFactory.decodeStream(input).compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
//delete repeated files
File[] filelist = d.listFiles();
int count = filelist.length;
//remove duplicates
for (File file : filelist) {
if(!f.equals(file)){
if(equalContent(f, file))
file.delete();
count--;
}
}
filelist = d.listFiles();
count = filelist.length;
//if exceeds the sample limit it removes the oldest sample
if(count>maxSamples){
File oldest = null;
long timeoldest = System.currentTimeMillis();
for (File file : filelist) {
long t = file.lastModified();
if(t<timeoldest){
timeoldest = t;
oldest = file;
}
}
oldest.delete();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Compare if two files have the same content.
* @param f1 First file.
* @param f2 Second file.
* @return Return <code>true</code> if the files are equal.
*/
private boolean equalContent(File f1, File f2){
try {
r1 = new BufferedReader(new FileReader(f1) );
r2 = new BufferedReader(new FileReader(f2) );
String s1, s2;
for(;;){
s1 = r1.readLine();
s2 = r2.readLine();
if(!s1.equals(s2)){
return false;
}
if(s1==null || s2==null)
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
/**
* Get all contacts and store in the database.
* @param intent
*/
private void getContacts(Intent intent)
//public void getContactPhoto()
{
//Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
if (cursor.moveToFirst())
{
do
{
long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
loadContactPhoto(resolver,contactId);
Log.v("ContactPicker", name);
cont++;
}while(cursor.moveToNext());
}
Log.d("CONTADOR", ""+cont);
cursor.close();
}
}
| Java |
package com.example.androideye;
import java.io.File;
import android.os.Environment;
/**
* Store some global constants.
* @author Alan Zanoni Peixinho
*
*/
public class Globals {
public static final File APP_DIR = new File(Environment.getExternalStorageDirectory(), "AndroidEye");
public static final File BASE_DIR = new File(APP_DIR, "Database");
public class PersistentInfo
{
public static final String PREFERENCES_FILE = "AndroidEye.PersistentInfo";
public static final String HAS_STARTED = "HasStarted";
public static final String INSTALLED_EXTRA = "InstalledExtraData";
}
}
| Java |
package com.example.androideye;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
public class ExperimentRun extends Activity{
/** Called when the activity is first created. */
final static int VOICE_ACTION_REQUEST_CODE = 1;
EditText edit = null;
TextToSpeech tts;
Button btn;
Speaker speakerOut = null;
EditText scaleEditW = null;
EditText scaleEditH = null;
EditText topEdit = null;
EditText confEdit = null;
EditText datasetEdit = null;
RadioButton radioLBP = null;
RadioButton radioASM = null;
RadioButton radioPCA = null;
private Handler handler = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.experiment_main);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
edit = (EditText) findViewById(R.id.editText1);
scaleEditW = (EditText) findViewById(R.id.width);
scaleEditW.setText("1.0");
scaleEditH = (EditText) findViewById(R.id.height);
scaleEditH.setText("1.0");
topEdit = (EditText) findViewById(R.id.top);
confEdit = (EditText) findViewById(R.id.model);
datasetEdit = (EditText) findViewById(R.id.dataset);
radioLBP = (RadioButton) findViewById(R.id.radioLBP);
radioASM = (RadioButton) findViewById(R.id.radioASM);
radioPCA = (RadioButton) findViewById(R.id.radioPCA);
handler = new Handler();
speakerOut = new Speaker(ExperimentRun.this);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
@SuppressWarnings("deprecation")
public void run()
{
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
if (!Database.changeBaseDir(datasetEdit.getText().toString()) ){
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
edit.setText("Invalid Database");
}
});
return;
}
List<File> people = Database.listPeople();
LinkedList<File> train = new LinkedList<File>();
LinkedList<File> test = new LinkedList<File>();
LinkedList<String> trainId = new LinkedList<String>();
LinkedList<String> testId = new LinkedList<String>();
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
edit.setText("Listing images from "+Database.BASE_DIR+" ...\n");
}
});
for (File person : people) {
List<File> img = Database.listImages(person);
Pair<LinkedList<File>, LinkedList<File>> p = Database.split(img, 0.5);
for (File file : p.first) {
trainId.addLast(person.getName());
train.addLast(file);
//testId.addLast(person.getName());
//test.addLast(file);
}
for (File file : p.second) {
testId.addLast(person.getName());
test.addLast(file);
//trainId.addLast(person.getName());
//train.addLast(file);
}
}
//train set and test set createds
double scaleW = Double.parseDouble(scaleEditW.getText().toString());
double scaleH = Double.parseDouble(scaleEditH.getText().toString());
String confFileASM = "/mnt/sdcard/data/"+confEdit.getText().toString();
String confFilePCA = "/mnt/sdcard/AndroidEye/"+confEdit.getText().toString();
FaceDescriptor f = null;
if(radioASM.isChecked()){
f = new StasmLib(confFileASM);
}
else if(radioLBP.isChecked()){
f = new LocalBinaryPattern(null, scaleW, scaleH);
}
else if(radioPCA.isChecked()){
Log.v("experiment", "Its PCA Baby.");
f = new PrincipalComponentAnalysis(confFilePCA);
}
FaceDetect detector = null;
long t = System.currentTimeMillis();
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
edit.append("Training ...\n");
}
});
LinkedList<Double> classifyTime = new LinkedList<Double>();
LinkedList<Double> descTime = new LinkedList<Double>();
NearestNeighbor classifier = new NearestNeighbor(detector, f);
classifier._train(trainId, train);
Iterator<String> it = testId.iterator();
int top = Integer.parseInt(topEdit.getText().toString());
int []ncorrects = new int[top];
int []nmistakes = new int[top];
for (int j = 0; j < top; j++) {
ncorrects[j]=nmistakes[j]=0;
}
int curTest=1;
for (File file:test) {
Bitmap faceImage = FaceImage.loadImage(file);
Log.v("Main", "Current File: "+file.getName());
String s = it.next();
t = System.currentTimeMillis();
//Collection<String> founds = classifier._classify(faceImage);
Collection<String> founds = classifier.topClassify(faceImage, top);
t = System.currentTimeMillis() - t;
if(founds.size()>0){
classifyTime.add(((double)t)/1000);
descTime.add(f.timeElapsed());
}
Log.v("MyOUT", "classify time: "+((double)t)/1000);
final double time = (double)(t)/1000;
final double desctime = f.timeElapsed();
final String filename = file.getName();
final String strFounds = ""+founds;
final int cur = curTest;
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//speakerOut.speak();
StringBuffer s = new StringBuffer();
s.append("\n\nClassifying ");
s.append(filename);
s.append("\nCur = ");
s.append(cur);
s.append("\nPrev classification time: ");
s.append(time);
s.append("s\nPrev descriptor time: ");
s.append(desctime);
s.append("s\n");
s.append(strFounds);
edit.setText(s.toString());
; }
});
curTest++;
Log.v("Main", "Classifieds: "+founds.size());
int i=0;
int idx=top;
for (String string : founds) {
if(s.equals(string)){
idx=i;
break;
}
i++;
}
for (int j = 0; j < idx; j++) {
nmistakes[j]++;
}
for(int j=idx; j<top; j++){
ncorrects[j]++;
}
}
final int ntotal = ncorrects[0]+nmistakes[0];
//final int rank = classifier.rank;
final double classifyMean = MathUtils.mean(classifyTime);
final double classifyStdDev = MathUtils.stdDeviation(classifyTime, classifyMean);
final double classifyVar = MathUtils.variance(classifyTime, classifyMean);
final double descMean = MathUtils.mean(descTime);
final double descStdDev = MathUtils.stdDeviation(descTime, descMean);
final double descVar = MathUtils.variance(descTime, descMean);
for (int i = 0; i < top; i++) {
final double acc = ((double)ncorrects[i])/(ncorrects[i]+nmistakes[i]);
final int curTop = i+1;
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
edit.append(String.format("\nTop %d\nTotal Comparison = %d\nAccuracy = %f\nMean Time Classify = %f\nStdDev = %f\nVariance = %f\n\nMean Time Descriptor = %f\nStdDev = %f\nVariance = %f\n", curTop, ntotal, acc, classifyMean, classifyStdDev, classifyVar, descMean, descStdDev, descVar));
}
});
}
Log.v("Main", String.format("Corrects = %d Wrongs = %d", ncorrects[0], nmistakes[0]));
t = System.currentTimeMillis() - t;
Log.v("Main",""+(((double)t)/1000)+"s");
wl.release();
}
};
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
}
);
}
} | Java |
package com.example.androideye;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import junit.framework.Assert;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.Log;
/**
* Nearest Neighbor classifier to face recognition.
* @author Alan Zanoni Peixinho
*
*/
public class NearestNeighbor{
public static final String CLASSIFIER_FILE = new File(Database.BASE_DIR, "samples.dat").getAbsolutePath();
public static final String ID_FILE = new File(Database.BASE_DIR,"id.dat").getAbsolutePath();
FaceDescriptor descriptor;
FaceDetect detector;
int nFeatures;
File trainSet;
File trainId;
DataOutputStream fileout;
DataInputStream filein;
FileInputStream fis = null;
BufferedInputStream bis = null;
FileReader fr = null;
BufferedReader IDin;
BufferedWriter IDout;
String curId;
LinkedList<Double> cur;
LinkedList<Double> topDist;
LinkedList<String> topLabel;
private int consulteds = 0;
/**
* Creates a NearestNeighbor instance using the face detector and descriptor indicateds.
* @param det Face Detector to be used
* @param desc Face Descriptor to be used
*/
public NearestNeighbor(FaceDetect det, FaceDescriptor desc){
setDescriptor(desc);
setDetector(det);
initialize();
}
private void initialize() {
Locale.setDefault(Locale.US);//to read the double from text file
cur = new LinkedList<Double>();
trainSet = new File(CLASSIFIER_FILE);
trainId = new File(ID_FILE);
topDist = new LinkedList<Double>();
topLabel = new LinkedList<String>();
}
/**
*
* @return Check if the classifier is already trained.
*/
public boolean isTrained(){
return trainId.exists() && trainSet.exists();
}
/**
* Creates a NearestNeighbor instance using the default face detector ({@link SkinFaceDetector}) and descriptor ({@link LocalBinaryPattern}).
*/
public NearestNeighbor(){
setDescriptor(new LocalBinaryPattern());
setDetector(new SkinFaceDetector());
initialize();
}
/**
* Set the face descriptor
* @param d Face Descriptor
*/
private void setDescriptor(FaceDescriptor d)
{
descriptor = d;
}
/**
* Set the face detector
* @param d Face Detector
*/
private void setDetector(FaceDetect d){
detector = d;
}
/**
* Train the classifier using all images in the default database indicated in {@link Database#BASE_DIR}.
* @param ui Main Interface
*/
public void train(UserInterface ui){
trainSet.delete();//if exists, doesn't exist anymore
trainId.delete();
try {
trainSet.createNewFile();
trainId.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int i = 0;
Log.v("NN", "Listing people ...");
List<File> people = Database.listPeople();
Log.v("NN", "People number: "+people.size());
for (File person : people) {
Log.v("NN", "Adding "+person.getName());
List<File> imgs = Database.listImages(person);
for (File file : imgs) {
Log.v("NN", "Opening image "+file.getName());
Bitmap b = FaceImage.loadImage(file);
//ui.callSpeaker("Width: "+b.getWidth()+", Height: "+b.getHeight());
//b = FaceImage.resizeBitmap(b, 0.5, 0.5);
String s = person.getName();//directory name is the person ID
List<Rect> r = detector.findFaces(b);
if(r.size()==1)
{
ui.callSpeaker("Adding "+Database.personName(person.getName()));
b = FaceImage.cropFace(b, r.get(0));
Collection<Double> desc = descriptor.getDescriptor(b);
if(i==0){
setNumFeatures(desc.size());
}
if(desc!=null){
addSample(s, desc);
//ui.callSpeaker(String.format("%s added to classifier.", file.getName()));
Log.v("NN", String.format("%s added to classifier.", file.getName()));
i++;
}
else{
//ui.callSpeaker(String.format("%s had an error getting descriptor.", file.getName()));
Log.v("NN", String.format("%s had an error getting descriptor.", file.getName()));
}
}
else{
//ui.callSpeaker(String.format("%d faces detecteds", r.size()));
if(r.size()!=0)
Log.v("NN", String.format("%s contains %d faces, not added to classifier.", file.getName(),r.size()));
else
Log.v("NN", String.format("No faces found in %s, not added to classifier.", file.getName(),r.size()));
}
}
}
try {
fileout.close();
IDout.close();
//filein = new DataInputStream(new FileInputStream(trainSet));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @deprecated
* Train the classifier using the indicated files with cropped faces.
* @param id Label list corresponding the images list.
* @param imgs Images list to be used in the training step.
*/
//train the classifier with the dataset
public void _train(Collection<String> id, Collection<File> imgs){
assert(id.size()==imgs.size()):"The labels number and images number is different";
/*if(1==1)
return;
*/
trainSet.delete();//if exists, doesn't exist anymore
trainId.delete();
try {
trainSet.createNewFile();
trainId.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Iterator<String> it = id.iterator();
int i=0;
for (File file : imgs) {
Log.v("NN", "Current File: "+file.getName());
Bitmap b = FaceImage.loadImage(file);
String s = it.next();
Collection<Double> desc = descriptor.getDescriptor(b);
if(desc!=null){
if(i==0){
setNumFeatures(desc.size());
}
addSample(s, desc);
//Log.v("NN", "Desc = "+desc);
Log.v("NN", String.format("%s added to classifier.", file.getName()));
i++;
}
}
try {
fileout.close();
IDout.close();
//filein = new DataInputStream(new FileInputStream(trainSet));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Train the classifier using the indicated files.
* @param id Label list corresponding the images list.
* @param imgs Images list to be used in the training step.
*/
public void train(Collection<String> id, Collection<File> imgs){
assert(id.size()==imgs.size()):"The labels number and images number is different";
trainSet.delete();//if exists, doesn't exist anymore
trainId.delete();
try {
trainSet.createNewFile();
trainId.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Iterator<String> it = id.iterator();
int i=0;
for (File file : imgs) {
Bitmap b = FaceImage.loadImage(file);
//b = FaceImage.resizeBitmap(b, 0.5, 0.5);
String s = it.next();
List<Rect> r = detector.findFaces(b);
if(r.size()==1)
{
b = FaceImage.cropFace(b, r.get(0));
Collection<Double> desc = descriptor.getDescriptor(b);
if(i==0){
setNumFeatures(desc.size());
}
if(desc!=null){
addSample(s, desc);
Log.v("NN", String.format("%s added to classifier.", file.getName()));
i++;
}
else{
Log.v("NN", String.format("%s had an error getting descriptor.", file.getName()));
}
}
else{
if(r.size()!=0)
Log.v("NN", String.format("%s contains %d faces, not added to classifier.", file.getName(),r.size()));
else
Log.v("NN", String.format("No faces found in %s, not added to classifier.", file.getName(),r.size()));
}
}
try {
fileout.close();
IDout.close();
//filein = new DataInputStream(new FileInputStream(trainSet));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Store the number of descriptors in classifier file.
* */
private void setNumFeatures(int numFeatures){
nFeatures=numFeatures;
try {
fileout = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(trainSet), 2*1024));
IDout = new BufferedWriter(new FileWriter(trainId));
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileout.writeInt(numFeatures);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.v("Info", "Features Number Stored: "+nFeatures);
}
/**
* Get the number of descriptors in classifier file, and store in nFeatures var.
*/
private void getNumFeatures(){
try {
Log.v("NN", "File stream closing ...");
if(filein!=null){
filein.close();
IDin.close();
filein = null;
IDin = null;
}
Log.v("NN", String.format("File stream opening ...%s %s", trainSet.getName(), trainId.getName()));
if(fis!=null){
fis.close();
fis=null;
}
if(bis!=null){
bis.close();
bis=null;
}
if(fr!=null){
fr.close();
fr=null;
}
System.gc();
fis = new FileInputStream(trainSet);
bis = new BufferedInputStream(fis,2*1024);
filein = new DataInputStream(bis);//buffer-100k
fr = new FileReader(trainId);
IDin = new BufferedReader(fr, 2*1024);
Log.v("NN", "File stream opened");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int x = 0;
try {
x = filein.readInt();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nFeatures = x;
//Log.v("Info", "Features Number Loaded: "+nFeatures);
}
/**
* Store a sample in classifier file.
* @param sampleLabel Sample label
* @param sampleDescriptor Sample descriptor
*/
private void addSample(String sampleLabel, Collection<Double> sampleDescriptor)
{
try{
IDout.write(sampleLabel+'\n');
Assert.assertTrue(sampleDescriptor.size()==nFeatures);
for (double d: sampleDescriptor) {
fileout.writeFloat((float)d);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Get the sample in classifier file, stores the label in curId var and the descriptor in cur var.
* @return Return <code>false</code> if the end of file is reached.
*/
private boolean getSample(){
cur.clear();
String s;
try{
s = IDin.readLine();
if (s==null) {
return false;
}
curId = s;
for (int i = 0; i < nFeatures; i++) {
double d = (double)filein.readFloat();
cur.addLast(d);
}
}
catch(Exception e){}
return true;
}
/**
* Get the closest sample label to the indicated sample
* @param c Sample Descriptor
* @return Returns the label of the closest sample in training database.
*/
private String closest(Collection<Double> c){
String minId = null;
double minDist = Double.MAX_VALUE;
//Log.v("NN", "Comparing to database");
int i=0;
getNumFeatures();
while(getSample()){
//Log.v("NN", "Comparing "+i);
i++;
//double dist = chiSquareDistance(c, cur);
double dist = descriptor.distance(c, cur);
//Log.v("NN", String.format("Comparing with %s - dist = %f", curId, dist));
if (dist<minDist) {
minDist=dist;
minId=new String(curId);
}
}
//Log.v("NN", String.format("Closest label %s.", minId));
/*try {
filein.close();
IDin.close();
} catch (IOException e) {
e.printStackTrace();
}*/
return minId;
}
public Collection<Double> getBestDistances(){
LinkedList<Double> list = new LinkedList<Double>();
for (Double d : topDist) {
list.addLast(d);
}
return list;
}
/**
* Get a list of closest sample labels to the indicated sample.
* @param c Sample Descriptor
* @param topsize Number of closest samples to be returned.
* @return Returns a list of the closest sample labels.
*/
private Collection<String> topClosest(Collection<Double> c, int topsize){
//Log.v("NN", "Comparing to database");
topDist.clear();
topLabel.clear();
for (int i = 0; i < topsize; i++) {
topDist.add(Double.MAX_VALUE);
topLabel.add(null);
}
int i=0;
getNumFeatures();
while(getSample()){
//Log.v("NN", "Comparing "+i);
i++;
//double dist = chiSquareDistance(c, cur);
double dist = descriptor.distance(c, cur);
//Log.v("NN", String.format("Comparing with %s - dist = %f", curId, dist));
Iterator<String> itLabel = topLabel.iterator();
Iterator<Double> itDist = topDist.iterator();
for (int j = 0; j < topsize; j++) {
String s = itLabel.next();
double d = itDist.next();
//Log.v("NN", "Cur: " + curId + " -> " +cur);
if (dist<d) {
//Log.v("NN", "dist = "+dist + " label: "+curId);
topDist.add(j, dist);
topLabel.add(j, new String(curId));
topDist.removeLast();
topLabel.removeLast();
break;
}
}
}
Log.v("NN", "Best labels = " + topLabel);
Log.v("NN", "Best distances = " + topDist);
consulteds = i;
return topLabel;
}
/**
* Number of images consulteds in the database.
* @return Number of images consulteds in the database.
*/
public int consultedInDatabase(){
return consulteds;
}
/**
* Classify a image without face detection.
* @deprecated
* @param image Image used in face recognition.
* @return Return the labels of each face found.
*/
public Collection<String> _classify(Bitmap image){
Log.v("NN","Classifying ...");
//image = FaceImage.resizeBitmap(image, 0.5, 0.5);//down resolution to improve the face detection time
//List<Rect> rects = detector.findFaces(image);
LinkedList<String> labels = new LinkedList<String>();
//Log.v("NN", String.format("%d faces detecteds.", rects.size()));
Collection<Double> desc = descriptor.getDescriptor(image);
if(desc!=null){
String label = closest(desc);
if(label!=null)
labels.addLast(label);
}
return labels;
}
/**
* Perform face recognition in each face found.
* @param image Image used in face recognition.
* @return Return the labels of each face found.
*/
public Collection<String> classify(Bitmap image){
Log.v("NN","Classifying ...");
//image = FaceImage.resizeBitmap(image, 0.5, 0.5);//down resolution to improve the face detection time
List<Rect> rects = detector.findFaces(image);
LinkedList<String> labels = new LinkedList<String>();
Log.v("NN", String.format("%d faces detecteds.", rects.size()));
for (Rect rect : rects) {
Bitmap b = FaceImage.cropFace(image, rect);
Collection<Double> desc = descriptor.getDescriptor(b);
String label = closest(desc);
labels.addLast(label);
}
return labels;
}
/**
* Perform face recognition in an image returning the <i>topsize</i> closest labels.
* @param img Image used in face recognition
* @param topsize Number of labels returned.
* @return Return the <i>topsize</i> closest labels.
*/
public Collection<String> topClassify(Bitmap img, int topsize){
Log.v("NN","Classifying ...");
//image = FaceImage.resizeBitmap(image, 0.5, 0.5);//down resolution to improve the face detection time
//List<Rect> rects = detector.findFaces(image);
//Log.v("NN", String.format("%d faces detecteds.", rects.size()));
Collection<String> labels = null;
Log.v("NN", "Descriptor");
Collection<Double> desc = descriptor.getDescriptor(img);
if(desc!=null){
Log.v("NN", "Searching closest ...");
labels = topClosest(desc, topsize);
Log.v("NN", String.format("%d Closest founds ...", labels.size()));
}
else{
//Log.v("NN", String.format("labels = %p", labels));
return new LinkedList<String>();//empty list
}
Log.v("NN", "");
return labels;
}
}
| Java |
package com.example.androideye;
import android.os.Bundle;
/**
* Interface for speech recognition callbacks.
*
* Essentially a cut-down version of {@link android.speech.RecognitionListener},
* to avoid dependencies on Froyo and methods we don't need or can't provide.
*
* @author David Huggins-Daines <dhuggins@cs.cmu.edu>
*
*/
public interface RecognitionListener {
/**
* Called on the recognition thread when partial results are available.
*
* Note: This is not like android.speech.RecognitionListener in that it does
* not get called on the main thread.
*
* @param b
* Bundle containing the partial result string under the "hyp"
* key.
*/
abstract void onPartialResults(Bundle b);
/**
* Called when final results are available.
*
* Note: This is not like android.speech.RecognitionListener in that it does
* not get called on the main thread.
*
* @param b
* Bundle containing the final result string under the "hyp" key.
*/
abstract void onResults(Bundle b);
/**
* Called if a recognition error occurred.
*
* Note: This will only ever be passed -1 for the moment, which corresponds
* to a recognition failure (null result).
*
* @param err
* Code representing the error that occurred.
*/
abstract void onError(int err);
}
| Java |
package com.example.androideye;
import java.io.File;
import java.util.concurrent.LinkedBlockingQueue;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import edu.cmu.pocketsphinx.Config;
import edu.cmu.pocketsphinx.Decoder;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.pocketsphinx;
/**
* Speech recognition task, which runs in a worker thread.
*
* This class implements speech recognition for this demo application. It takes
* the form of a long-running task which accepts requests to start and stop
* listening, and emits recognition results to a listener.
*
* @author David Huggins-Daines <dhuggins@cs.cmu.edu>
*/
public class RecognizerTask implements Runnable {
static {
System.loadLibrary("pocketsphinx_jni");
}
public static final String REC_DIR = new File(UserInterface.APP_DIR, "edu.cmu.pocketsphinx").getAbsolutePath();
/**
* Audio recording task.
*
* This class implements a task which pulls blocks of audio from the system
* audio input and places them on a queue.
*
* @author David Huggins-Daines <dhuggins@cs.cmu.edu>
*/
class AudioTask implements Runnable {
/**
* Queue on which audio blocks are placed.
*/
LinkedBlockingQueue<short[]> q;
AudioRecord rec;
int block_size;
boolean done;
static final int DEFAULT_BLOCK_SIZE = 512;
AudioTask() {
this.init(new LinkedBlockingQueue<short[]>(), DEFAULT_BLOCK_SIZE);
}
AudioTask(LinkedBlockingQueue<short[]> q) {
this.init(q, DEFAULT_BLOCK_SIZE);
}
AudioTask(LinkedBlockingQueue<short[]> q, int block_size) {
this.init(q, block_size);
}
void init(LinkedBlockingQueue<short[]> q, int block_size) {
this.done = false;
this.q = q;
this.block_size = block_size;
this.rec = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, 8192);
}
public int getBlockSize() {
return block_size;
}
public void setBlockSize(int block_size) {
this.block_size = block_size;
}
public LinkedBlockingQueue<short[]> getQueue() {
return q;
}
public void stop() {
this.done = true;
}
public void run() {
this.rec.startRecording();
while (!this.done) {
int nshorts = this.readBlock();
if (nshorts <= 0)
break;
}
this.rec.stop();
this.rec.release();
}
int readBlock() {
short[] buf = new short[this.block_size];
int nshorts = this.rec.read(buf, 0, buf.length);
if (nshorts > 0) {
Log.d(getClass().getName(), "Posting " + nshorts + " samples to queue");
this.q.add(buf);
}
return nshorts;
}
}
/**
* PocketSphinx native decoder object.
*/
Decoder ps;
/**
* Audio recording task.
*/
AudioTask audio;
/**
* Thread associated with recording task.
*/
Thread audio_thread;
/**
* Queue of audio buffers.
*/
LinkedBlockingQueue<short[]> audioq;
/**
* Listener for recognition results.
*/
RecognitionListener rl;
/**
* Whether to report partial results.
*/
boolean use_partials;
/**
* State of the main loop.
*/
enum State {
IDLE, LISTENING
};
/**
* Events for main loop.
*/
enum Event {
NONE, START, STOP, SHUTDOWN
};
/**
* Current event.
*/
Event mailbox;
public RecognitionListener getRecognitionListener() {
return rl;
}
public void setRecognitionListener(RecognitionListener rl) {
this.rl = rl;
}
public void setUsePartials(boolean use_partials) {
this.use_partials = use_partials;
}
public boolean getUsePartials() {
return this.use_partials;
}
public RecognizerTask() {
File log = new File(REC_DIR, "pocketsphinx.log");
log.delete();
pocketsphinx
.setLogfile(log.getAbsolutePath());
Config c = new Config();
/*
* In 2.2 and above we can use getExternalFilesDir() or whatever it's
* called
*/
//c.setString("-dither", "yes");
c.setString("-hmm",
new File(REC_DIR, "hmm/en_US/hub4wsj_sc_8k").getAbsolutePath());
c.setString("-dict",
// "/mnt/sdcard/edu.cmu.pocketsphinx/lm/en_US/hub4.5000.dic");
new File(REC_DIR, "lm/en_US/4762.dic").getAbsolutePath());
c.setString("-lm",
//"/mnt/sdcard/edu.cmu.pocketsphinx/lm/en_US/hub4.5000.DMP");
new File(REC_DIR, "lm/en_US/4762.dmp").getAbsolutePath());
/*
c.setString("-hmm",
"/sdcard/Android/data/edu.cmu.pocketsphinx/hmm/zh/tdt_sc_8k");
c.setString("-dict",
"/sdcard/Android/data/edu.cmu.pocketsphinx/lm/zh_TW/mandarin_notone.dic");
c.setString("-lm",
"/sdcard/Android/data/edu.cmu.pocketsphinx/lm/zh_TW/gigatdt.5000.DMP");
*/
c.setString("-rawlogdir", REC_DIR);
c.setFloat("-samprate", 8000.0);
c.setInt("-maxhmmpf", 2000);
c.setInt("-maxwpf", 10);
c.setInt("-pl_window", 2);
c.setBoolean("-backtrace", true);
c.setBoolean("-bestpath", false);
this.ps = new Decoder(c);
this.audio = null;
this.audioq = new LinkedBlockingQueue<short[]>();
this.use_partials = false;
this.mailbox = Event.NONE;
}
public void run() {
/* Main loop for this thread. */
boolean done = false;
/* State of the main loop. */
State state = State.IDLE;
/* Previous partial hypothesis. */
String partial_hyp = null;
while (!done) {
/* Read the mail. */
Event todo = Event.NONE;
synchronized (this.mailbox) {
todo = this.mailbox;
/* If we're idle then wait for something to happen. */
if (state == State.IDLE && todo == Event.NONE) {
try {
Log.d(getClass().getName(), "waiting");
this.mailbox.wait();
todo = this.mailbox;
Log.d(getClass().getName(), "got" + todo);
} catch (InterruptedException e) {
/* Quit main loop. */
Log.e(getClass().getName(), "Interrupted waiting for mailbox, shutting down");
todo = Event.SHUTDOWN;
}
}
/* Reset the mailbox before releasing, to avoid race condition. */
this.mailbox = Event.NONE;
}
/* Do whatever the mail says to do. */
switch (todo) {
case NONE:
if (state == State.IDLE)
Log.e(getClass().getName(), "Received NONE in mailbox when IDLE, threading error?");
break;
case START:
if (state == State.IDLE) {
Log.d(getClass().getName(), "START");
this.audio = new AudioTask(this.audioq, 1024);
this.audio_thread = new Thread(this.audio);
this.ps.startUtt();
this.audio_thread.start();
state = State.LISTENING;
}
else
Log.e(getClass().getName(), "Received START in mailbox when LISTENING");
break;
case STOP:
if (state == State.IDLE)
Log.e(getClass().getName(), "Received STOP in mailbox when IDLE");
else {
Log.d(getClass().getName(), "STOP");
assert this.audio != null;
this.audio.stop();
try {
this.audio_thread.join();
}
catch (InterruptedException e) {
Log.e(getClass().getName(), "Interrupted waiting for audio thread, shutting down");
done = true;
}
/* Drain the audio queue. */
short[] buf;
while ((buf = this.audioq.poll()) != null) {
Log.d(getClass().getName(), "Reading " + buf.length + " samples from queue");
this.ps.processRaw(buf, buf.length, false, false);
}
this.ps.endUtt();
this.audio = null;
this.audio_thread = null;
Hypothesis hyp = this.ps.getHyp();
if (this.rl != null) {
if (hyp == null) {
Log.d(getClass().getName(), "Recognition failure");
this.rl.onError(-1);
}
else {
Bundle b = new Bundle();
Log.d(getClass().getName(), "Final hypothesis: " + hyp.getHypstr());
b.putString("hyp", hyp.getHypstr());
this.rl.onResults(b);
}
}
state = State.IDLE;
}
break;
case SHUTDOWN:
Log.d(getClass().getName(), "SHUTDOWN");
if (this.audio != null) {
this.audio.stop();
assert this.audio_thread != null;
try {
this.audio_thread.join();
}
catch (InterruptedException e) {
/* We don't care! */
}
}
this.ps.endUtt();
this.audio = null;
this.audio_thread = null;
state = State.IDLE;
done = true;
break;
}
/* Do whatever's appropriate for the current state. Actually this just means processing audio if possible. */
if (state == State.LISTENING) {
assert this.audio != null;
try {
short[] buf = this.audioq.take();
Log.d(getClass().getName(), "Reading " + buf.length + " samples from queue");
this.ps.processRaw(buf, buf.length, false, false);
Hypothesis hyp = this.ps.getHyp();
if (hyp != null) {
String hypstr = hyp.getHypstr();
if (hypstr != partial_hyp) {
Log.d(getClass().getName(), "Hypothesis: " + hyp.getHypstr());
if (this.rl != null && hyp != null) {
Bundle b = new Bundle();
b.putString("hyp", hyp.getHypstr());
this.rl.onPartialResults(b);
}
}
partial_hyp = hypstr;
}
} catch (InterruptedException e) {
Log.d(getClass().getName(), "Interrupted in audioq.take");
}
}
}
}
public void start() {
Log.d(getClass().getName(), "signalling START");
File dir = new File(REC_DIR);
for (File file : dir.listFiles()){
if(file.getName().contains("raw")){
file.delete();
}
}
synchronized (this.mailbox) {
this.mailbox.notifyAll();
Log.d(getClass().getName(), "signalled START");
this.mailbox = Event.START;
}
}
public void stop() {
Log.d(getClass().getName(), "signalling STOP");
synchronized (this.mailbox) {
this.mailbox.notifyAll();
Log.d(getClass().getName(), "signalled STOP");
this.mailbox = Event.STOP;
}
}
public void shutdown() {
Log.d(getClass().getName(), "signalling SHUTDOWN");
synchronized (this.mailbox) {
this.mailbox.notifyAll();
Log.d(getClass().getName(), "signalled SHUTDOWN");
this.mailbox = Event.SHUTDOWN;
}
}
} | Java |
package com.example.androideye;
import java.util.LinkedList;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.Log;
/**
*
* @author Everton Fernandes da Silva
* @author Alan Zanoni Peixinho
*
*/
public class SkinFaceDetector implements FaceDetect {
public static final int NUMBER_OF_FACES = 4;
FaceDetector.Face myFace[];
FaceDetector myFaceDetect;
LinkedList<Rect> faces;
PointF p;
long time;
int width, height;
/**
* Creates an instance of {@link SkinFaceDetector}.
*/
public SkinFaceDetector(){
width = 640;
height = 480;
myFace = new FaceDetector.Face [NUMBER_OF_FACES];//acha ateh 4 faces numa imagem
myFaceDetect = new FaceDetector(width, height, NUMBER_OF_FACES);
faces = new LinkedList<Rect>();
p = new PointF();
time = 0;
}
/**
* The Android face detector returns a {@link Face} object, this function converts it to a rectangle.
* @param f Android Face parameter.
* @param imgwidth Image width.
* @param imgheight Image height.
* @return Return the rectangle that contains the face
*/
private Rect face2Rect(Face f, int imgwidth, int imgheight)
{
f.getMidPoint(p);
double eyesDistance = f.eyesDistance();
int x, y, width, height;
x = (int)(Math.floor(p.x-(1.0*eyesDistance)));
y = (int)(Math.floor(p.y-(1.0*eyesDistance)));
width = (int)Math.ceil(2.0*eyesDistance);
height = (int)Math.ceil(3.0f*eyesDistance);
//verifica se o retangulo da face nao estah definido fora da imagem
if(x < 0)
x = 0;
if(y < 0)
y = 0;
if((y + height) > imgheight)
height = (int)(imgheight - y);
if((x + width) > imgwidth)
width = (int)(imgwidth - x);
Rect r = new Rect();
r.set(x, y, x+width, y+height);
return r;
}
@Override
public List<Rect> findFaces(Bitmap img) {
if(img.getWidth()!=width || img.getHeight()!=height)
{
width = img.getWidth();
height = img.getHeight();
Log.v("SkinFaceDetector", String.format("Changing face detector resolution to %dx%d", width, height));
myFaceDetect = new FaceDetector(width, height, NUMBER_OF_FACES);
}
faces.clear();
time = System.currentTimeMillis();
int n = myFaceDetect.findFaces(img, myFace);
time = System.currentTimeMillis() - time;
for (int i = 0; i < n; i++) {
Rect r = face2Rect(myFace[i], img.getWidth(), img.getHeight());
faces.add(r);
}
return faces;
}
@Override
public double timeElapsed() {
// TODO Auto-generated method stub
return ((double)time)/1000;
}
@Override
public int normalSize() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Bitmap normalizeSize(Bitmap b) {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package com.example.androideye;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import android.graphics.Bitmap;
import android.util.Log;
/**
* Local Binary Pattern descriptor.
* @author Alan Zanoni Peixinho.
*
*/
public class LocalBinaryPattern implements FaceDescriptor{
public static final int WIDTH = 75;
public static final int HEIGHT = 150;
double windowW, windowH;
long time;
double feats[];
int pixels[];
/**
* Initialize some variables.
* @param windowW Window width.
* @param windowH Window height.
*/
private void initialize(double windowW, double windowH)
{
Log.v("LBP", "Initializing Local Binary Pattern Face Descriptor");
this.windowW = windowW;
this.windowH = windowH;
time = 0;
feats = new double[256];
pixels = null;
}
/**
* Creates an instance of {@link LocalBinaryPattern} without windows.
*/
public LocalBinaryPattern()
{
initialize(1.0, 1.0);
}
/**
* Creates an instance of {@link LocalBinaryPattern} with windows.
* @param detect Face detector used.
* @param windowPercentage Windows size percentage used in descriptor.
*/
public LocalBinaryPattern(FaceDetect detect, double windowPercentage) {
initialize(windowPercentage, windowPercentage);
}
/**
* Creates an instance of {@link LocalBinaryPattern} with windows.
* @param detect Face detector used.
* @param windowW Window width.
* @param windowH Window height.
*/
public LocalBinaryPattern(FaceDetect detect, double windowW, double windowH) {
initialize(windowW, windowH);
}
/**
* Creates an instance of {@link LocalBinaryPattern} with windows.
* @param detect Face detector used.
*/
public LocalBinaryPattern(FaceDetect detect) {
// TODO Auto-generated constructor stub
initialize(1.0, 1.0);//a janela possui o tamanho da imagem
}
/**
* Get the (x,y) pixel in the image array.
* @param pixels Image array.
* @param x Pixel line.
* @param y Pixel Column.
* @param width Image width.
* @return Return the pixel value at (x,y).
*/
private int getPixel(int pixels[], int x, int y, int width)
{
return pixels[y*width+x];
}
/**
* Extract Local Binary Pattern histogram in the image.
* @param img Image to be used.
* @return Return the Local Binary Pattern Histogram.
*/
private Collection<Double> lbp(Bitmap img){
for(int i=0; i<feats.length; ++i)
feats[i] = 0.0;
if(pixels==null || pixels.length<(img.getHeight()*img.getWidth()))
{
pixels = new int[img.getWidth()*img.getHeight()];
}
int width = img.getWidth();
int height = img.getHeight();
long t = System.currentTimeMillis();
img.getPixels(pixels, 0, width, 0, 0, width, height);
t = System.currentTimeMillis() - t;
Log.v("getdata", ""+(double)(t)/1000.0);
for (int i = 0; i < pixels.length; i++) {
pixels[i] = (int) FaceImage.rgb2gray(pixels[i]);
//Log.v("LBP", "pixel["+i+"] = " + pixels[i]);
}
for(int i=1; i<width-1; ++i)
{
for (int j = 1; j < height-1 ; ++j) {
int output = 0;
int cur = getPixel(pixels, i, j, width);
if (getPixel(pixels, i-1, j-1, width)>=cur) {
output = 1;
}
else
{
output = 0;
}
if (getPixel(pixels, i, j-1, width)>=cur) {
output = (output << 1) + 1;
}
else
{
output = (output << 1) + 0;
}
if (getPixel(pixels, i+1, j-1, width)>=cur) {
output = (output << 1) + 1;
}
else
{
output = (output << 1) + 0;
}
if (getPixel(pixels, i+1, j, width)>=cur) {
output = (output << 1) + 1;
}
else
{
output = (output << 1) + 0;
}
if (getPixel(pixels, i+1, j+1, width)>=cur) {
output = (output << 1) + 1;
}
else
{
output = (output << 1) + 0;
}
if (getPixel(pixels, i, j+1, width)>=cur) {
output = (output << 1) + 1;
}
else
{
output = (output << 1) + 0;
}
if (getPixel(pixels, i-1, j+1, width)>=cur) {
output = (output << 1) + 1;
}
else
{
output = (output << 1) + 0;
}
if (getPixel(pixels, i-1, j, width)>=cur) {
output = (output << 1) + 1;
}
else
{
output = (output << 1) + 0;
}
feats[output]++;
}
}
double sum = 0.0;
for (int k = 0; k < feats.length; k++) {
sum+=feats[k];
}
//normalize array to work with images in different sizes
for (int k = 0; k < feats.length; k++) {
feats[k]/=sum;
}
LinkedList<Double> list = new LinkedList<Double>();
for (int i = 0; i < feats.length; i++) {
list.addLast(feats[i]);
}
return list;
}
public Collection<Double> getDescriptor(Bitmap img) {
// TODO Auto-generated method stub
Bitmap resImg = FaceImage.resizeBitmap(img, (double)WIDTH/img.getWidth());
if(windowW==1.0 && windowH==1.0)//if the window size is 1.0 is not necessary allocate new Bitmaps
{
Log.v("LBP", "Run Local Binary Pattern without window");
time = System.currentTimeMillis();
Collection<Double> it = lbp(resImg);
time = System.currentTimeMillis() - time;
return it;
}
time = System.currentTimeMillis();
int wInc = (int)(resImg.getWidth()*windowW);
int hInc = (int)(resImg.getHeight()*windowH);
Log.v("LBP", String.format("Run Local Binary Pattern with windowSize (%d, %d)",wInc, hInc));
LinkedList<Double> features = new LinkedList<Double>();
for (int i = 0; i+wInc <= resImg.getWidth(); i+=wInc) {
for (int j = 0; j+hInc <= resImg.getHeight(); j+=hInc) {
//long t = System.currentTimeMillis();
Bitmap subImg = Bitmap.createBitmap(resImg, i, j, wInc, hInc);
//t = System.currentTimeMillis() - t;
//Log.v("Subimage", ""+(double)(t)/1000.0);
Iterable<Double> it = lbp(subImg);
subImg.recycle();
for (Double double1 : it) {
features.addLast(double1);
}
}
}
time = System.currentTimeMillis() - time;
resImg.recycle();
return features;
}
public double timeElapsed() {
// TODO Auto-generated method stub
return ((double)time)/1000;
}
public double distance(Collection<Double> c1, Collection<Double> c2) {
// TODO Auto-generated method stub
return MathUtils.chiSquareDistance(c1, c2);
}
}
| Java |
package com.example.androideye;
import java.util.Collection;
import java.util.LinkedList;
import android.graphics.Bitmap;
import android.util.Log;
/**
* Active Shape Model face descriptor, uses the Stasm library
*
* @author Alan Zanoni Peixinho
*
*/
public class StasmLib implements FaceDescriptor{
private final String TEMP_FILE = "/mnt/sdcard/alan.bmp";//Database.BASE_DIR+"temp.bmp";
String confFile = null;
private long time;
static{
System.loadLibrary("stasm");
}
public static native int add(int x);
public static native int[] hello(String s);
public static native double[] getFeatures(String fileName, String confFile);
public static native double[] getPoints(int[] img, int width, int height);
/**
* Creates an instance of {@link StasmLib} using the default stasm config file.
*/
public StasmLib() {
// TODO Auto-generated constructor stub
confFile = "/mnt/sdcard/data/mu-68-1d.conf";
}
/**
* Creates an instance of {@link StasmLib} using the indicated stasm config file.
* @param confFile Stasm config file
*/
public StasmLib(String confFile){
this.confFile = new String(confFile);
}
public Collection<Double> getDescriptor(Bitmap img) {
int width = img.getWidth();
int height = img.getHeight();
int pixels[] = new int[width*height];
img.getPixels(pixels, 0, width, 0, 0, width, height);
Log.v("Stasm", "Saving ...");
OpenCV.save(pixels, width, height, TEMP_FILE);
time = System.currentTimeMillis();
Log.v("Stasm", "Searching ...");
double f[] = getFeatures(TEMP_FILE, confFile);
if(f==null)
return null;
Log.v("Stasm", "Maping in Collection ...");
LinkedList<Double> feats = new LinkedList<Double>();
for (double d : f) {
feats.addLast(d);
}
Log.v("Stasm", "Feats Size = "+feats.size());
//Log.v("Stasm", ""+feats);
//Log.v("Stasm", "Deleting temp file ...");
//File file = new File(TEMP_FILE);
//file.delete();
time = System.currentTimeMillis() - time;
Log.v("STASM", "Time spent: "+((double)time)/1000.0);
f = null;
System.gc();
return feats;
}
@Override
public double timeElapsed() {
// TODO Auto-generated method stub
return (double)(time)/1000;
}
@Override
public double distance(Collection<Double> c1, Collection<Double> c2) {
// TODO Auto-generated method stub
return MathUtils.euclideanDistance(c1, c2);
}
}
| Java |
package com.example.androideye;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import android.util.Log;
import android.util.Pair;
/**
* Manipulate the Android Eye database.
* @author Alan Zanoni Peixinho
*
*/
public class Database {
/*
/mnt/sdcard/AndroidEye/Database
* */
public static String BASE_DIR = Globals.BASE_DIR.getAbsolutePath();
static{
File d = new File(BASE_DIR);
if(!d.exists()){
d.mkdirs();
}
}
/**
* List the people present in the database.
* @return Return a list with the people present in database.
*/
public static List<File> listPeople()
{
File dirlist= new File(BASE_DIR);
Log.v("Database", dirlist.getName());
File l[]=dirlist.listFiles();
LinkedList<File> people = new LinkedList<File>();
for (File file : l) {
if(file.isDirectory()){
people.addLast(file);
}
}
return people;
}
static boolean changeBaseDir(String baseDir){
return changeBaseDir(new File(baseDir));
}
/**
* Change the database used in AndroidEye
* @param baseDir The new database directory
* @return
* @return True in success case, or false if the directory doesn't exist
*/
static boolean changeBaseDir(File baseDir){
if(baseDir.isDirectory()){
BASE_DIR = baseDir.getAbsolutePath();
return true;
}
else{
return false;
}
}
/**
* Split a list of images. Used to generate experiments database.
* @param img List of images.
* @param perc1 [0.0,1.0] The first list has perc1 of the images. The second list has (1-perc1) of the images.
* @return Return a pair containing the two lists.
*/
public static Pair<LinkedList<File>, LinkedList<File> > split(List<File> img, double perc1){
LinkedList<File> tempList = new LinkedList<File>(img);
Collections.shuffle(tempList);
LinkedList<File> set1 = new LinkedList<File>();
LinkedList<File> set2 = new LinkedList<File>();
int sz = img.size();
int i;
for (i = 0; i < sz*perc1; i++) {
File f = tempList.removeFirst();
set1.addLast(f);
}
for (; i< sz; i++) {
File f = tempList.removeFirst();
set2.addLast(f);
}
return new Pair<LinkedList<File>, LinkedList<File>>(set1, set2);
}
/**
* Clear the database.
*/
public void clear(){
File dir = new File(BASE_DIR);
File list[] = dir.listFiles();
for (File file : list) {
file.delete();
}
}
/**
* List all images of a person.
* @param personId ID (label) of person.
* @return Return a list with all images of <i>personId</i>.
*/
public static List<File> listImages(String personId)
{
File dir = new File(BASE_DIR, personId);
return listImages(dir);
}
/**
* List all images of a person.
* @param personId ID (label) of person.
* @return Return a list with all images of <i>personId</i>.
*/
public static List<File> listImages(File personDir)
{
LinkedList<File> img = new LinkedList<File>();
File l2[]=personDir.listFiles();
for (File file2 : l2) {
if(file2.getName().endsWith(".jpg") ){
img.addLast(file2);
}
}
return img;
}
/**
* Get the name of a person.
* @param personDir personId ID (label) of person.
* @return Return the real name of <i>personId</i>
*/
public static String personName(File personDir){
String s = null;
File f = new File(personDir, "name.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(f));
s = br.readLine();
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
s = null;
}
return s;
}
/**
* Get the name of a person.
* @param personDir personId ID (label) of person.
* @return Return the real name of <i>personId</i>
*/
public static String personName(String personId){
File dir = new File(BASE_DIR, personId);
return personName(dir);
}
}
| Java |
package com.example.androideye;
import java.util.LinkedList;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.Rect;
public class ViolaJonesFaceDetector implements FaceDetect {
LinkedList<Rect> faces;
long time;
public ViolaJonesFaceDetector()
{
OpenCV.initFaceDetection("/mnt/sdcard/haarcascade_frontalface_alt.xml");
faces = new LinkedList<Rect>();
time = 0;
}
@Override
public List<Rect> findFaces(Bitmap img) {
int width, height;
faces.clear();
width = img.getWidth();
height = img.getHeight();
int img_data[] = new int[width*height];
img.getPixels(img_data, 0, width, 0, 0, width, height);
OpenCV.setSourceImage(img_data, width, height);
time = System.currentTimeMillis();
Rect[] r = OpenCV.findAllFaces();
time = System.currentTimeMillis() - time;
if(r!=null){
for (int i = 0; i < r.length; i++) {
faces.add(r[i]);
}
}
// TODO Auto-generated method stub
return faces;
}
public int normalSize()
{
return 30*30;
}
public Bitmap normalizeSize(Bitmap b)
{
return FaceImage.resizeBitmap(b, 30, 30);
}
@Override
public double timeElapsed() {
// TODO Auto-generated method stub
return ((double)time)/1000;
}
}
| Java |
package com.example.androideye;
import java.util.Collection;
import java.util.Iterator;
/**
* Some math utilities.
* @author Alan Zanoni Peixinho
*
*/
public class MathUtils {
/**
* Compute the Chi-Square distance between samples.
* @param i1 First sample.
* @param i2 Second sample.
* @return Return the Chi-Square sample between samples.
*/
//chi-square distance between samples
public static double chiSquareDistance(Collection<Double> i1, Collection<Double> i2){
double dist = 0.0;
double diff;
double v1, v2;
double sum;
assert(i1.size()==i2.size()):"Dimensions must agree.";
Iterator<Double> it1 = i1.iterator();
Iterator<Double> it2 = i2.iterator();
//Log.v("Info", String.format("Features Number - distance function: %d %d", i1.size(), i2.size()));
int nFeatures = i1.size();
for (int i = 0; i < nFeatures; i++)
{
v1 = it1.next();
v2 = it2.next();
diff = v1 - v2;
sum = v1 + v2;
//Log.v("Chi Square", String.format("%f, %f", v1, v2));
if(sum>0.0)
dist += (diff*diff)/sum;
}//while
return 0.5*dist;
}
/**
* Compute the Euclidean distance between samples.
* @param i1 First sample.
* @param i2 Second Sample.
* @return Return the Euclidean distance between samples.
*/
public static double euclideanDistance(Collection<Double> i1, Collection<Double> i2){
double dist = 0.0;
double value;
assert(i1.size()==i2.size()):"Dimensions must agree.";
Iterator<Double> it1 = i1.iterator();
Iterator<Double> it2 = i2.iterator();
while(it1.hasNext() && it2.hasNext())
{
value = it1.next() - it2.next();
dist += value*value;
}//while
return Math.sqrt(dist);
}
/**
* Computes the set mean.
* @param c Values set.
* @return Return the average value of the set.
*/
public static double mean(Collection<Double> c)
{
double sum = 0.0;
for (Double t : c) {
sum+= t;
}
return sum/c.size();
}
/**
* Computes the standard deviation of a set, given the average value.
* @param c Values set
* @param mean Average value of the set.
* @return Return the standard deviation of the set.
*/
public static double stdDeviation(Collection<Double> c, double mean)
{
double var = variance(c, mean);
return Math.sqrt(var/(c.size()-1));
}
public static double variance(Collection<Double> c, double mean){
double sum = 0.0;
for (Double i: c) {
double cur = i-mean;
sum+=cur*cur;
}
return sum;
}
public static double variance(Collection<Double> c){
return variance(c, mean(c));
}
/**
* Computes the standard deviation of a set.
* @param c Values set
* @return Return the standard deviation of the set.
*/
public static double stdDeviation(Collection<Double> c){
return stdDeviation(c, mean(c));
}
}
| Java |
package hr.fer.anna.tests.microcode;
import java.util.Random;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.microcode.AddMicroinstruction;
import hr.fer.anna.microcode.SubtractMicroinstruction;
import hr.fer.anna.oisc.StatusRegister;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.Register;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Testovi ALU mikrokoda.
* @author Boran
*
*/
public class ArithmeticTests {
/** Broj testova */
private static final int NUM_OF_TESTS = 1000;
/** Širina općih registara koje koristimo (u bitovima) */
private static final int REGISTER_WIDTH = 32;
/**
* Registar zastavica koji se koristi prilikom testiranja. ALU naredbe postavljaju
* zastavice tokom svog izvršavanja.
*/
private static IFlagsRegister flagsRegister;
/**
* Općeniti registar 1 koji služi za testiranje.
*/
private static Register regA;
/**
* Općeniti registar 2 koji služi za testiranje.
*/
private static Register regB;
/**
* Generator slučajnih brojeva
*/
private static Random random;
/**
* Inicijalizacija registra zastavica i općenitih registara.
*/
@BeforeClass
public static void setUp() {
// Koristimo OISC-ov status registar kao registar zastavica
flagsRegister = new StatusRegister();
regA = new Register(REGISTER_WIDTH);
regB = new Register(REGISTER_WIDTH);
random = new Random();
}
/**
* Testira aritmetičku operaciju zbrajanja nad registrima.
*/
@Test
public void testAdd() {
Register result = new Register(REGISTER_WIDTH);
for (int i = 0; i < NUM_OF_TESTS; i++) {
int a = random.nextInt() & 0x3FFFFFFF;
int b = random.nextInt() & 0x3FFFFFFF;
regA.set(new Constant(a));
regB.set(new Constant(b));
try {
new AddMicroinstruction(result, regA, regB, flagsRegister).execute();
} catch (Exception e) {
Assert.fail(e.getLocalizedMessage());
}
Assert.assertEquals("Oduzimanje ne radi pravilno!", Integer.toHexString(a+b).toUpperCase(), result.getHexString().toUpperCase());
Assert.assertEquals("Zastavica negative nije pravilno postavljena!", (a+b) < 0, flagsRegister.getNegative());
Assert.assertEquals("Zastavica greške nije ispravno postavljena!", false, flagsRegister.getOverflow());
}
}
/**
* Testira aritmetičku operaciju oduzimanja nad registrima.
*/
@Test
public void testSubtract() {
Register result = new Register(REGISTER_WIDTH);
for (int i = 0; i < NUM_OF_TESTS; i++) {
int a = random.nextInt() & 0x3FFFFFFF;
int b = random.nextInt() & 0x3FFFFFFF;
regA.set(new Constant(a));
regB.set(new Constant(b));
try {
new SubtractMicroinstruction(result, regA, regB, flagsRegister).execute();
} catch (Exception e) {
Assert.fail(e.getLocalizedMessage());
}
Assert.assertEquals("Oduzimanje ne radi pravilno!", Integer.toHexString(a-b).toUpperCase(), result.getHexString().toUpperCase());
Assert.assertEquals("Zastavica negative nije pravilno postavljena!", (a-b) < 0, flagsRegister.getNegative());
Assert.assertEquals("Zastavica greške nije ispravno postavljena!", false, flagsRegister.getOverflow());
}
}
/**
* Testira nastupanje greške tokom računanja dvaju vrijednosti. Greška nastupa kada su
* predznaka obaju operanada ista, a predznak rezultata različit.
*/
@Test
public void testOverflow() {
Register result = new Register(REGISTER_WIDTH);
for (int i = 0; i < NUM_OF_TESTS; i++) {
int a = random.nextInt();
int b = random.nextInt();
regA.set(new Constant(a));
regB.set(new Constant(b));
try {
new AddMicroinstruction(result, regA, regB, flagsRegister).execute();
} catch (Exception e) {
Assert.fail(e.getLocalizedMessage());
}
boolean overflow = (a > 0 && b > 0 && (a+b) < 0) || (a < 0 && b < 0 && (a+b) > 0);
Assert.assertEquals("Testiranje greške ne radi pravilno!", overflow, flagsRegister.getOverflow());
}
}
}
| Java |
package hr.fer.anna.tests.oisc;
import hr.fer.anna.oisc.StatusRegister;
import hr.fer.anna.tests.uniform.IFlagsRegisterConformance;
import org.junit.Before;
import org.junit.Test;
/**
* JUnit testovi OISC-ovog StatusRegistera
* @author Boran
*
*/
public class StatusRegisterTest {
/**
* Primjerak status registra koji ćemo testirati.
*/
private StatusRegister register;
/**
* Inicijalizira sve potrebno.
*/
@Before
public void setUp() {
register = new StatusRegister();
}
/**
* Testira ispravnu implementaciju ovog registra kao flags registra.
*/
@Test
public void testIFlagsRegisterCompliance() {
IFlagsRegisterConformance.testCarry(register);
IFlagsRegisterConformance.testZero(register);
IFlagsRegisterConformance.testOverflow(register);
IFlagsRegisterConformance.testPositiveNegative(register);
}
}
| Java |
package hr.fer.anna.tests.oisc;
import java.util.Random;
import hr.fer.anna.exceptions.BusAddressTaken;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IEventListener;
import hr.fer.anna.interfaces.IEventSetter;
import hr.fer.anna.oisc.Assembler;
import hr.fer.anna.oisc.Cpu;
import hr.fer.anna.simulator.Simulator;
import hr.fer.anna.uniform.Address;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.PlainBus;
import hr.fer.anna.uniform.SimpleMemory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Testovi procesora, njegovog načina izvršavanja. Simuliranje samog rada procesora.
* @author Boran
*
*/
public class CpuTest {
/** Veličina memorije (u bajtovima) */
private static final int MEMORY_SIZE = 1024;
/** Instanca procesora koja će se testirati */
private Cpu cpu;
/** Bus koji je spojen na procesor */
private PlainBus bus;
/** Memorija koja je spojena na bus */
private SimpleMemory memory;
/** Početno vrijeme simulacije */
private long startingSimulationTime;
/** Simulator koji koristimo prilikom simulacije */
private Simulator simulator;
/** Generator slučajnih brojeva */
private Random random;
@Before
public void setUp() {
this.bus = new PlainBus();
this.cpu = new Cpu(this.bus);
this.memory = new SimpleMemory(MEMORY_SIZE, 32);
try {
this.bus.registerBusUnit(this.memory, Address.fromWord(new Constant(0)));
} catch (UnknownAddressException ignorable) {
} catch (BusAddressTaken ignorable) {
}
this.simulator = new Simulator();
this.startingSimulationTime = simulator.getSimulatorTime();
simulator.registerEventSetters(new IEventSetter[] {this.cpu, this.memory});
simulator.registerEventListeners(new IEventListener[] {this.cpu, this.memory});
random = new Random();
}
/**
* Testira zbrajanje dvaju vrijednosti.
* 0: ADD a,b koji zbraja a i b i rezultat stavlja u b prelazi u:
* 0: SUBNEG a Z 4
* 4: SUBNEG Z b 8
* 8: SUBNEG Z Z 12
*
* Z je na lokaciji 1000 i mora biti vrijednosti 0
* a je na lokaciji 1004
* b je na lokaciji 1008
*/
@Test
public void simpleAddTest() {
final int a = 409658; //random.nextInt(1000000);
final int b = 945509; //random.nextInt(1000000);
try {
this.memory.write(Assembler.assemble(
"SUBNEG 1001 1000 1\n" +
"SUBNEG 1000 1002 2\n" +
"SUBNEG 1000 1000 3\n"
),
Address.fromWord(new Constant(0))
);
// halt
this.memory.write(new Constant(0), Address.fromWord(new Constant(4)));
this.memory.write(new Constant(0), Address.fromWord(new Constant(1000)));
this.memory.write(new Constant(a), Address.fromWord(new Constant(1001)));
this.memory.write(new Constant(b), Address.fromWord(new Constant(1002)));
simulator.run();
Assert.assertEquals("Zbroj nije točan!", Integer.toHexString(a+b).toUpperCase(), memory.read(Address.fromWord(new Constant(1002))).getHexString());
Assert.assertEquals("Trajanje simulacije neispravno!", startingSimulationTime + 24L + 2L, simulator.getSimulatorTime());
} catch (Exception e){
Assert.fail("Dogodila se neočekivana greška: " + e.getMessage());
}
}
/**
* Testira bezuvjetno skakanje na određenu adresu.
* 0: JMP c skoči na adresu c prelazi u:
* 0: SUBNEG POS Z c
* ...
* c: SUBNEG Z Z
*
* Z je na lokaciji 1000 i iznosi 0
* POS je na lokaciji 1004 i to je neki pozitivan broj
* c je neka proizvoljna lokacija od 4 do 996
*/
@Test
public void unconditionalJumpTest() {
final int pos = random.nextInt(1000000);
final int c = random.nextInt(MEMORY_SIZE);
try {
this.memory.write(
Assembler.assemble("SUBNEG 1001 1000 " + c + "\n"),
Address.fromWord(new Constant(0))
);
//halt
this.memory.write(new Constant(0), Address.fromWord(new Constant(1)));
this.memory.write(new Constant(0), Address.fromWord(new Constant(1000)));
this.memory.write(new Constant(pos), Address.fromWord(new Constant(1001)));
simulator.run();
Assert.assertEquals("Neispravna vrijednost na lokaciji 1000!", Integer.toHexString(-pos).toUpperCase(), memory.read(Address.fromWord(new Constant(1000))).toString());
Assert.assertEquals("Neispravan skok!", Integer.toHexString(c+1).toUpperCase(), this.cpu.describe().getRegister("PC").getHexString());
Assert.assertEquals("Trajanje simulacije neispravno!", startingSimulationTime + 8L + 2L, simulator.getSimulatorTime());
} catch (Exception e){
Assert.fail("Dogodila se neočekivana greška: " + e.getMessage());
}
}
}
| Java |
package hr.fer.anna.tests.uniform;
import org.junit.Assert;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusMaster;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
public class BusMasterForTesting implements IBusMaster {
/** Očekivana adresa */
private Address expectedAddress;
/** Očekivana riječ */
private Word expecetedWord;
/** Očekivana sabirnica */
private IBus expectedBus;
/**
*
* @param expecetedWord
*/
public void setExpecetedWord(Word expecetedWord) {
this.expecetedWord = expecetedWord;
}
public void setExpectedAddress(Address expectedAddress) {
this.expectedAddress = expectedAddress;
}
public void busReadCallback(IBus bus, Address globalAddress, Word word) {
if (this.expectedBus != null) {
Assert.assertEquals("Sabirnica nije jednaka očekivanoj!", this.expectedBus, bus);
}
if (this.expectedAddress != null) {
Assert.assertEquals("Adresa nije jednaka očekivanoj!", this.expectedAddress, globalAddress);
}
if (this.expecetedWord != null) {
Assert.assertEquals("Riječ nije jednaka očekivanoj!", this.expecetedWord, word);
}
}
public void busWriteCallback(IBus bus, Address globalAddress) {
if (this.expectedBus != null) {
Assert.assertEquals("Sabirnica nije jednaka očekivanoj!", this.expectedBus, bus);
}
if (this.expectedAddress != null) {
Assert.assertEquals("Adresa nije jednaka očekivanoj!", this.expectedAddress, globalAddress);
}
}
public void waitBus(IBus bus, boolean state) {
}
}
| Java |
package hr.fer.anna.tests.uniform;
import hr.fer.anna.interfaces.IFlagsRegister;
import org.junit.Assert;
/**
* Klasa koja implementira metode za provjeru i testiranje nekog registra. Testira se
* zadovoljanje sučelja IFlagsRegister i njihova ispravna implementacija. Testovi su
* osmišljeni tako da se pozivaju unutar testova određenog registra.
* @author Boran
*
*/
public class IFlagsRegisterConformance {
/**
* Testira postavljanje i brisanje carry zastavice.
*/
public static void testCarry(IFlagsRegister register) {
register.setCarry(true);
Assert.assertEquals("Postavljanje carry ne radi!", true, register.getCarry());
register.setCarry(false);
Assert.assertEquals("Brisanje carry ne radi!", false, register.getCarry());
}
/**
* Testira postavljanje i brisanje equal zastavice.
*/
public static void testZero(IFlagsRegister register) {
register.setZero(true);
Assert.assertEquals("Postavljanje zero ne radi!", true, register.getZero());
register.setZero(false);
Assert.assertEquals("Brisanje zero ne radi!", false, register.getZero());
}
/**
* Testira postavljanje i brisanje overflow zastavice.
*/
public static void testOverflow(IFlagsRegister register) {
register.setOverflow(true);
Assert.assertEquals("Postavljanje overflow ne radi!", true, register.getOverflow());
register.setOverflow(false);
Assert.assertEquals("Brisanje overflow ne radi!", false, register.getOverflow());
}
/**
* Testira postavljanje i brisanje positive i negative zastavica i njihovu međusobnu ovisnost.
* Positive je ekvivalentan komplementu negative i to mora vrijediti uvijek.
*/
public static void testPositiveNegative(IFlagsRegister register) {
register.setPositive();
Assert.assertEquals("Postavljanje positive ne radi!", true, register.getPositive());
Assert.assertEquals("Positive i negative nisu dobro povezani!", false, register.getNegative());
register.setNegative();
Assert.assertEquals("Postavljanje negative ne radi!", true, register.getNegative());
Assert.assertEquals("Negative i positive nisu dobro povezani!", false, register.getPositive());
}
}
| Java |
package hr.fer.anna.tests.uniform;
import org.junit.Assert;
import hr.fer.anna.exceptions.BusAddressTaken;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusMaster;
import hr.fer.anna.interfaces.IBusUnit;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
public class BusForTesting implements IBus {
/**
* Vanjska jedinica koja se testira
*/
private IBusUnit expectedBusUnit;
/**
* Lokalna adresa kojoj treba biti pristupljeno
*/
private Address expectedAddress;
/**
* Riječ koja se treba dohvatiti s jedinice
*/
private Word expectedWord;
/**
* Postavlja lokalnu adresu koju trebamo dobiti
* @param expectedAddress lokalna adresa na jedinici
*/
public void setExpectedAddress(Address expectedAddress) {
this.expectedAddress = expectedAddress;
}
/**
* Postavlja jedinicu kojoj je sabirnica trebala pristupiti
* @param expectedBusUnit jedinica
*/
public void setExpectedBusUnit(IBusUnit expectedBusUnit) {
this.expectedBusUnit = expectedBusUnit;
}
/**
* Postavlja riječ koja je trebala biti pročitana
* @param expectedWord očekivana riječ
*/
public void setExpectedWord(Word expectedWord) {
this.expectedWord = expectedWord;
}
public void busUnitReadCallback(IBusUnit busUnit, Address localAddress, Word word) {
Assert.assertEquals("S krive jedinice je pročitan podatak!", this.expectedBusUnit, busUnit);
Assert.assertEquals("S krive adrese je pročitan podatak!", this.expectedAddress, localAddress);
if(this.expectedWord != null) {
Assert.assertEquals("Neispravno čitanje podatka!", this.expectedWord, word);
}
}
public void busUnitWriteCallback(IBusUnit busUnit, Address localAddress) {
Assert.assertEquals("Na krivu jedinicu je zapisan podatak!", this.expectedBusUnit, busUnit);
Assert.assertEquals("Na krivu adresu je zapisan podatak!", this.expectedAddress, localAddress);
}
public IBusMaster getBusMaster() {
return null;
}
public boolean isBusy() {
return false;
}
public void registerBusUnit(IBusUnit busUnit, Address startAddress) throws UnknownAddressException, BusAddressTaken {
// Nepotrebno
}
public void requestRead(IBusMaster busMaster, Address globalAddress) throws UnknownAddressException, IllegalActionException {
// Nepotrebno
}
public void requestWrite(IBusMaster busMaster, Address globalAddress, Word word) throws UnknownAddressException, IllegalActionException {
// Nepotrebno
}
public void setBusMaster(IBusMaster newBusMaster) throws IllegalActionException {
// Nepotrebno
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.