hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
5c02af2f6d83c892e02f05bf55d31caec04ca65d
| 4,013
|
package app.taxipizzastaff.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GpsService extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
boolean isNetworkEnabled = false;
protected LocationManager locationManager;
public GpsService(Context context) {
this.context = context;
getLocation();
}
@Override
public void onCreate() {
super.onCreate();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isGPSEnabled ) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
8000,
10, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
8000,
10, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
if(location != null) {
latitude = location.getLatitude();
Log.i("gpsservice", latitude + "");
}
return latitude;
}
public double getLongitude() {
if(location != null) {
longitude = location.getLongitude();
Log.i("gpsservice", longitude + "");
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
| 27.29932
| 106
| 0.530526
|
9122b032e1a26db6d419ce5e75f90ac7da41ddb7
| 24,134
|
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2020 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.janusproject.kernel.bic;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReadWriteLock;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.eclipse.xtext.xbase.lib.Pure;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
import io.janusproject.services.executor.EarlyExitException;
import io.janusproject.services.executor.ExecutorService;
import io.janusproject.services.executor.JanusRunnable;
import io.sarl.core.AgentTask;
import io.sarl.core.Logging;
import io.sarl.core.Schedules;
import io.sarl.core.Time;
import io.sarl.lang.core.Agent;
import io.sarl.lang.core.AgentTrait;
import io.sarl.lang.core.Behavior;
import io.sarl.lang.core.Capacities;
import io.sarl.lang.core.SREutils;
import io.sarl.lang.core.Skill;
import io.sarl.lang.util.ClearableReference;
import io.sarl.lang.util.SynchronizedSet;
import io.sarl.util.concurrent.Collections3;
/**
* Skill that permits to execute tasks with an executor service.
*
* @author $Author: srodriguez$
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public class SchedulesSkill extends BuiltinSkill implements Schedules {
private static int installationOrder = -1;
@Inject
private ExecutorService executorService;
private final Map<String, TaskDescription> tasks = new TreeMap<>();
@Inject
private ReadWriteLock tasksLock;
private ClearableReference<Skill> skillBufferLogging;
private ClearableReference<Skill> skillBufferTime;
/** Constructor.
* @param agent the owner of this skill.
*/
SchedulesSkill(Agent agent) {
super(agent);
}
/** Replies the Logging skill as fast as possible.
*
* @return the skill
*/
protected final Logging getLoggingSkill() {
if (this.skillBufferLogging == null || this.skillBufferLogging.get() == null) {
this.skillBufferLogging = $getSkill(Logging.class);
}
return $castSkill(Logging.class, this.skillBufferLogging);
}
/** Replies the Time skill as fast as possible.
*
* @return the skill
*/
protected final Time getTimeSkill() {
if (this.skillBufferTime == null || this.skillBufferTime.get() == null) {
this.skillBufferTime = $getSkill(Time.class);
}
return $castSkill(Time.class, this.skillBufferTime);
}
/** Replies the lock for synchronizing on the task list.
*
* @return the lock.
*/
/** {@inheritDoc}
*
* @deprecated since 0.10
*/
@Override
@Deprecated
public int getInstallationOrder() {
if (installationOrder < 0) {
installationOrder = installationOrder(this);
}
return installationOrder;
}
/** Replies the lock for the tasks' list.
*
* @return the lock.
* @since 0.10
*/
protected final ReadWriteLock getTaskListLock() {
return this.tasksLock;
}
@Override
@Pure
public void toString(ToStringBuilder builder) {
super.toString(builder);
builder.add("tasks", this.tasks); //$NON-NLS-1$
}
/**
* Remove any reference to the given task.
*
* <p>This function is thread-safe.
*
* @param task the task.
* @param updateSkillReferences indicates if the references to skills should be updated too.
* @param updateAgentTraitReferences indicates if the references to agent traits should be updated too.
*/
private void finishTask(AgentTask task, boolean updateSkillReferences, boolean updateAgentTraitReferences) {
assert task != null;
if (updateSkillReferences) {
final ReadWriteLock llock = getTaskListLock();
llock.writeLock().lock();
try {
this.tasks.remove(task.getName());
} finally {
llock.writeLock().unlock();
}
}
if (updateAgentTraitReferences) {
final Object initiator = task.getInitiator();
if (initiator instanceof AgentTrait) {
final AgentTrait trait = (AgentTrait) initiator;
final AgentTraitData data = SREutils.getSreSpecificData(trait, AgentTraitData.class);
if (data != null) {
data.removeTask(task);
}
}
}
}
@Override
public SynchronizedSet<String> getActiveTasks() {
final ReadWriteLock lock = getTaskListLock();
lock.readLock().lock();
try {
return Collections3.unmodifiableSynchronizedSet(this.tasks.keySet(), lock);
} finally {
lock.readLock().unlock();
}
}
/**
* Replies the names of the active futures.
*
* @return the names of the active futures.
*/
Collection<Future<?>> getActiveFutures() {
final ReadWriteLock lock = getTaskListLock();
lock.readLock().lock();
try {
return Lists.newArrayList(Iterables.transform(this.tasks.values(), it -> it.getFuture()));
} finally {
lock.readLock().unlock();
}
}
/** Unregister the tasks associated to the given behavior.
*
* @param behavior the behavior.
*/
void unregisterTasksForBehavior(Behavior behavior) {
final AgentTraitData data = SREutils.getSreSpecificData(behavior, AgentTraitData.class);
if (data != null) {
final Iterable<AgentTask> iterable = data.resetTaskList();
for (final AgentTask taskToCancel : iterable) {
cancel(taskToCancel, Schedules.$DEFAULT_VALUE$CANCEL_0, false);
}
}
}
/** Cancel the running tasks.
*
* <p>This function is thread-safe.
*/
private void cancelAllRunningTasks() {
Future<?> future;
AgentTask task;
final ReadWriteLock lock = getTaskListLock();
lock.writeLock().lock();
try {
for (final Entry<String, TaskDescription> taskDescription : this.tasks.entrySet()) {
final TaskDescription pair = taskDescription.getValue();
if (pair != null) {
future = pair.getFuture();
if (future != null) {
future.cancel(true);
}
task = pair.getTask();
if (task != null) {
finishTask(task, false, true);
}
}
}
this.tasks.clear();
} finally {
lock.writeLock().unlock();
}
}
@Override
protected void uninstall(UninstallationStage stage) {
if (stage == UninstallationStage.PRE_DESTROY_EVENT) {
// Cancel the tasks as soon as possible in the uninstallation process
cancelAllRunningTasks();
} else {
// Cancel the tasks that were creating during the destruction stage (in the Destroy event handler)
cancelAllRunningTasks();
}
}
@Override
public AgentTask in(long delay, Procedure1<? super Agent> procedure) {
return in(Schedules.$DEFAULT_VALUE$IN_0, delay, procedure);
}
@Override
public AgentTask in(AgentTask task, long delay, Procedure1<? super Agent> procedure) {
TaskDescription description = preRunTask(task, procedure);
final long osDelay = Math.round(getTimeSkill().toOSDuration(delay));
final AgentTask runnableTask = description != null ? description.getTask() : task;
final ScheduledFuture<?> sf = this.executorService.schedule(
new AgentTaskRunner(runnableTask, false),
osDelay, TimeUnit.MILLISECONDS);
description = postRunTask(description, task, sf);
return description.getTask();
}
@Override
public AgentTask at(AgentTask task, long time, Procedure1<? super Agent> procedure) {
final long delay = Math.round(time - getTimeSkill().getTime());
if (delay > 0.) {
return in(task, delay, procedure);
}
return task;
}
/** Prepare the task to be run.
*
* <p>This function is thread safe.
*
* @param task the task to run.
* @param procedure the procedure to attach tothe task.
* @return the description
*/
private TaskDescription preRunTask(AgentTask task, Procedure1<? super Agent> procedure) {
final TaskDescription pair;
final AgentTask rtask;
if (task == null) {
pair = createTaskIfNecessary(null);
rtask = pair.getTask();
} else {
rtask = task;
final ReadWriteLock lock = getTaskListLock();
lock.readLock().lock();
try {
pair = this.tasks.get(task.getName());
} finally {
lock.readLock().unlock();
}
if (pair != null) {
// Caution: according to the lock's documentation, the writing lock cannot be obtained with reading lock handle
lock.writeLock().lock();
try {
pair.setTask(rtask);
} finally {
lock.writeLock().unlock();
}
}
}
rtask.setProcedure(procedure);
return pair;
}
/** Finalize the running query for the given task.
*
* <p>This function is thread-safe.
*
* @param description the description of the task.
* @param task the task.
* @param future the future object associated to the task.
* @return the description.
*/
private TaskDescription postRunTask(TaskDescription description, AgentTask task, Future<?> future) {
final TaskDescription pair;
if (description == null) {
pair = new TaskDescription(task, future);
final ReadWriteLock lock = getTaskListLock();
lock.writeLock().lock();
try {
this.tasks.put(task.getName(), pair);
} finally {
lock.writeLock().unlock();
}
} else {
pair = description;
pair.setFuture(future);
}
return pair;
}
/** Create a task if it was not created.
*
* <p>This function is thread-safe.
*
* @param name the name of the task.
* @return the description.
*/
private TaskDescription createTaskIfNecessary(String name) {
TaskDescription pair = null;
final String realName;
final ReadWriteLock lock = getTaskListLock();
if (Strings.isNullOrEmpty(name)) {
realName = "task-" + UUID.randomUUID().toString(); //$NON-NLS-1$
} else {
realName = name;
lock.readLock().lock();
try {
pair = this.tasks.get(realName);
} finally {
lock.readLock().unlock();
}
}
if (pair == null) {
final AgentTrait caller = Capacities.getCaller();
final AgentTask task = new AgentTask(caller);
task.setTaskName(realName);
task.setGuard(AgentTask.TRUE_GUARD);
pair = new TaskDescription(task);
// Caution: according to the lock's documentation, the writing lock cannot be obtained with reading lock handle
lock.writeLock().lock();
try {
this.tasks.put(realName, pair);
} finally {
lock.writeLock().unlock();
}
if (caller != null) {
AgentTraitData data = SREutils.getSreSpecificData(caller, AgentTraitData.class);
if (data == null) {
data = new AgentTraitData();
SREutils.setSreSpecificData(caller, data);
}
data.addTask(task);
}
}
return pair;
}
@Override
public AgentTask task(String name) {
return createTaskIfNecessary(name).getTask();
}
@Override
public void setName(AgentTask task, String name) {
String nm = name;
int i = 0;
final String prefix = name + "-"; //$NON-NLS-1$
final TaskDescription desc;
final ReadWriteLock lock = getTaskListLock();
lock.writeLock().lock();
try {
desc = this.tasks.remove(task.getName());
if (desc != null) {
// Acquire the reading lock before releasing the writing lock
lock.readLock().lock();
}
} finally {
lock.writeLock().unlock();
}
if (desc != null) {
try {
while (this.tasks.containsKey(nm)) {
++i;
nm = prefix + i;
}
} finally {
lock.readLock().unlock();
}
task.setTaskName(nm);
// Caution: according to the lock's documentation, the writing lock cannot be obtained with reading lock handle
lock.writeLock().lock();
try {
this.tasks.put(nm, desc);
} finally {
lock.writeLock().unlock();
}
}
}
@Override
public final boolean cancel(AgentTask task) {
return cancel(task, Schedules.$DEFAULT_VALUE$CANCEL_0, true);
}
@Override
public final boolean cancel(AgentTask task, boolean mayInterruptIfRunning) {
return cancel(task, mayInterruptIfRunning, true);
}
/** Cancel the given task with finer control on the reference updates.
*
* @param task the task to cancel.
* @param mayInterruptIfRunning indicates if the task's thread could be interrupt.
* @param updateAgentTraitReferences indicates if the references in the task's agent trait may be updates, if
* they exist.
* @return {@code true} if the task is canceled, {@code false} if not.
*/
protected boolean cancel(AgentTask task, boolean mayInterruptIfRunning, boolean updateAgentTraitReferences) {
if (task != null) {
final String name = task.getName();
final TaskDescription pair;
final ReadWriteLock lock = getTaskListLock();
lock.readLock().lock();
try {
pair = this.tasks.get(name);
} finally {
lock.readLock().unlock();
}
if (pair != null) {
final Future<?> future = pair.getFuture();
if (future != null && !future.isDone() && !future.isCancelled() && future.cancel(mayInterruptIfRunning)) {
finishTask(task, true, updateAgentTraitReferences);
return true;
}
}
}
return false;
}
@Override
public boolean isCanceled(AgentTask task) {
if (task != null) {
final String name = task.getName();
final Future<?> future = getActiveFuture(name);
if (future != null) {
return future.isCancelled();
}
}
return false;
}
/** Replies the future object for the given task.
*
* @param taskName the name of the task.
* @return the future.
* @since 0.5
*/
Future<?> getActiveFuture(String taskName) {
final TaskDescription pair;
final ReadWriteLock lock = getTaskListLock();
lock.readLock().lock();
try {
pair = this.tasks.get(taskName);
} finally {
lock.readLock().unlock();
}
if (pair != null) {
return pair.getFuture();
}
return null;
}
@Override
public AgentTask every(long period, Procedure1<? super Agent> procedure) {
return every(Schedules.$DEFAULT_VALUE$EVERY_0, period, procedure);
}
@Override
public AgentTask every(AgentTask task, long period, Procedure1<? super Agent> procedure) {
TaskDescription description = preRunTask(task, procedure);
final long osPeriod = Math.round(getTimeSkill().toOSDuration(period));
final AgentTask runnableTask = description != null ? description.getTask() : task;
final ScheduledFuture<?> sf = this.executorService.scheduleAtFixedRate(
new AgentTaskRunner(runnableTask, true),
0, osPeriod, TimeUnit.MILLISECONDS);
description = postRunTask(description, task, sf);
return description.getTask();
}
@Override
public AgentTask atFixedDelay(long delay, Procedure1<? super Agent> procedure) {
return atFixedDelay(Schedules.$DEFAULT_VALUE$ATFIXEDDELAY_0, delay, procedure);
}
@Override
public AgentTask atFixedDelay(AgentTask task, long delay, Procedure1<? super Agent> procedure) {
TaskDescription description = preRunTask(task, procedure);
final AgentTask runnableTask = description != null ? description.getTask() : task;
final Future<?> future;
final long osDelay = Math.round(getTimeSkill().toOSDuration(delay));
if (osDelay <= 0) {
future = this.executorService.submit(new AgentInfiniteLoopTask(runnableTask));
} else {
future = this.executorService.scheduleWithFixedDelay(
new AgentTaskRunner(runnableTask, true),
0, osDelay, TimeUnit.MILLISECONDS);
}
description = postRunTask(description, task, future);
return description.getTask();
}
@Override
public AgentTask execute(Procedure1<? super Agent> procedure) {
return execute(Schedules.$DEFAULT_VALUE$EXECUTE_0, procedure);
}
@Override
public AgentTask execute(AgentTask task, Procedure1<? super Agent> procedure) {
TaskDescription description = preRunTask(task, procedure);
final AgentTask runnableTask = description != null ? description.getTask() : task;
final Future<?> future = this.executorService.submit(new AgentTaskRunner(runnableTask, false));
description = postRunTask(description, task, future);
return description.getTask();
}
/**
* Implementation of an agent task.
*
* @author $Author: srodriguez$
* @author $Author: sgalland$
* @version $Name$ $Revision$ $Date$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
@SuppressWarnings("synthetic-access")
private class AgentTaskRunner extends JanusRunnable {
private final WeakReference<AgentTask> agentTaskRef;
private WeakReference<Future<?>> future;
private final boolean isPeriodic;
AgentTaskRunner(AgentTask task, boolean isPeriodic) {
assert task != null;
this.agentTaskRef = new WeakReference<>(task);
this.isPeriodic = isPeriodic;
}
/** Set the future of this task.
*
* @param future the future.
* @since 0.5
*/
void setFuture(Future<?> future) {
this.future = future == null ? null : new WeakReference<>(future);
}
/** Replies the future of this task.
*
* @return the future.
* @since 0.5
*/
private Future<?> getFuture() {
final WeakReference<Future<?>> safeFutureReference = this.future;
return safeFutureReference == null ? null : safeFutureReference.get();
}
@Override
public void run() {
final AgentTask task = this.agentTaskRef.get();
if (task == null) {
throw new RuntimeException(Messages.SchedulesSkill_0);
}
final Future<?> future = getFuture();
if (future != null && (future.isDone() || future.isCancelled())) {
setFuture(null);
return;
}
boolean mustBeCanceled = false;
try {
final Agent owner = getOwner();
final Function1<? super Agent, ? extends Boolean> guard = task.getGuard();
if (guard == null || guard.apply(owner).booleanValue()) {
final Procedure1<? super Agent> procedure = task.getProcedure();
if (procedure != null) {
procedure.apply(owner);
}
} else {
mustBeCanceled = true;
}
} catch (EarlyExitException ex) {
// Be silent
} catch (Throwable ex) {
getLoggingSkill().error(Messages.SchedulesSkill_1, ex, toString(), ex.getLocalizedMessage());
mustBeCanceled = true;
} finally {
if (mustBeCanceled || !this.isPeriodic) {
finishTask(task, true, true);
}
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("name", this.agentTaskRef.get().getName()) //$NON-NLS-1$
.add("agent", getOwner().getID()).toString(); //$NON-NLS-1$
}
}
/**
* Implementation of an agent infinite loop task.
*
* @author $Author: srodriguez$
* @version $Name$ $Revision$ $Date$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
@SuppressWarnings("synthetic-access")
private class AgentInfiniteLoopTask extends JanusRunnable {
private WeakReference<AgentTask> agentTaskRef;
AgentInfiniteLoopTask(AgentTask task) {
this.agentTaskRef = new WeakReference<>(task);
}
private boolean canRun() {
final AgentTask task = this.agentTaskRef.get();
if (task != null) {
final Future<?> future = getActiveFuture(task.getName());
return future != null && !future.isDone() && !future.isCancelled();
}
return false;
}
private Function1<? super Agent, ? extends Boolean> getGuard() {
final AgentTask task = this.agentTaskRef.get();
if (task != null) {
return task.getGuard();
}
return null;
}
private Procedure1<? super Agent> getProcedure() {
final AgentTask task = this.agentTaskRef.get();
if (task != null) {
return task.getProcedure();
}
return null;
}
@Override
public void run() {
try {
final Agent owner = getOwner();
while (canRun()) {
final Function1<? super Agent, ? extends Boolean> guard = getGuard();
if (guard == null || guard.apply(owner).booleanValue()) {
final Procedure1<? super Agent> procedure = getProcedure();
if (procedure != null) {
procedure.apply(owner);
}
} else {
// Break the loop without introducing a local boolean variable
break;
}
Thread.yield();
}
} catch (EarlyExitException ex) {
// Ignore
} catch (Throwable ex) {
getLoggingSkill().error(Messages.SchedulesSkill_1, ex, toString(), ex.getLocalizedMessage());
} finally {
final AgentTask task = this.agentTaskRef.get();
if (task != null) {
finishTask(task, true, true);
}
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("name", this.agentTaskRef.get().getName()) //$NON-NLS-1$
.add("agent", getOwner().getID()).toString(); //$NON-NLS-1$
}
}
/**
* Description of a task.
*
* @author $Author: sgalland$
* @version $Name$ $Revision$ $Date$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 0.5
*/
private static class TaskDescription {
/** Agent task.
*/
private AgentTask task;
/** The scheduled future associated to the task.
*/
private Future<?> future;
TaskDescription(AgentTask task) {
this(task, null);
}
TaskDescription(AgentTask task, Future<?> future) {
this.task = task;
if (future == null) {
this.future = new FutureReceiver();
} else {
this.future = future;
}
}
@Override
public String toString() {
return Objects.toString(this.task);
}
public AgentTask getTask() {
return this.task;
}
public void setTask(AgentTask task) {
this.task = task;
}
public Future<?> getFuture() {
return this.future;
}
public void setFuture(Future<?> future) {
if (future != null) {
final FutureReceiver receiver;
if (this.future instanceof FutureReceiver) {
receiver = (FutureReceiver) this.future;
} else {
receiver = null;
}
this.future = future;
if (receiver != null) {
receiver.apply(this.future);
}
}
}
/**
* A future definition that enables to interact with the future
* object's even if it is not already provided by the thread manager.
* This receiver will be replaced by the real future object as soon
* as it is provided by the thread manager. Then, any interaction with
* the receiver will be propagated to the real future.
*
* @author $Author: sgalland$
* @version $Name$ $Revision$ $Date$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 0.9
*/
private static class FutureReceiver implements Future<Object> {
private final AtomicBoolean cancelFlag = new AtomicBoolean();
private final AtomicBoolean mayInterruptIfRunningFlag = new AtomicBoolean();
FutureReceiver() {
//
}
void apply(Future<?> future) {
if (future != null && !future.isCancelled() && !future.isDone() && this.cancelFlag.get()) {
future.cancel(this.mayInterruptIfRunningFlag.get());
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
this.mayInterruptIfRunningFlag.set(mayInterruptIfRunning);
this.cancelFlag.set(true);
return true;
}
@Override
public boolean isCancelled() {
return this.cancelFlag.get();
}
@Override
public boolean isDone() {
return false;
}
@Override
public Object get() throws InterruptedException, ExecutionException {
throw new ExecutionException(new UnsupportedOperationException());
}
@Override
public Object get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
throw new ExecutionException(new UnsupportedOperationException());
}
}
}
}
| 27.99768
| 115
| 0.690437
|
63ad42684a80e80494e69306a4f4e755908d7f1b
| 359
|
package ch.thn.util.gui.component.table;
/**
* @author Thomas Naeff (github.com/thnaeff)
*
*/
public interface SimpleTableColumnListener {
/**
* Is fired if anything on a {@link SimpleTableColumn} (title, renderer, ...) has changed
*
* @param column The column which has changed
*/
public void columnChanged(SimpleTableColumn column);
}
| 21.117647
| 91
| 0.699164
|
6a14acbc9dfec05f161fbb934675fd4a5b508318
| 88,785
|
/*
* Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.javafx.css;
import com.sun.javafx.css.parser.CSSParser;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.css.PseudoClass;
import javafx.css.StyleOrigin;
import javafx.css.Styleable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.image.Image;
import javafx.scene.layout.Region;
import javafx.scene.text.Font;
import javafx.stage.Window;
import sun.util.logging.PlatformLogger;
import sun.util.logging.PlatformLogger.Level;
import java.io.FileNotFoundException;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PermissionCollection;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Contains the stylesheet state for a single scene. This includes both the
* Stylesheets defined on the Scene itself as well as a map of stylesheets for
* "style"s defined on the Node itself. These containers are kept in the
* containerMap, key'd by the Scene to which they belong. <p> One of the key
* responsibilities of the StylesheetContainer is to create and maintain an
* admittedly elaborate series of caches so as to minimize the amount of time it
* takes to match a Node to its eventual StyleHelper, and to reuse the
* StyleHelper as much as possible. <p> Initially, the cache is empty. It is
* recreated whenever the userStylesheets on the container change, or whenever
* the userAgentStylesheet changes. The cache is built up as nodes are looked
* for, and thus there is some overhead associated with the first lookup but
* which is then not repeated for subsequent lookups. <p> The cache system used
* is a two level cache. The first level cache simply maps the
* classname/id/styleclass combination of the request node to a 2nd level cache.
* If the node has "styles" specified then we still use this 2nd level cache,
* but must combine its selectors with the selectors specified in "styles" and perform
* more work to cascade properly. <p> The 2nd level cache contains a data
* structure called the Cache. The Cache contains an ordered sequence of Rules,
* a Long, and a Map. The ordered sequence of selectors are the selectors that *may*
* match a node with the given classname, id, and style class. For example,
* selectors which may apply are any selector where the simple selector of the selector
* contains a reference to the id, style class, or classname of the Node, or a
* compound selector who's "descendant" part is a simple selector which contains
* a reference to the id, style class, or classname of the Node. <p> During
* lookup, we will iterate over all the potential selectors and discover if they
* apply to this particular node. If so, then we toggle a bit position in the
* Long corresponding to the position of the selector that matched. This long then
* becomes our key into the final map. <p> Once we have established our key, we
* will visit the map and look for an existing StyleHelper. If we find a
* StyleHelper, then we will return it. If not, then we will take the Rules that
* matched and construct a new StyleHelper from their various parts. <p> This
* system, while elaborate, also provides for numerous fast paths and sharing of
* data structures which should dramatically reduce the memory and runtime
* performance overhead associated with CSS by reducing the matching overhead
* and caching as much as possible. We make no attempt to use weak references
* here, so if memory issues result one work around would be to toggle the root
* user agent stylesheet or stylesheets on the scene to cause the cache to be
* flushed.
*/
final public class StyleManager {
/**
* Global lock object for the StyleManager. StyleManager is a singleton,
* which loads CSS stylesheets and manages style caches for all scenes.
* It needs to be thread-safe since a Node or Scene can be constructed and
* load its stylesheets on an arbitrary thread, meaning that multiple Scenes
* can load or apply their stylesheets concurrently. The global lock is used
* to serialize access to the various state in the StyleManager.
*/
private static final Object styleLock = new Object();
private static PlatformLogger LOGGER;
private static PlatformLogger getLogger() {
if (LOGGER == null) {
LOGGER = com.sun.javafx.util.Logging.getCSSLogger();
}
return LOGGER;
}
private static class InstanceHolder {
final static StyleManager INSTANCE = new StyleManager();
}
/**
* Return the StyleManager instance.
*/
public static StyleManager getInstance() {
return InstanceHolder.INSTANCE;
}
private StyleManager() {
}
/**
* A map from a parent to its style cache. The parent is either a Scene root, or a
* Parent with author stylesheets. If a Scene or Parent is removed from the scene,
* it's cache is annihilated.
*/
// package for testing
static final Map<Parent, CacheContainer> cacheContainerMap = new WeakHashMap<>();
// package for testing
CacheContainer getCacheContainer(Styleable styleable, SubScene subScene) {
if (styleable == null && subScene == null) return null;
Parent root = null;
if (subScene != null) {
root = subScene.getRoot();
} else if (styleable instanceof Node) {
Node node = (Node)styleable;
Scene scene = node.getScene();
if (scene != null) root = scene.getRoot();
} else if (styleable instanceof Window) {
// this catches the PopupWindow case
Scene scene = ((Window)styleable).getScene();
if (scene != null) root = scene.getRoot();
}
// todo: what other Styleables need to be handled here?
if (root == null) return null;
synchronized (styleLock) {
CacheContainer container = cacheContainerMap.get(root);
if (container == null) {
container = new CacheContainer();
cacheContainerMap.put(root, container);
}
return container;
}
}
/**
* StyleHelper uses this cache but it lives here so it can be cleared
* when style-sheets change.
*/
public StyleCache getSharedCache(Styleable styleable, SubScene subScene, StyleCache.Key key) {
CacheContainer container = getCacheContainer(styleable, subScene);
if (container == null) return null;
Map<StyleCache.Key,StyleCache> styleCache = container.getStyleCache();
if (styleCache == null) return null;
StyleCache sharedCache = styleCache.get(key);
if (sharedCache == null) {
sharedCache = new StyleCache();
styleCache.put(new StyleCache.Key(key), sharedCache);
}
return sharedCache;
}
public StyleMap getStyleMap(Styleable styleable, SubScene subScene, int smapId) {
if (smapId == -1) return StyleMap.EMPTY_MAP;
CacheContainer container = getCacheContainer(styleable, subScene);
if (container == null) return StyleMap.EMPTY_MAP;
return container.getStyleMap(smapId);
}
/**
* A list of user-agent stylesheets from Scene or SubScene.
* The order of the entries in this list does not matter since a Scene or
* SubScene will only have zero or one user-agent stylesheets.
*/
// package for testing
final List<StylesheetContainer> userAgentStylesheetContainers = new ArrayList<>();
/**
* A list of user-agent stylesheet urls from calling setDefaultUserAgentStylesheet and
* addUserAgentStylesheet. The order of entries this list matters. The zeroth element is
* _the_ platform default.
*/
// package for testing
final List<StylesheetContainer> platformUserAgentStylesheetContainers = new ArrayList<>();
// package for testing
boolean hasDefaultUserAgentStylesheet = false;
////////////////////////////////////////////////////////////////////////////
//
// stylesheet handling
//
////////////////////////////////////////////////////////////////////////////
/*
* A container for stylesheets and the Parents or Scenes that use them.
* If a stylesheet is removed, then all other Parents or Scenes
* that use that stylesheet should get new styles if the
* stylesheet is added back in since the stylesheet may have been
* removed and re-added because it was edited (typical of SceneBuilder).
* This container provides the hooks to get back to those Parents or Scenes.
*
* StylesheetContainer<Parent> are created and added to stylesheetContainerMap
* in the method gatherParentStylesheets.
*
* StylesheetContainer<Scene> are created and added to sceneStylesheetMap in
* the method updateStylesheets
*/
// package for testing
static class StylesheetContainer {
// the stylesheet uri
final String fname;
// the parsed stylesheet so we don't reparse for every parent that uses it
final Stylesheet stylesheet;
// the parents or scenes that use this stylesheet. Typically, this list
// should be very small.
final SelectorPartitioning selectorPartitioning;
// who uses this stylesheet?
final RefList<Parent> parentUsers;
// RT-24516 -- cache images coming from this stylesheet.
// This just holds a hard reference to the image.
final List<Image> imageCache;
final int hash;
final byte[] checksum;
boolean checksumInvalid = false;
StylesheetContainer(String fname, Stylesheet stylesheet) {
this(fname, stylesheet, stylesheet != null ? calculateCheckSum(stylesheet.getUrl()) : new byte[0]);
}
StylesheetContainer(String fname, Stylesheet stylesheet, byte[] checksum) {
this.fname = fname;
hash = (fname != null) ? fname.hashCode() : 127;
this.stylesheet = stylesheet;
if (stylesheet != null) {
selectorPartitioning = new SelectorPartitioning();
final List<Rule> rules = stylesheet.getRules();
final int rMax = rules == null || rules.isEmpty() ? 0 : rules.size();
for (int r=0; r<rMax; r++) {
final Rule rule = rules.get(r);
final List<Selector> selectors = rule.getUnobservedSelectorList();
final int sMax = selectors == null || selectors.isEmpty() ? 0 : selectors.size();
for (int s=0; s < sMax; s++) {
final Selector selector = selectors.get(s);
selectorPartitioning.partition(selector);
}
}
} else {
selectorPartitioning = null;
}
this.parentUsers = new RefList<Parent>();
// this just holds a hard reference to the image
this.imageCache = new ArrayList<Image>();
this.checksum = checksum;
}
void invalidateChecksum() {
// if checksum is byte[0], then it is forever valid.
checksumInvalid = checksum.length > 0;
}
@Override
public int hashCode() {
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final StylesheetContainer other = (StylesheetContainer) obj;
if ((this.fname == null) ? (other.fname != null) : !this.fname.equals(other.fname)) {
return false;
}
return true;
}
@Override public String toString() {
return fname;
}
}
/*
* A list that holds references. Used by StylesheetContainer.
*/
// package for testing
static class RefList<K> {
final List<Reference<K>> list = new ArrayList<Reference<K>>();
void add(K key) {
for (int n=list.size()-1; 0<=n; --n) {
final Reference<K> ref = list.get(n);
final K k = ref.get();
if (k == null) {
// stale reference, remove it.
list.remove(n);
} else {
// already have it, bail
if (k == key) {
return;
}
}
}
// not found, add it.
list.add(new WeakReference<K>(key));
}
void remove(K key) {
for (int n=list.size()-1; 0<=n; --n) {
final Reference<K> ref = list.get(n);
final K k = ref.get();
if (k == null) {
// stale reference, remove it.
list.remove(n);
} else {
// already have it, bail
if (k == key) {
list.remove(n);
return;
}
}
}
}
// for unit testing
boolean contains(K key) {
for (int n=list.size()-1; 0<=n; --n) {
final Reference<K> ref = list.get(n);
final K k = ref.get();
if (k == key) {
return true;
}
}
return false;
}
}
/**
* A map from String => Stylesheet. If a stylesheet for the
* given URL has already been loaded then we'll simply reuse the stylesheet
* rather than loading a duplicate.
* This list is for author stylesheets and not for user-agent stylesheets. User-agent
* stylesheets are either platformUserAgentStylesheetContainers or userAgentStylesheetContainers
*/
// package for unit testing
final Map<String,StylesheetContainer> stylesheetContainerMap = new HashMap<>();
/**
* called from Window when the scene is closed.
*/
public void forget(final Scene scene) {
if (scene == null) return;
forget(scene.getRoot());
synchronized (styleLock) {
//
// if this scene has user-agent stylesheets, clean up the userAgentStylesheetContainers list
//
String sceneUserAgentStylesheet = null;
if ((scene.getUserAgentStylesheet() != null) &&
(!(sceneUserAgentStylesheet = scene.getUserAgentStylesheet().trim()).isEmpty())) {
for(int n=userAgentStylesheetContainers.size()-1; 0<=n; --n) {
StylesheetContainer container = userAgentStylesheetContainers.get(n);
if (sceneUserAgentStylesheet.equals(container.fname)) {
container.parentUsers.remove(scene.getRoot());
if (container.parentUsers.list.size() == 0) {
userAgentStylesheetContainers.remove(n);
}
}
}
}
//
// remove any parents belonging to this scene from the stylesheetContainerMap
//
Set<Entry<String,StylesheetContainer>> stylesheetContainers = stylesheetContainerMap.entrySet();
Iterator<Entry<String,StylesheetContainer>> iter = stylesheetContainers.iterator();
while(iter.hasNext()) {
Entry<String,StylesheetContainer> entry = iter.next();
StylesheetContainer container = entry.getValue();
Iterator<Reference<Parent>> parentIter = container.parentUsers.list.iterator();
while (parentIter.hasNext()) {
Reference<Parent> ref = parentIter.next();
Parent _parent = ref.get();
if (_parent == null || _parent.getScene() == scene || _parent.getScene() == null) {
ref.clear();
parentIter.remove();
}
}
if (container.parentUsers.list.isEmpty()) {
iter.remove();
}
}
}
}
/**
* called from Scene's stylesheets property's onChanged method
*/
public void stylesheetsChanged(Scene scene, Change<String> c) {
synchronized (styleLock) {
// Clear the cache so the cache will be rebuilt.
Set<Entry<Parent,CacheContainer>> entrySet = cacheContainerMap.entrySet();
for(Entry<Parent,CacheContainer> entry : entrySet) {
Parent parent = entry.getKey();
CacheContainer container = entry.getValue();
if (parent.getScene() == scene) {
container.clearCache();
}
}
c.reset();
while(c.next()) {
if (c.wasRemoved()) {
for (String fname : c.getRemoved()) {
stylesheetRemoved(scene, fname);
StylesheetContainer stylesheetContainer = stylesheetContainerMap.get(fname);
if (stylesheetContainer != null) {
stylesheetContainer.invalidateChecksum();
}
}
}
}
}
}
private void stylesheetRemoved(Scene scene, String fname) {
stylesheetRemoved(scene.getRoot(), fname);
}
/**
* Called from Parent's scenesChanged method when the Parent's scene is set to null.
* @param parent The Parent being removed from the scene-graph
*/
public void forget(Parent parent) {
if (parent == null) return;
synchronized (styleLock) {
// RT-34863 - clean up CSS cache when Parent is removed from scene-graph
CacheContainer removedContainer = cacheContainerMap.remove(parent);
if (removedContainer != null) {
removedContainer.clearCache();
}
final List<String> stylesheets = parent.getStylesheets();
if (stylesheets != null && !stylesheets.isEmpty()) {
for (String fname : stylesheets) {
stylesheetRemoved(parent, fname);
}
}
Iterator<Entry<String,StylesheetContainer>> containerIterator = stylesheetContainerMap.entrySet().iterator();
while (containerIterator.hasNext()) {
Entry<String,StylesheetContainer> entry = containerIterator.next();
StylesheetContainer container = entry.getValue();
container.parentUsers.remove(parent);
if (container.parentUsers.list.isEmpty()) {
containerIterator.remove();
if (container.selectorPartitioning != null) {
container.selectorPartitioning.reset();
}
// clean up image cache by removing images from the cache that
// might have come from this stylesheet
final String fname = container.fname;
cleanUpImageCache(fname);
}
}
// Do not iterate over children since this method will be called on each from Parent#scenesChanged
}
}
/**
* called from Parent's stylesheets property's onChanged method
*/
public void stylesheetsChanged(Parent parent, Change<String> c) {
synchronized (styleLock) {
c.reset();
while(c.next()) {
if (c.wasRemoved()) {
for (String fname : c.getRemoved()) {
stylesheetRemoved(parent, fname);
StylesheetContainer stylesheetContainer = stylesheetContainerMap.get(fname);
if (stylesheetContainer != null) {
stylesheetContainer.invalidateChecksum();
}
}
}
}
}
}
private void stylesheetRemoved(Parent parent, String fname) {
synchronized (styleLock) {
StylesheetContainer stylesheetContainer = stylesheetContainerMap.get(fname);
if (stylesheetContainer == null) return;
stylesheetContainer.parentUsers.remove(parent);
if (stylesheetContainer.parentUsers.list.isEmpty()) {
removeStylesheetContainer(stylesheetContainer);
}
}
}
/**
* called from Window when the scene is closed.
*/
public void forget(final SubScene subScene) {
if (subScene == null) return;
final Parent subSceneRoot = subScene.getRoot();
if (subSceneRoot == null) return;
forget(subSceneRoot);
synchronized (styleLock) {
//
// if this scene has user-agent stylesheets, clean up the userAgentStylesheetContainers list
//
String sceneUserAgentStylesheet = null;
if ((subScene.getUserAgentStylesheet() != null) &&
(!(sceneUserAgentStylesheet = subScene.getUserAgentStylesheet().trim()).isEmpty())) {
Iterator<StylesheetContainer> iterator = userAgentStylesheetContainers.iterator();
while(iterator.hasNext()) {
StylesheetContainer container = iterator.next();
if (sceneUserAgentStylesheet.equals(container.fname)) {
container.parentUsers.remove(subScene.getRoot());
if (container.parentUsers.list.size() == 0) {
iterator.remove();
}
}
}
}
//
// remove any parents belonging to this SubScene from the stylesheetContainerMap
//
// copy the list to avoid concurrent mod.
List<StylesheetContainer> stylesheetContainers = new ArrayList<>(stylesheetContainerMap.values());
Iterator<StylesheetContainer> iter = stylesheetContainers.iterator();
while(iter.hasNext()) {
StylesheetContainer container = iter.next();
Iterator<Reference<Parent>> parentIter = container.parentUsers.list.iterator();
while (parentIter.hasNext()) {
final Reference<Parent> ref = parentIter.next();
final Parent _parent = ref.get();
if (_parent != null) {
// if this stylesheet refererent is a child of this subscene, nuke it.
Parent p = _parent;
while (p != null) {
if (subSceneRoot == p.getParent()) {
ref.clear();
parentIter.remove();
forget(_parent); // _parent, not p!
break;
}
p = p.getParent();
}
}
}
// forget(_parent) will remove the container if the parentUser's list is empty
// if (container.parentUsers.list.isEmpty()) {
// iter.remove();
// }
}
}
}
private void removeStylesheetContainer(StylesheetContainer stylesheetContainer) {
if (stylesheetContainer == null) return;
synchronized (styleLock) {
final String fname = stylesheetContainer.fname;
stylesheetContainerMap.remove(fname);
if (stylesheetContainer.selectorPartitioning != null) {
stylesheetContainer.selectorPartitioning.reset();
}
// if container has no references, then remove it
for(Entry<Parent,CacheContainer> entry : cacheContainerMap.entrySet()) {
CacheContainer container = entry.getValue();
if (container == null || container.cacheMap == null || container.cacheMap.isEmpty()) {
continue;
}
List<List<String>> entriesToRemove = new ArrayList<>();
for (Entry<List<String>, Map<Key,Cache>> cacheMapEntry : container.cacheMap.entrySet()) {
List<String> cacheMapKey = cacheMapEntry.getKey();
if (cacheMapKey != null ? cacheMapKey.contains(fname) : fname == null) {
entriesToRemove.add(cacheMapKey);
}
}
if (!entriesToRemove.isEmpty()) {
for (List<String> cacheMapKey : entriesToRemove) {
Map<Key,Cache> cacheEntry = container.cacheMap.remove(cacheMapKey);
if (cacheEntry != null) {
cacheEntry.clear();
}
}
}
}
// clean up image cache by removing images from the cache that
// might have come from this stylesheet
cleanUpImageCache(fname);
final List<Reference<Parent>> parentList = stylesheetContainer.parentUsers.list;
for (int n=parentList.size()-1; 0<=n; --n) {
final Reference<Parent> ref = parentList.remove(n);
final Parent parent = ref.get();
ref.clear();
if (parent == null || parent.getScene() == null) {
continue;
}
//
// tell parent it needs to reapply css
// No harm is done if parent is in a scene that has had
// impl_reapplyCSS called on the root.
//
parent.impl_reapplyCSS();
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Image caching
//
////////////////////////////////////////////////////////////////////////////
private final Map<String,Image> imageCache = new HashMap<String,Image>();
public Image getCachedImage(String url) {
synchronized (styleLock) {
Image image = null;
if (imageCache.containsKey(url)) {
image = imageCache.get(url);
} else {
try {
image = new Image(url);
// RT-31865
if (image.isError()) {
final PlatformLogger logger = getLogger();
if (logger != null && logger.isLoggable(Level.WARNING)) {
logger.warning("Error loading image: " + url);
}
image = null;
}
imageCache.put(url, image);
} catch (IllegalArgumentException iae) {
// url was empty!
final PlatformLogger logger = getLogger();
if (logger != null && logger.isLoggable(Level.WARNING)) {
logger.warning(iae.getLocalizedMessage());
}
} catch (NullPointerException npe) {
// url was null!
final PlatformLogger logger = getLogger();
if (logger != null && logger.isLoggable(Level.WARNING)) {
logger.warning(npe.getLocalizedMessage());
}
}
}
return image;
}
}
private void cleanUpImageCache(String imgFname) {
synchronized (styleLock) {
if (imgFname == null && imageCache.isEmpty()) return;
final String fname = imgFname.trim();
if (fname.isEmpty()) return;
int len = fname.lastIndexOf('/');
final String path = (len > 0) ? fname.substring(0,len) : fname;
final int plen = path.length();
final String[] entriesToRemove = new String[imageCache.size()];
int count = 0;
final Set<Entry<String, Image>> entrySet = imageCache.entrySet();
for(Entry<String, Image> entry : entrySet) {
final String key = entry.getKey();
len = key.lastIndexOf('/');
final String kpath = (len > 0) ? key.substring(0, len) : key;
final int klen = kpath.length();
// if the longer path begins with the shorter path,
// then assume the image came from this path.
boolean match = (klen > plen) ? kpath.startsWith(path) : path.startsWith(kpath);
if (match) entriesToRemove[count++] = key;
}
for (int n=0; n<count; n++) {
Image img = imageCache.remove(entriesToRemove[n]);
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Stylesheet loading
//
////////////////////////////////////////////////////////////////////////////
private static final String skinPrefix = "com/sun/javafx/scene/control/skin/";
private static final String skinUtilsClassName = "com.sun.javafx.scene.control.skin.Utils";
private static URL getURL(final String str) {
// Note: this code is duplicated, more or less, in URLConverter
if (str == null || str.trim().isEmpty()) return null;
try {
URI uri = new URI(str.trim());
// if url doesn't have a scheme
if (uri.isAbsolute() == false) {
// Handle internal resources as a special case
if (str.startsWith(skinPrefix) &&
(str.endsWith(".css") || str.endsWith(".bss"))) {
try {
ClassLoader cl = StyleManager.class.getClassLoader();
Class<?> clz = Class.forName(skinUtilsClassName, true, cl);
Method m_getResource = clz.getMethod("getResource", String.class);
return (URL)m_getResource.invoke(null, str.substring(skinPrefix.length()));
} catch (ClassNotFoundException
| NoSuchMethodException
| IllegalAccessException
| InvocationTargetException ex) {
ex.printStackTrace();
return null;
}
}
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
final String path = uri.getPath();
URL resource = null;
if (contextClassLoader != null) {
if (path.startsWith("/")) {
resource = contextClassLoader.getResource(path.substring(1));
} else {
resource = contextClassLoader.getResource(path);
}
}
return resource;
}
// else, url does have a scheme
return uri.toURL();
} catch (MalformedURLException malf) {
// Do not log exception here - caller will handle null return.
// For example, we might be looking for a .bss that doesn't exist
return null;
} catch (URISyntaxException urise) {
return null;
}
}
// Calculate checksum for stylesheet file. Return byte[0] if checksum could not be calculated.
static byte[] calculateCheckSum(String fname) {
if (fname == null || fname.isEmpty()) return new byte[0];
try {
final URL url = getURL(fname);
// We only care about stylesheets from file: URLs.
if (url != null && "file".equals(url.getProtocol())) {
// not looking for security, just a checksum. MD5 should be faster than SHA
try (final InputStream stream = url.openStream();
final DigestInputStream dis = new DigestInputStream(stream, MessageDigest.getInstance("MD5")); ) {
dis.getMessageDigest().reset();
while (dis.read() != -1) { /* empty loop body is intentional */ }
return dis.getMessageDigest().digest();
}
}
} catch (IllegalArgumentException | NoSuchAlgorithmException | IOException | SecurityException e) {
// IOException also covers MalformedURLException
// SecurityException means some untrusted applet
// Fall through...
}
return new byte[0];
}
public static Stylesheet loadStylesheet(final String fname) {
try {
return loadStylesheetUnPrivileged(fname);
} catch (java.security.AccessControlException ace) {
/*
** we got an access control exception, so
** we could be running from an applet/jnlp/or with a security manager.
** we'll allow the app to read a css file from our runtime jar,
** and give it one more chance.
*/
/*
** check that there are enough chars after the !/ to have a valid .css or .bss file name
*/
if ((fname.length() < 7) && (fname.indexOf("!/") < fname.length()-7)) {
return null;
}
/*
**
** first check that it's actually looking for the same runtime jar
** that we're running from, and not some other file.
*/
try {
URI requestedFileUrI = new URI(fname);
/*
** is the requested file in a jar
*/
if ("jar".equals(requestedFileUrI.getScheme())) {
/*
** let's check that the css file is being requested from our
** runtime jar
*/
URI styleManagerJarURI = AccessController.doPrivileged((PrivilegedExceptionAction<URI>) () -> StyleManager.class.getProtectionDomain().getCodeSource().getLocation().toURI());
final String styleManagerJarPath = styleManagerJarURI.getSchemeSpecificPart();
String requestedFilePath = requestedFileUrI.getSchemeSpecificPart();
String requestedFileJarPart = requestedFilePath.substring(requestedFilePath.indexOf('/'), requestedFilePath.indexOf("!/"));
/*
** it's the correct jar, check it's a file access
** strip off the leading jar
*/
if (styleManagerJarPath.equals(requestedFileJarPart)) {
/*
** strip off the leading "jar",
** the css file name is past the last '!'
*/
String requestedFileJarPathNoLeadingSlash = fname.substring(fname.indexOf("!/")+2);
/*
** check that it's looking for a css file in the runtime jar
*/
if (fname.endsWith(".css") || fname.endsWith(".bss")) {
/*
** set up a read permission for the jar
*/
FilePermission perm = new FilePermission(styleManagerJarPath, "read");
PermissionCollection perms = perm.newPermissionCollection();
perms.add(perm);
AccessControlContext permsAcc = new AccessControlContext(
new ProtectionDomain[] {
new ProtectionDomain(null, perms)
});
/*
** check that the jar file exists, and that we're allowed to
** read it.
*/
JarFile jar = null;
try {
jar = AccessController.doPrivileged((PrivilegedExceptionAction<JarFile>) () -> new JarFile(styleManagerJarPath), permsAcc);
} catch (PrivilegedActionException pae) {
/*
** we got either a FileNotFoundException or an IOException
** in the privileged read. Return the same error as we
** would have returned if the css file hadn't of existed.
*/
return null;
}
if (jar != null) {
/*
** check that the file is in the jar
*/
JarEntry entry = jar.getJarEntry(requestedFileJarPathNoLeadingSlash);
if (entry != null) {
/*
** allow read access to the jar
*/
return AccessController.doPrivileged(
(PrivilegedAction<Stylesheet>) () -> loadStylesheetUnPrivileged(fname), permsAcc);
}
}
}
}
}
/*
** no matter what happen, we return the same error that would
** be returned if the css file hadn't of existed.
** That way there in no information leaked.
*/
return null;
}
/*
** no matter what happen, we return the same error that would
** be returned if the css file hadn't of existed.
** That way there in no information leaked.
*/
catch (java.net.URISyntaxException e) {
return null;
}
catch (java.security.PrivilegedActionException e) {
return null;
}
}
}
private static Stylesheet loadStylesheetUnPrivileged(final String fname) {
synchronized (styleLock) {
Boolean parse = AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
final String bss = System.getProperty("binary.css");
// binary.css is true by default.
// parse only if the file is not a .bss
// and binary.css is set to false
return (!fname.endsWith(".bss") && bss != null) ?
!Boolean.valueOf(bss) : Boolean.FALSE;
});
try {
final String ext = (parse) ? (".css") : (".bss");
java.net.URL url = null;
Stylesheet stylesheet = null;
// check if url has extension, if not then just url as is and always parse as css text
if (!(fname.endsWith(".css") || fname.endsWith(".bss"))) {
url = getURL(fname);
parse = true;
} else {
final String name = fname.substring(0, fname.length() - 4);
url = getURL(name+ext);
if (url == null && (parse = !parse)) {
// If we failed to get the URL for the .bss file,
// fall back to the .css file.
// Note that 'parse' is toggled in the test.
url = getURL(name+".css");
}
if ((url != null) && !parse) {
try {
// RT-36332: if loadBinary throws an IOException, make sure to try .css
stylesheet = Stylesheet.loadBinary(url);
} catch (IOException ioe) {
stylesheet = null;
}
if (stylesheet == null && (parse = !parse)) {
// If we failed to load the .bss file,
// fall back to the .css file.
// Note that 'parse' is toggled in the test.
url = getURL(fname);
}
}
}
// either we failed to load the .bss file, or parse
// was set to true.
if ((url != null) && parse) {
stylesheet = new CSSParser().parse(url);
}
if (stylesheet == null) {
if (errors != null) {
CssError error =
new CssError(
"Resource \""+fname+"\" not found."
);
errors.add(error);
}
if (getLogger().isLoggable(Level.WARNING)) {
getLogger().warning(
String.format("Resource \"%s\" not found.", fname)
);
}
}
// load any fonts from @font-face
if (stylesheet != null) {
faceLoop: for(FontFace fontFace: stylesheet.getFontFaces()) {
for(FontFace.FontFaceSrc src: fontFace.getSources()) {
if (src.getType() == FontFace.FontFaceSrcType.URL) {
Font loadedFont = Font.loadFont(src.getSrc(),10);
if (loadedFont == null) {
getLogger().info("Could not load @font-face font [" + src.getSrc() + "]");
}
continue faceLoop;
}
}
}
}
return stylesheet;
} catch (FileNotFoundException fnfe) {
if (errors != null) {
CssError error =
new CssError(
"Stylesheet \""+fname+"\" not found."
);
errors.add(error);
}
if (getLogger().isLoggable(Level.INFO)) {
getLogger().info("Could not find stylesheet: " + fname);//, fnfe);
}
} catch (IOException ioe) {
if (errors != null) {
CssError error =
new CssError(
"Could not load stylesheet: " + fname
);
errors.add(error);
}
if (getLogger().isLoggable(Level.INFO)) {
getLogger().info("Could not load stylesheet: " + fname);//, ioe);
}
}
return null;
}
}
////////////////////////////////////////////////////////////////////////////
//
// User Agent stylesheet handling
//
////////////////////////////////////////////////////////////////////////////
/**
* Set a bunch of user agent stylesheets all at once. The order of the stylesheets in the list
* is the order of their styles in the cascade. Passing null, an empty list, or a list full of empty
* strings does nothing.
*
* @param urls The list of stylesheet URLs as Strings.
*/
public void setUserAgentStylesheets(List<String> urls) {
if (urls == null || urls.size() == 0) return;
synchronized (styleLock) {
// Avoid resetting user agent stylesheets if they haven't changed.
if (urls.size() == platformUserAgentStylesheetContainers.size()) {
boolean isSame = true;
for (int n=0, nMax=urls.size(); n < nMax && isSame; n++) {
final String url = urls.get(n);
final String fname = (url != null) ? url.trim() : null;
if (fname == null || fname.isEmpty()) break;
StylesheetContainer container = platformUserAgentStylesheetContainers.get(n);
// assignment in this conditional is intentional!
if(isSame = fname.equals(container.fname)) {
// don't use fname in calculateCheckSum since it is just the key to
// find the StylesheetContainer. Rather, use the URL of the
// stylesheet that was already loaded. For example, we could have
// fname = "com/sun/javafx/scene/control/skin/modena/modena.css, but
// the stylesheet URL could be jar:file://some/path/!com/sun/javafx/scene/control/skin/modena/modena.bss
String stylesheetUrl = container.stylesheet.getUrl();
byte[] checksum = calculateCheckSum(stylesheetUrl);
isSame = Arrays.equals(checksum, container.checksum);
}
}
if (isSame) return;
}
boolean modified = false;
for (int n=0, nMax=urls.size(); n < nMax; n++) {
final String url = urls.get(n);
final String fname = (url != null) ? url.trim() : null;
if (fname == null || fname.isEmpty()) continue;
if (!modified) {
// we have at least one non null or non-empty url
platformUserAgentStylesheetContainers.clear();
modified = true;
}
if (n==0) {
_setDefaultUserAgentStylesheet(fname);
} else {
_addUserAgentStylesheet(fname);
}
}
if (modified) {
userAgentStylesheetsChanged();
}
}
}
/**
* Add a user agent stylesheet, possibly overriding styles in the default
* user agent stylesheet.
*
* @param fname The file URL, either relative or absolute, as a String.
*/
public void addUserAgentStylesheet(String fname) {
addUserAgentStylesheet(null, fname);
}
/**
* Add a user agent stylesheet, possibly overriding styles in the default
* user agent stylesheet.
* @param scene Only used in CssError for tracking back to the scene that loaded the stylesheet
* @param url The file URL, either relative or absolute, as a String.
*/
// For RT-20643
public void addUserAgentStylesheet(Scene scene, String url) {
final String fname = (url != null) ? url.trim() : null;
if (fname == null || fname.isEmpty()) {
return;
}
synchronized (styleLock) {
// RT-20643
CssError.setCurrentScene(scene);
if (_addUserAgentStylesheet(fname)) {
userAgentStylesheetsChanged();
}
// RT-20643
CssError.setCurrentScene(null);
}
}
// fname is assumed to be non null and non empty
private boolean _addUserAgentStylesheet(String fname) {
synchronized (styleLock) {
// if we already have this stylesheet, bail
for (int n=0, nMax= platformUserAgentStylesheetContainers.size(); n < nMax; n++) {
StylesheetContainer container = platformUserAgentStylesheetContainers.get(n);
if (fname.equals(container.fname)) {
return false;
}
}
final Stylesheet ua_stylesheet = loadStylesheet(fname);
if (ua_stylesheet == null) return false;
ua_stylesheet.setOrigin(StyleOrigin.USER_AGENT);
platformUserAgentStylesheetContainers.add(new StylesheetContainer(fname, ua_stylesheet));
return true;
}
}
/**
* Add a user agent stylesheet, possibly overriding styles in the default
* user agent stylesheet.
* @param scene Only used in CssError for tracking back to the scene that loaded the stylesheet
* @param ua_stylesheet The stylesheet to add as a user-agent stylesheet
*/
public void addUserAgentStylesheet(Scene scene, Stylesheet ua_stylesheet) {
if (ua_stylesheet == null ) {
throw new IllegalArgumentException("null arg ua_stylesheet");
}
// null url is ok, just means that it is a stylesheet not loaded from a file
String url = ua_stylesheet.getUrl();
final String fname = url != null ? url.trim() : "";
synchronized (styleLock) {
// if we already have this stylesheet, bail
for (int n=0, nMax= platformUserAgentStylesheetContainers.size(); n < nMax; n++) {
StylesheetContainer container = platformUserAgentStylesheetContainers.get(n);
if (fname.equals(container.fname)) {
return;
}
}
// RT-20643
CssError.setCurrentScene(scene);
platformUserAgentStylesheetContainers.add(new StylesheetContainer(fname, ua_stylesheet));
if (ua_stylesheet != null) {
ua_stylesheet.setOrigin(StyleOrigin.USER_AGENT);
}
userAgentStylesheetsChanged();
// RT-20643
CssError.setCurrentScene(null);
}
}
/**
* Set the default user agent stylesheet.
*
* @param fname The file URL, either relative or absolute, as a String.
*/
public void setDefaultUserAgentStylesheet(String fname) {
setDefaultUserAgentStylesheet(null, fname);
}
/**
* Set the default user agent stylesheet
* @param scene Only used in CssError for tracking back to the scene that loaded the stylesheet
* @param url The file URL, either relative or absolute, as a String.
*/
// For RT-20643
public void setDefaultUserAgentStylesheet(Scene scene, String url) {
final String fname = (url != null) ? url.trim() : null;
if (fname == null || fname.isEmpty()) {
return;
}
synchronized (styleLock) {
// RT-20643
CssError.setCurrentScene(scene);
if(_setDefaultUserAgentStylesheet(fname)) {
userAgentStylesheetsChanged();
}
// RT-20643
CssError.setCurrentScene(null);
}
}
// fname is expected to be non null and non empty
private boolean _setDefaultUserAgentStylesheet(String fname) {
synchronized (styleLock) {
// if we already have this stylesheet, make sure it is the first element
for (int n=0, nMax= platformUserAgentStylesheetContainers.size(); n < nMax; n++) {
StylesheetContainer container = platformUserAgentStylesheetContainers.get(n);
if (fname.equals(container.fname)) {
if (n > 0) {
platformUserAgentStylesheetContainers.remove(n);
if (hasDefaultUserAgentStylesheet) {
platformUserAgentStylesheetContainers.set(0, container);
} else {
platformUserAgentStylesheetContainers.add(0, container);
}
}
// return true only if platformUserAgentStylesheetContainers was modified
return n > 0;
}
}
final Stylesheet ua_stylesheet = loadStylesheet(fname);
if (ua_stylesheet == null) return false;
ua_stylesheet.setOrigin(StyleOrigin.USER_AGENT);
final StylesheetContainer sc = new StylesheetContainer(fname, ua_stylesheet);
if (platformUserAgentStylesheetContainers.size() == 0) {
platformUserAgentStylesheetContainers.add(sc);
}
else if (hasDefaultUserAgentStylesheet) {
platformUserAgentStylesheetContainers.set(0,sc);
}
else {
platformUserAgentStylesheetContainers.add(0,sc);
}
hasDefaultUserAgentStylesheet = true;
return true;
}
}
/**
* Removes the specified stylesheet from the application default user agent
* stylesheet list.
* @param url The file URL, either relative or absolute, as a String.
*/
public void removeUserAgentStylesheet(String url) {
final String fname = (url != null) ? url.trim() : null;
if (fname == null || fname.isEmpty()) {
return;
}
synchronized (styleLock) {
// if we already have this stylesheet, remove it!
boolean removed = false;
for (int n = platformUserAgentStylesheetContainers.size() - 1; n >= 0; n--) {
// don't remove the platform default user agent stylesheet
if (fname.equals(Application.getUserAgentStylesheet())) {
continue;
}
StylesheetContainer container = platformUserAgentStylesheetContainers.get(n);
if (fname.equals(container.fname)) {
platformUserAgentStylesheetContainers.remove(n);
removed = true;
}
}
if (removed) {
userAgentStylesheetsChanged();
}
}
}
/**
* Set the user agent stylesheet. This is the base default stylesheet for
* the platform
*/
public void setDefaultUserAgentStylesheet(Stylesheet ua_stylesheet) {
if (ua_stylesheet == null ) {
return;
}
// null url is ok, just means that it is a stylesheet not loaded from a file
String url = ua_stylesheet.getUrl();
final String fname = url != null ? url.trim() : "";
synchronized (styleLock) {
// if we already have this stylesheet, make sure it is the first element
for (int n=0, nMax= platformUserAgentStylesheetContainers.size(); n < nMax; n++) {
StylesheetContainer container = platformUserAgentStylesheetContainers.get(n);
if (fname.equals(container.fname)) {
if (n > 0) {
platformUserAgentStylesheetContainers.remove(n);
if (hasDefaultUserAgentStylesheet) {
platformUserAgentStylesheetContainers.set(0, container);
} else {
platformUserAgentStylesheetContainers.add(0, container);
}
}
return;
}
}
StylesheetContainer sc = new StylesheetContainer(fname, ua_stylesheet);
if (platformUserAgentStylesheetContainers.size() == 0) {
platformUserAgentStylesheetContainers.add(sc);
} else if (hasDefaultUserAgentStylesheet) {
platformUserAgentStylesheetContainers.set(0,sc);
} else {
platformUserAgentStylesheetContainers.add(0,sc);
}
hasDefaultUserAgentStylesheet = true;
ua_stylesheet.setOrigin(StyleOrigin.USER_AGENT);
userAgentStylesheetsChanged();
}
}
/*
* If the userAgentStylesheets change, then all scenes are updated.
*/
private void userAgentStylesheetsChanged() {
List<Parent> parents = new ArrayList<>();
synchronized (styleLock) {
for (CacheContainer container : cacheContainerMap.values()) {
container.clearCache();
}
StyleConverterImpl.clearCache();
for (Parent root : cacheContainerMap.keySet()) {
if (root == null) {
continue;
}
parents.add(root);
}
}
for (Parent root : parents) root.impl_reapplyCSS();
}
private List<StylesheetContainer> processStylesheets(List<String> stylesheets, Parent parent) {
synchronized (styleLock) {
final List<StylesheetContainer> list = new ArrayList<StylesheetContainer>();
for (int n = 0, nMax = stylesheets.size(); n < nMax; n++) {
final String fname = stylesheets.get(n);
StylesheetContainer container = null;
if (stylesheetContainerMap.containsKey(fname)) {
container = stylesheetContainerMap.get(fname);
if (!list.contains(container)) {
// minor optimization: if existing checksum in byte[0], then don't bother recalculating
if (container.checksumInvalid) {
final byte[] checksum = calculateCheckSum(fname);
if (!Arrays.equals(checksum, container.checksum)) {
removeStylesheetContainer(container);
// Stylesheet did change. Re-load the stylesheet and update the container map.
Stylesheet stylesheet = loadStylesheet(fname);
container = new StylesheetContainer(fname, stylesheet, checksum);
stylesheetContainerMap.put(fname, container);
} else {
container.checksumInvalid = false;
}
}
list.add(container);
}
// RT-22565: remember that this parent or scene uses this stylesheet.
// Later, if the cache is cleared, the parent or scene is told to
// reapply css.
container.parentUsers.add(parent);
} else {
final Stylesheet stylesheet = loadStylesheet(fname);
// stylesheet may be null which would mean that some IOException
// was thrown while trying to load it. Add it to the
// stylesheetContainerMap anyway as this will prevent further
// attempts to parse the file
container = new StylesheetContainer(fname, stylesheet);
// RT-22565: remember that this parent or scene uses this stylesheet.
// Later, if the cache is cleared, the parent or scene is told to
// reapply css.
container.parentUsers.add(parent);
stylesheetContainerMap.put(fname, container);
list.add(container);
}
}
return list;
}
}
//
// recurse so that stylesheets of Parents closest to the root are
// added to the list first. The ensures that declarations for
// stylesheets further down the tree (closer to the leaf) have
// a higher ordinal in the cascade.
//
private List<StylesheetContainer> gatherParentStylesheets(final Parent parent) {
if (parent == null) {
return Collections.<StylesheetContainer>emptyList();
}
final List<String> parentStylesheets = parent.impl_getAllParentStylesheets();
if (parentStylesheets == null || parentStylesheets.isEmpty()) {
return Collections.<StylesheetContainer>emptyList();
}
synchronized (styleLock) {
// RT-20643
CssError.setCurrentScene(parent.getScene());
final List<StylesheetContainer> list = processStylesheets(parentStylesheets, parent);
// RT-20643
CssError.setCurrentScene(null);
return list;
}
}
//
//
//
private List<StylesheetContainer> gatherSceneStylesheets(final Scene scene) {
if (scene == null) {
return Collections.<StylesheetContainer>emptyList();
}
final List<String> sceneStylesheets = scene.getStylesheets();
if (sceneStylesheets == null || sceneStylesheets.isEmpty()) {
return Collections.<StylesheetContainer>emptyList();
}
synchronized (styleLock) {
// RT-20643
CssError.setCurrentScene(scene);
final List<StylesheetContainer> list = processStylesheets(sceneStylesheets, scene.getRoot());
// RT-20643
CssError.setCurrentScene(null);
return list;
}
}
// reuse key to avoid creation of numerous small objects
private Key key = null;
/**
* Finds matching styles for this Node.
*/
public StyleMap findMatchingStyles(Node node, SubScene subScene, Set<PseudoClass>[] triggerStates) {
final Scene scene = node.getScene();
if (scene == null) {
return StyleMap.EMPTY_MAP;
}
CacheContainer cacheContainer = getCacheContainer(node, subScene);
if (cacheContainer == null) {
assert false : node.toString();
return StyleMap.EMPTY_MAP;
}
synchronized (styleLock) {
final Parent parent =
(node instanceof Parent)
? (Parent) node : node.getParent();
final List<StylesheetContainer> parentStylesheets =
gatherParentStylesheets(parent);
final boolean hasParentStylesheets = parentStylesheets.isEmpty() == false;
final List<StylesheetContainer> sceneStylesheets = gatherSceneStylesheets(scene);
final boolean hasSceneStylesheets = sceneStylesheets.isEmpty() == false;
final String inlineStyle = node.getStyle();
final boolean hasInlineStyles = inlineStyle != null && inlineStyle.trim().isEmpty() == false;
final String sceneUserAgentStylesheet = scene.getUserAgentStylesheet();
final boolean hasSceneUserAgentStylesheet =
sceneUserAgentStylesheet != null && sceneUserAgentStylesheet.trim().isEmpty() == false;
final String subSceneUserAgentStylesheet =
(subScene != null) ? subScene.getUserAgentStylesheet() : null;
final boolean hasSubSceneUserAgentStylesheet =
subSceneUserAgentStylesheet != null && subSceneUserAgentStylesheet.trim().isEmpty() == false;
String regionUserAgentStylesheet = null;
// is this node in a region that has its own stylesheet?
Node region = node;
while (region != null) {
regionUserAgentStylesheet = (region instanceof Region) ? ((Region) region).getUserAgentStylesheet() : null;
if (regionUserAgentStylesheet != null) {
// We want 'region' to be the node that has the user agent stylesheet.
// 'region' is used below - look for if (hasRegionUserAgentStylesheet) block
break;
}
region = region.getParent();
}
final boolean hasRegionUserAgentStylesheet =
regionUserAgentStylesheet != null && regionUserAgentStylesheet.trim().isEmpty() == false;
//
// Are there any stylesheets at all?
// If not, then there is nothing to match and the
// resulting StyleMap is going to end up empty
//
if (hasInlineStyles == false
&& hasParentStylesheets == false
&& hasSceneStylesheets == false
&& hasSceneUserAgentStylesheet == false
&& hasSubSceneUserAgentStylesheet == false
&& hasRegionUserAgentStylesheet == false
&& platformUserAgentStylesheetContainers.isEmpty()) {
return StyleMap.EMPTY_MAP;
}
final String cname = node.getTypeSelector();
final String id = node.getId();
final List<String> styleClasses = node.getStyleClass();
if (key == null) {
key = new Key();
}
key.className = cname;
key.id = id;
for(int n=0, nMax=styleClasses.size(); n<nMax; n++) {
final String styleClass = styleClasses.get(n);
if (styleClass == null || styleClass.isEmpty()) continue;
key.styleClasses.add(StyleClassSet.getStyleClass(styleClass));
}
Map<Key, Cache> cacheMap = cacheContainer.getCacheMap(parentStylesheets,regionUserAgentStylesheet);
Cache cache = cacheMap.get(key);
if (cache != null) {
// key will be reused, so clear the styleClasses for next use
key.styleClasses.clear();
} else {
// If the cache is null, then we need to create a new Cache and
// add it to the cache map
// Construct the list of Selectors that could possibly apply
final List<Selector> selectorData = new ArrayList<>();
// User agent stylesheets have lowest precedence and go first
if (hasSubSceneUserAgentStylesheet || hasSceneUserAgentStylesheet) {
// if has both, use SubScene
final String uaFileName = hasSubSceneUserAgentStylesheet ?
subScene.getUserAgentStylesheet().trim() :
scene.getUserAgentStylesheet().trim();
StylesheetContainer container = null;
for (int n=0, nMax=userAgentStylesheetContainers.size(); n<nMax; n++) {
container = userAgentStylesheetContainers.get(n);
if (uaFileName.equals(container.fname)) {
break;
}
container = null;
}
if (container == null) {
Stylesheet stylesheet = loadStylesheet(uaFileName);
if (stylesheet != null) {
stylesheet.setOrigin(StyleOrigin.USER_AGENT);
}
container = new StylesheetContainer(uaFileName, stylesheet);
userAgentStylesheetContainers.add(container);
}
if (container.selectorPartitioning != null) {
final Parent root = hasSubSceneUserAgentStylesheet ? subScene.getRoot() : scene.getRoot();
container.parentUsers.add(root);
final List<Selector> matchingRules =
container.selectorPartitioning.match(id, cname, key.styleClasses);
selectorData.addAll(matchingRules);
}
} else if (platformUserAgentStylesheetContainers.isEmpty() == false) {
for(int n=0, nMax= platformUserAgentStylesheetContainers.size(); n<nMax; n++) {
final StylesheetContainer container = platformUserAgentStylesheetContainers.get(n);
if (container != null && container.selectorPartitioning != null) {
final List<Selector> matchingRules =
container.selectorPartitioning.match(id, cname, key.styleClasses);
selectorData.addAll(matchingRules);
}
}
}
if (hasRegionUserAgentStylesheet) {
// Unfortunate duplication of code from previous block. No time to refactor.
StylesheetContainer container = null;
for (int n=0, nMax=userAgentStylesheetContainers.size(); n<nMax; n++) {
container = userAgentStylesheetContainers.get(n);
if (regionUserAgentStylesheet.equals(container.fname)) {
break;
}
container = null;
}
if (container == null) {
Stylesheet stylesheet = loadStylesheet(regionUserAgentStylesheet);
if (stylesheet != null) {
stylesheet.setOrigin(StyleOrigin.USER_AGENT);
}
container = new StylesheetContainer(regionUserAgentStylesheet, stylesheet);
userAgentStylesheetContainers.add(container);
}
if (container.selectorPartitioning != null) {
// Depending on RefList add method not allowing duplicates.
container.parentUsers.add((Parent)region);
final List<Selector> matchingRules =
container.selectorPartitioning.match(id, cname, key.styleClasses);
selectorData.addAll(matchingRules);
}
}
// Scene stylesheets come next since declarations from
// parent stylesheets should take precedence.
if (sceneStylesheets.isEmpty() == false) {
for(int n=0, nMax=sceneStylesheets.size(); n<nMax; n++) {
final StylesheetContainer container = sceneStylesheets.get(n);
if (container != null && container.selectorPartitioning != null) {
final List<Selector> matchingRules =
container.selectorPartitioning.match(id, cname, key.styleClasses);
selectorData.addAll(matchingRules);
}
}
}
// lastly, parent stylesheets
if (hasParentStylesheets) {
final int nMax = parentStylesheets == null ? 0 : parentStylesheets.size();
for(int n=0; n<nMax; n++) {
final StylesheetContainer container = parentStylesheets.get(n);
if (container.selectorPartitioning != null) {
final List<Selector> matchingRules =
container.selectorPartitioning.match(id, cname, key.styleClasses);
selectorData.addAll(matchingRules);
}
}
}
// create a new Cache from these selectors.
cache = new Cache(selectorData);
cacheMap.put(key, cache);
// cause a new Key to be created the next time this method is called
key = null;
}
//
// Create a style helper for this node from the styles that match.
//
StyleMap smap = cache.getStyleMap(cacheContainer, node, triggerStates, hasInlineStyles);
return smap;
}
}
////////////////////////////////////////////////////////////////////////////
//
// CssError reporting
//
////////////////////////////////////////////////////////////////////////////
private static ObservableList<CssError> errors = null;
/**
* Errors that may have occurred during css processing.
* This list is null until errorsProperty() is called.
*
* NOTE: this is not thread-safe, and cannot readily be made so given the
* nature of the API.
* Currently it is only used by SceneBuilder. If a public API is ever
* needed, then a new API should be designed.
*
* @return
*/
public static ObservableList<CssError> errorsProperty() {
if (errors == null) {
errors = FXCollections.observableArrayList();
}
return errors;
}
/**
* Errors that may have occurred during css processing.
* This list is null until errorsProperty() is called and is used
* internally to figure out whether or not anyone is interested in
* receiving CssError.
* Not meant for general use - call errorsProperty() instead.
* @return
*/
public static ObservableList<CssError> getErrors() {
return errors;
}
////////////////////////////////////////////////////////////////////////////
//
// Classes and routines for mapping styles to a Node
//
////////////////////////////////////////////////////////////////////////////
private static List<String> cacheMapKey;
// Each Scene has its own cache
// package for testing
static class CacheContainer {
private Map<StyleCache.Key,StyleCache> getStyleCache() {
if (styleCache == null) styleCache = new HashMap<StyleCache.Key, StyleCache>();
return styleCache;
}
private Map<Key,Cache> getCacheMap(List<StylesheetContainer> parentStylesheets, String regionUserAgentStylesheet) {
if (cacheMap == null) {
cacheMap = new HashMap<List<String>,Map<Key,Cache>>();
}
synchronized (styleLock) {
if ((parentStylesheets == null || parentStylesheets.isEmpty()) &&
(regionUserAgentStylesheet == null || regionUserAgentStylesheet.isEmpty())) {
Map<Key,Cache> cmap = cacheMap.get(null);
if (cmap == null) {
cmap = new HashMap<Key,Cache>();
cacheMap.put(null, cmap);
}
return cmap;
} else {
final int nMax = parentStylesheets.size();
if (cacheMapKey == null) {
cacheMapKey = new ArrayList<String>(nMax);
}
for (int n=0; n<nMax; n++) {
StylesheetContainer sc = parentStylesheets.get(n);
if (sc == null || sc.fname == null || sc.fname.isEmpty()) continue;
cacheMapKey.add(sc.fname);
}
if (regionUserAgentStylesheet != null) {
cacheMapKey.add(regionUserAgentStylesheet);
}
Map<Key,Cache> cmap = cacheMap.get(cacheMapKey);
if (cmap == null) {
cmap = new HashMap<Key,Cache>();
cacheMap.put(cacheMapKey, cmap);
// create a new cacheMapKey the next time this method is called
cacheMapKey = null;
} else {
// reuse cacheMapKey, but not the data, the next time this method is called
cacheMapKey.clear();
}
return cmap;
}
}
}
private List<StyleMap> getStyleMapList() {
if (styleMapList == null) styleMapList = new ArrayList<StyleMap>();
return styleMapList;
}
private int nextSmapId() {
styleMapId = baseStyleMapId + getStyleMapList().size();
return styleMapId;
}
private void addStyleMap(StyleMap smap) {
getStyleMapList().add(smap);
}
public StyleMap getStyleMap(int smapId) {
final int correctedId = smapId - baseStyleMapId;
if (0 <= correctedId && correctedId < getStyleMapList().size()) {
return getStyleMapList().get(correctedId);
}
return StyleMap.EMPTY_MAP;
}
private void clearCache() {
if (cacheMap != null) cacheMap.clear();
if (styleCache != null) styleCache.clear();
if (styleMapList != null) styleMapList.clear();
baseStyleMapId = styleMapId;
// 7/8ths is totally arbitrary
if (baseStyleMapId > Integer.MAX_VALUE/8*7) {
baseStyleMapId = styleMapId = 0;
}
}
/**
* Get the mapping of property to style from Node.style for this node.
*/
private Selector getInlineStyleSelector(String inlineStyle) {
// If there are no styles for this property then we can just bail
if ((inlineStyle == null) || inlineStyle.trim().isEmpty()) return null;
if (inlineStylesCache != null && inlineStylesCache.containsKey(inlineStyle)) {
// Value of Map entry may be null!
return inlineStylesCache.get(inlineStyle);
}
//
// inlineStyle wasn't in the inlineStylesCache, or inlineStylesCache was null
//
if (inlineStylesCache == null) {
inlineStylesCache = new HashMap<>();
}
final Stylesheet inlineStylesheet =
new CSSParser().parse("*{"+inlineStyle+"}");
if (inlineStylesheet != null) {
inlineStylesheet.setOrigin(StyleOrigin.INLINE);
List<Rule> rules = inlineStylesheet.getRules();
Rule rule = rules != null && !rules.isEmpty() ? rules.get(0) : null;
List<Selector> selectors = rule != null ? rule.getUnobservedSelectorList() : null;
Selector selector = selectors != null && !selectors.isEmpty() ? selectors.get(0) : null;
// selector might be null if parser throws some exception
if (selector != null) {
selector.setOrdinal(-1);
inlineStylesCache.put(inlineStyle, selector);
return selector;
}
// if selector is null, fall through
}
// even if selector is null, put it in cache so we don't
// bother with trying to parse it again.
inlineStylesCache.put(inlineStyle, null);
return null;
}
private Map<StyleCache.Key,StyleCache> styleCache;
private Map<List<String>, Map<Key,Cache>> cacheMap;
private List<StyleMap> styleMapList;
/**
* Cache of parsed, inline styles. The key is Node.style.
* The value is the Selector from the inline stylesheet.
*/
private Map<String,Selector> inlineStylesCache;
/*
* A simple counter used to generate a unique id for a StyleMap.
* This unique id is used by StyleHelper in figuring out which
* style cache to use.
*/
private int styleMapId = 0;
// When the cache is cleared, styleMapId counting begins here.
// If a StyleHelper calls getStyleMap with an id less than the
// baseStyleMapId, then that StyleHelper is working with an old
// cache and is no longer valid.
private int baseStyleMapId = 0;
}
/**
* Creates and caches maps of styles, reusing them as often as practical.
*/
private static class Cache {
private static class Key {
final long[] key;
final String inlineStyle;
Key(long[] key, String inlineStyle) {
this.key = key;
// let inlineStyle be null if it is empty
this.inlineStyle = (inlineStyle != null && inlineStyle.trim().isEmpty() ? null : inlineStyle);
}
@Override public String toString() {
return Arrays.toString(key) + (inlineStyle != null ? "* {" + inlineStyle + "}" : "");
}
@Override
public int hashCode() {
int hash = 3;
hash = 17 * hash + Arrays.hashCode(this.key);
if (inlineStyle != null) hash = 17 * hash + inlineStyle.hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Key other = (Key) obj;
if (inlineStyle == null ? other.inlineStyle != null : !inlineStyle.equals(other.inlineStyle)) {
return false;
}
if (!Arrays.equals(this.key, other.key)) {
return false;
}
return true;
}
}
// this must be initialized to the appropriate possible selectors when
// the helper cache is created by the StylesheetContainer. Note that
// SelectorPartioning sorts the matched selectors by ordinal, so this
// list of selectors will be in the same order in which the selectors
// appear in the stylesheets.
private final List<Selector> selectors;
private final Map<Key, Integer> cache;
Cache(List<Selector> selectors) {
this.selectors = selectors;
this.cache = new HashMap<Key, Integer>();
}
private StyleMap getStyleMap(CacheContainer cacheContainer, Node node, Set<PseudoClass>[] triggerStates, boolean hasInlineStyle) {
if ((selectors == null || selectors.isEmpty()) && !hasInlineStyle) {
return StyleMap.EMPTY_MAP;
}
final int selectorDataSize = selectors.size();
//
// Since the list of selectors is found by matching only the
// rightmost selector, the set of selectors may larger than those
// selectors that actually match the node. The following loop
// whittles the list down to those selectors that apply.
//
//
// To lookup from the cache, we construct a key from a Long
// where the selectors that match this particular node are
// represented by bits on the long[].
//
long key[] = new long[selectorDataSize/Long.SIZE + 1];
boolean nothingMatched = true;
for (int s = 0; s < selectorDataSize; s++) {
final Selector sel = selectors.get(s);
//
// This particular flavor of applies takes a PseudoClassState[]
// fills in the pseudo-class states from the selectors where
// they apply to a node. This is an expedient to looking the
// applies loopa second time on the matching selectors. This has to
// be done ahead of the cache lookup since not all nodes that
// have the same set of selectors will have the same node hierarchy.
//
// For example, if I have .foo:hover:focused .bar:selected {...}
// and the "bar" node is 4 away from the root and the foo
// node is two away from the root, pseudoclassBits would be
// [selected, 0, hover:focused, 0]
// Note that the states run from leaf to root. This is how
// the code in StyleHelper expects things.
// Note also that, if the selector does not apply, the triggerStates
// is unchanged.
//
if (sel.applies(node, triggerStates, 0)) {
final int index = s / Long.SIZE;
final long mask = key[index] | 1l << s;
key[index] = mask;
nothingMatched = false;
}
}
// nothing matched!
if (nothingMatched && hasInlineStyle == false) {
return StyleMap.EMPTY_MAP;
}
final String inlineStyle = node.getStyle();
final Key keyObj = new Key(key, inlineStyle);
if (cache.containsKey(keyObj)) {
Integer styleMapId = cache.get(keyObj);
final StyleMap styleMap = styleMapId != null
? cacheContainer.getStyleMap(styleMapId.intValue())
: StyleMap.EMPTY_MAP;
return styleMap;
}
final List<Selector> selectors = new ArrayList<>();
if (hasInlineStyle) {
Selector selector = cacheContainer.getInlineStyleSelector(inlineStyle);
if (selector != null) selectors.add(selector);
}
for (int k = 0; k<key.length; k++) {
if (key[k] == 0) continue;
final int offset = k * Long.SIZE;
for (int b = 0; b<Long.SIZE; b++) {
// bit at b in key[k] set?
final long mask = 1l << b;
if ((mask & key[k]) != mask) continue;
final Selector pair = this.selectors.get(offset + b);
selectors.add(pair);
}
}
int id = cacheContainer.nextSmapId();
cache.put(keyObj, Integer.valueOf(id));
final StyleMap styleMap = new StyleMap(id, selectors);
cacheContainer.addStyleMap(styleMap);
return styleMap;
}
}
/**
* The key used in the cacheMap of the StylesheetContainer
*/
private static class Key {
// note that the class name here is the *full* class name, such as
// javafx.scene.control.Button. We only bother parsing this down to the
// last part when doing matching against selectors, and so want to avoid
// having to do a bunch of preliminary parsing in places where it isn't
// necessary.
String className;
String id;
final StyleClassSet styleClasses;
private Key() {
styleClasses = new StyleClassSet();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof Key) {
Key other = (Key)o;
if (className == null ? other.className != null : (className.equals(other.className) == false)) {
return false;
}
if (id == null ? other.id != null : (id.equals(other.id) == false)) {
return false;
}
return this.styleClasses.equals(other.styleClasses);
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (this.className != null ? this.className.hashCode() : 0);
hash = 29 * hash + (this.id != null ? this.id.hashCode() : 0);
hash = 29 * hash + this.styleClasses.hashCode();
return hash;
}
}
}
| 38.618965
| 194
| 0.530653
|
998af3b982b2342feb08dae845ead4fee865f4d1
| 1,490
|
package advent;
import java.io.IOException;
public class Day17 {
private static final int FINAL_VALUE_A = 2017;
private static final int FINAL_VALUE_B = 50_000_000;
public static void main(String[] args) throws IOException {
int stepSize = Integer.parseInt(FileUtility.fileToString("input/17.txt"));
// Part one
Node headA = buildList(stepSize, FINAL_VALUE_A);
FileUtility.printAndOutput(find(headA, FINAL_VALUE_A).next.value, "output/17A.txt");
// Part two
// Awfully slow. Maybe there's a way to make the "steps" take constant time?
Node headB = buildList(stepSize, FINAL_VALUE_B);
FileUtility.printAndOutput(headB.next.value, "output/17B.txt");
}
private static class Node {
public final int value;
public Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
private static Node buildList(int stepSize, int finalValue) {
Node head = new Node(0, null);
head.next = head;
Node current = head;
for (int i = 1; i <= finalValue; i++) {
// Step forward n times
for (int j = 0; j < stepSize; j++) {
current = current.next;
}
// Insert
Node insert = new Node(i, current.next);
current.next = insert;
current = insert;
}
return head;
}
private static Node find(Node head, int value) {
Node current = head;
do {
if (current.value == value) {
return current;
}
current = current.next;
} while (current != head);
return null;
}
}
| 22.575758
| 86
| 0.663758
|
26c8d1eb89a5de3f069adb6c58ee49aef1acd829
| 8,342
|
package edu.uoregon.casls.aris_android.models;
import android.content.Context;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import edu.uoregon.casls.aris_android.GamePlayActivity;
import edu.uoregon.casls.aris_android.Utilities.AppConfig;
import edu.uoregon.casls.aris_android.data_objects.Game;
import edu.uoregon.casls.aris_android.data_objects.Instance;
import edu.uoregon.casls.aris_android.data_objects.Item;
import edu.uoregon.casls.aris_android.data_objects.User;
/**
* Created by smorison on 8/20/15.
*/
public class PlayerInstancesModel extends ARISModel {
public Map<Long, Instance> playerInstances = new LinkedHashMap<>();
public Map<Long, Instance> inventory = new LinkedHashMap<>(); // to be instantiated later and parcel to logic.
public Map<Long, Instance> attributes = new LinkedHashMap<>(); // todo: is this an array of "Item" or something else?
public int currentWeight;
// instead of mPlayer representing the player obj as in iOS we'll just grab a reference to it when instantiated
// public User mPlayer;
// public ItemsModel mItemsModel;
// public InstancesModel mInstancesModel;
// public transient Game mGame;
// private Context mContext;
// private GamePlayActivity mGamePlayAct;
// private LogsModel mLogsModel;
public transient GamePlayActivity mGamePlayAct;
// todo - reform the constructor into the initContext version.
public void PlayerInstancesModel(Context context, User player, ItemsModel items, Game game, InstancesModel instancesModel) { // todo: does player want to be of type playerModel instead of Player?
// mContext = context;
// mGamePlayAct = (GamePlayActivity) mContext;
// mPlayer = player; // remember: Java passes objects by reference, so mPlayer IS the same object passed in.
// mItemsModel = items;
// mInstancesModel = instancesModel;
// mGame = game;
}
public void initContext(GamePlayActivity gamePlayAct) {
mGamePlayAct = gamePlayAct; // todo: may need leak checking is activity gets recreated.
}
// public void clearGameData() {
// n_maintenance_data_received = 0;
// }
public void clearPlayerData() {
playerInstances.clear();
this.invalidateCaches();
currentWeight = 0;
}
public void invalidateCaches() {
inventory.clear();
attributes.clear();
}
public void requestMaintenanceData() {
this.touchPlayerInstances();
}
public void clearMaintenanceData() {
n_maintenance_data_received = 0;
}
public long nMaintenanceDataToReceive() {
return 1;
}
public void playerInstancesTouched() { // called after response received to touchItemsForPlayer via Dispatcher.services_player_instances_touched()
n_maintenance_data_received++;
mGamePlayAct.mDispatch.model_player_instances_touched(); // _ARIS_NOTIF_SEND_(@"MODEL_PLAYER_INSTANCES_TOUCHED",nil,nil);
mGamePlayAct.mDispatch.maintenance_piece_available(); //_ARIS_NOTIF_SEND_(@"MAINTENANCE_PIECE_AVAILABLE",nil,nil);
}
public void touchPlayerInstances() {
mGamePlayAct.mAppServices.touchItemsForPlayer();
// call (via two messages) Game.gamePieceReceived() // todo: check for completeness
}
/*{
NSArray *newInstances = [_MODEL_INSTANCES_ playerInstances];
[self clearPlayerData];
Instance *newInstance;
for(long i = 0; i < newInstances.count; i++)
{
newInstance = newInstances[i];
if(![newInstance.object_type isEqualToString:@"ITEM"] || newInstance.owner_id != _MODEL_PLAYER_.user_id) continue;
playerInstances[[NSNumber numberWithLong:newInstance.object_id]] = newInstance;
}
_ARIS_NOTIF_SEND_(@"MODEL_PLAYER_INSTANCES_AVAILABLE",nil,nil);
}
*/
public void playerInstancesAvailable(Map<String, List<Map<String, Object>>> playerDeltas) {
List<Instance> newInstances = new ArrayList<>();
newInstances = mGamePlayAct.mGame.instancesModel.playerInstances();
// NSArray *newInstances = [_MODEL_INSTANCES_ playerInstances];
this.clearPlayerData();
// Instance newInstance;
for (Instance newInstance : newInstances) {
if(!newInstance.object_type.contentEquals("ITEM") || newInstance.owner_id != Long.parseLong(mGamePlayAct.mPlayer.user_id)) continue;
playerInstances.put(newInstance.object_id, newInstance);
}
// Notify Attributes and Inventory Views of new stuff.
mGamePlayAct.mDispatch.model_player_instances_available(); // _ARIS_NOTIF_SEND_(@"MODEL_PLAYER_INSTANCES_AVAILABLE",nil,nil);
}
public void calculateWeight() {
currentWeight = 0;
Collection<Instance> insts;
insts = playerInstances.values();
for (Instance inst : insts) {
if (inst.object_type.contentEquals("ITEM")) {
Item item = mGamePlayAct.mGame.itemsModel.itemForId(inst.object_id);
currentWeight += item.weight * inst.qty;
}
}
}
public long dropItemFromPlayer (long item_id, long qty) {
Instance pII = playerInstances.get(item_id);
if (pII == null) return 0; //UH OH! NO INSTANCE TO TAKE ITEM FROM! (shouldn't happen if touchItemsForPlayer was called...)
if (pII.qty < qty) qty = pII.qty;
if (!mGamePlayAct.mGame.network_level.contentEquals("LOCAL")) {
mGamePlayAct.dropItem(item_id, qty); // todo send message back to GamePlayActivity to make this call. TESTTESTTTEST this..
}
return this.takeItemFromPlayer(item_id, qty);
}
public long takeItemFromPlayer(long item_id, long qty) {
Instance pII = playerInstances.get(item_id);
if (pII == null) return 0; //UH OH! NO INSTANCE TO TAKE ITEM FROM! (shouldn't happen if touchItemsForPlayer was called...)
if (pII.qty < qty) qty = pII.qty;
return this.setItemsForPlayer(item_id, pII.qty-qty);
}
public long giveItemToPlayer(long item_id, long qty) {
Instance pII = playerInstances.get(item_id);
if (pII == null) return 0; //UH OH! NO INSTANCE TO GIVE ITEM TO! (shouldn't happen if touchItemsForPlayer was called...)
if (qty > this.qtyAllowedToGiveForItem(item_id)) qty = this.qtyAllowedToGiveForItem(item_id);
return this.setItemsForPlayer(item_id, pII.qty + qty);
}
public long setItemsForPlayer(long item_id, long qty) {
// Log.d(AppConfig.LOGTAG_D2, "PlayerInstanceModel. setItemsForPlayer " + item_id + ", " + qty);
Instance pII = playerInstances.get(item_id);
if (pII == null) return 0; //UH OH! NO INSTANCE TO GIVE ITEM TO! (shouldn't happen if touchItemsForPlayer was called...)
if (qty < 0) qty = 0;
if (qty-pII.qty > this.qtyAllowedToGiveForItem(item_id)) qty = pII.qty + this.qtyAllowedToGiveForItem(item_id);
long oldQty = pII.qty;
mGamePlayAct.mGame.instancesModel.setQtyForInstanceId(pII.instance_id, qty);
if (qty > oldQty) mGamePlayAct.mGame.logsModel.playerReceivedItemId(item_id, qty);
if (qty < oldQty) mGamePlayAct.mGame.logsModel.playerLostItemId(item_id, qty);
return qty;
}
public long qtyOwnedForItem(long item_id) {
return playerInstances.get(item_id).qty;
}
public long qtyOwnedForTag(long tag_id) {
long q = 0;
List<Long> item_ids = mGamePlayAct.mGame.tagsModel.objectIdsOfType("ITEM" , tag_id);
for (int i = 0; i < item_ids.size(); i++)
q += this.qtyOwnedForItem(item_ids.get(i));
return q;
}
public long qtyAllowedToGiveForItem(long item_id) {
this.calculateWeight();
Item i = mGamePlayAct.mGame.itemsModel.itemForId(item_id);
long amtMoreCanHold = i.max_qty_in_inventory-this.qtyOwnedForItem(item_id);
while(mGamePlayAct.mGame.inventory_weight_cap > 0 &&
(amtMoreCanHold*i.weight + currentWeight) > mGamePlayAct.mGame.inventory_weight_cap)
amtMoreCanHold--;
return amtMoreCanHold;
}
public Map<Long, Instance> inventory() {
if(inventory != null && inventory.size() > 0) return inventory;
inventory = new LinkedHashMap<Long, Instance>();
Collection<Instance> instancearray = playerInstances.values();
for (Instance inst : instancearray) {
Item item = (Item) inst.object();
if (item.type.contentEquals("NORMAL") || item.type.contentEquals("URL"))
inventory.put(inst.instance_id, inst);
}
return inventory;
}
public Map<Long, Instance> attributes() {
if(attributes != null) return attributes;
attributes = new LinkedHashMap<>();
Collection<Instance> instancearray = playerInstances.values();
for (Instance inst : instancearray) {
Item item = (Item) inst.object();
if (item.type.contentEquals("ATTRIB"))
attributes.put(inst.instance_id, inst);
}
return attributes;
}
}
| 35.497872
| 196
| 0.748382
|
dd5c027d6a2cc8c53ea699676e259d34a522d500
| 546
|
package net.energy.exception;
/**
* 队列任务未正常返回时抛出此异常
*
* @author wuqh
*
*/
public class TaskNotReturnException extends RuntimeException {
private static final long serialVersionUID = -5775094087402819132L;
public TaskNotReturnException() {
super();
}
public TaskNotReturnException(String message, Throwable cause) {
super(message, cause);
}
public TaskNotReturnException(String message) {
super(message);
}
public TaskNotReturnException(Throwable cause) {
super(cause);
}
}
| 16.545455
| 69
| 0.684982
|
e59343eed2cd4390c49140c62c96b7517694aaf2
| 262
|
package com.hughbone.playerpig;
public interface PlayerPigExt {
void setPlayerName(String name);
void setPlayerUUID(String uuid);
String getPlayerName();
String getPlayerUUID();
boolean isPlayerPig();
void setPlayerPig(boolean setPP);
}
| 23.818182
| 37
| 0.732824
|
23637ce6586bbb137d762d20d4a2ffe27634d7a2
| 483
|
package nl.weeaboo.vn;
import org.junit.Assert;
import nl.weeaboo.vn.math.Vec2;
/**
* General purpose assertions.
*/
public final class ApiTestUtil {
public static final double EPSILON = 0.001;
private ApiTestUtil() {
}
/**
* Fuzzy equals for {@link Vec2}.
*/
public static void assertEquals(double x, double y, Vec2 vec, double epsilon) {
Assert.assertEquals(x, vec.x, epsilon);
Assert.assertEquals(y, vec.y, epsilon);
}
}
| 18.576923
| 83
| 0.641822
|
80f27b039307b3dad4b8374f8fc9d4ed39dbf6f8
| 665
|
package org.tain;
import org.tain.working.BookObjectWorking;
import org.tain.working.ReflectWorking;
public class KieaAnnotation04Main {
private static boolean flag = true;
public static void main(String[] args) throws Exception {
if (!flag) job01(); // reflect
if (flag) job02(); // BookObject and PageObject
}
////////////////////////////////////////////////////////////////////
private static void job01() {
if (!flag) ReflectWorking.test001();
if (flag) ReflectWorking.test002();
}
////////////////////////////////////////////////////////////////////
private static void job02() {
if (flag) BookObjectWorking.test001();
}
}
| 22.931034
| 69
| 0.554887
|
1c651de7f772c54cffa2cd33093538c7de7f5e08
| 1,656
|
package com.netcompany.fagarbeid.aspektsikkerhet;
import com.netcompany.fagarbeid.aspektsikkerhet.security.Secured;
import com.netcompany.fagarbeid.aspektsikkerhet.security.predicates.SecurityPredicate;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class SecuredTestUtil {
public static void checkSecuredOnMethod(Object object,
String methodName,
Class<? extends SecurityPredicate>... predicates) {
final Method[] declaredMethods = object.getClass().getDeclaredMethods();
final List<Method> matchingMethods = Arrays.stream(declaredMethods)
.filter(m -> m.getName().equals(methodName))
.collect(Collectors.toList());
if (matchingMethods.size() != 1) {
throw new IllegalStateException("Found " + matchingMethods.size() + " methods named " + methodName + " on " + object.getClass().getName());
}
final Secured annotation = matchingMethods.get(0).getAnnotation(Secured.class);
if (annotation == null) {
throw new IllegalStateException("No Secured annotation on method " + methodName + " on " + object.getClass().getName());
}
final List<Class<? extends SecurityPredicate>> predicatesOnMethod = Arrays.asList(annotation.value());
final List<Class<? extends SecurityPredicate>> predicatesExpected = Arrays.asList(predicates);
assertThat(predicatesOnMethod).isEqualTo(predicatesExpected);
}
}
| 42.461538
| 151
| 0.681763
|
e6e5d7898bce3433e26872eea46b431a82396b71
| 1,741
|
package org.jdfs.tracker.handler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.handler.demux.MessageHandler;
import org.jdfs.commons.request.JdfsRequestConstants;
import org.jdfs.tracker.request.FileInfoResponse;
import org.jdfs.tracker.request.ReadFileInfoRequest;
import org.jdfs.tracker.service.FileInfo;
import org.jdfs.tracker.service.FileInfoService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
* 读取文件信息消息处理器
*
* @author James Quan
* @version 2015年2月3日 下午5:15:29
*/
public class ReadFileInfoMessageHandler implements
MessageHandler<ReadFileInfoRequest>, InitializingBean {
private FileInfoService fileInfoService;
public FileInfoService getFileInfoService() {
return fileInfoService;
}
public void setFileInfoService(FileInfoService fileInfoService) {
this.fileInfoService = fileInfoService;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(fileInfoService, "fileInfoService is required!");
}
@Override
public void handleMessage(IoSession session, ReadFileInfoRequest message)
throws Exception {
long id = message.getId();
FileInfo file = fileInfoService.getFileInfo(id);
FileInfoResponse resp;
if (file == null) {
resp = new FileInfoResponse();
resp.setBatchId(message.getBatchId());
resp.setStatus(JdfsRequestConstants.STATUS_FILE_NOT_FOUND);
} else {
resp = new FileInfoResponse();
resp.setBatchId(message.getBatchId());
resp.setStatus(JdfsRequestConstants.STATUS_OK);
resp.setId(file.getId());
resp.setName(file.getName());
resp.setSize(file.getSize());
resp.setLastModified(file.getLastModified().getMillis());
}
session.write(resp);
}
}
| 30.017241
| 74
| 0.780011
|
457a4f8c17b3278427a63ab70fcf70d6dd214ed8
| 300
|
package in.bugzy.data.remote.model;
public class LoginData {
protected String token;
public LoginData(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| 16.666667
| 40
| 0.61
|
215c58a31493afe6b640f4a0698e8a31b140f67c
| 3,874
|
/*
* Copyright 2018-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb.stitch.android.examples.todosync;
import java.util.Date;
import org.bson.BsonBoolean;
import org.bson.BsonDateTime;
import org.bson.BsonDocument;
import org.bson.BsonObjectId;
import org.bson.BsonReader;
import org.bson.BsonString;
import org.bson.BsonWriter;
import org.bson.codecs.BsonDocumentCodec;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.types.ObjectId;
class TodoItem {
public static final String TODO_LIST_DATABASE = "todo";
public static final String TODO_LIST_COLLECTION = "items";
private final ObjectId id;
private final String ownerId;
private final String task;
private final boolean checked;
private Date doneDate;
/** Constructs a todo item from a MongoDB document. */
TodoItem(
final ObjectId id,
final String ownerId,
final String task,
final boolean checked,
final Date doneDate
) {
this.id = id;
this.ownerId = ownerId;
this.task = task;
this.checked = checked;
this.doneDate = doneDate;
}
public ObjectId getId() {
return id;
}
public String getOwnerId() {
return ownerId;
}
public String getTask() {
return task;
}
public Boolean isChecked() {
return checked;
}
public Date getDoneDate() {
return doneDate;
}
static BsonDocument toBsonDocument(final TodoItem item) {
final BsonDocument asDoc = new BsonDocument();
asDoc.put(Fields.ID, new BsonObjectId(item.getId()));
asDoc.put(Fields.OWNER_ID, new BsonString(item.getOwnerId()));
asDoc.put(Fields.TASK, new BsonString(item.getTask()));
asDoc.put(Fields.CHECKED, new BsonBoolean(item.isChecked()));
if (item.getDoneDate() != null) {
asDoc.put(Fields.DONE_DATE, new BsonDateTime(item.getDoneDate().getTime()));
}
return asDoc;
}
static TodoItem fromBsonDocument(final BsonDocument doc) {
final Date doneDate;
if (doc.containsKey(Fields.DONE_DATE)) {
doneDate = new Date(doc.getDateTime(Fields.DONE_DATE).getValue());
} else {
doneDate = null;
}
return new TodoItem(
doc.getObjectId(Fields.ID).getValue(),
doc.getString(Fields.OWNER_ID).getValue(),
doc.getString(Fields.TASK).getValue(),
doc.getBoolean(Fields.CHECKED).getValue(),
doneDate
);
}
static final class Fields {
static final String ID = "_id";
static final String OWNER_ID = "owner_id";
static final String TASK = "task";
static final String CHECKED = "checked";
static final String DONE_DATE = "done_date";
}
public static final Codec<TodoItem> codec = new Codec<TodoItem>() {
@Override
public void encode(
final BsonWriter writer, final TodoItem value, final EncoderContext encoderContext) {
new BsonDocumentCodec().encode(writer, toBsonDocument(value), encoderContext);
}
@Override
public Class<TodoItem> getEncoderClass() {
return TodoItem.class;
}
@Override
public TodoItem decode(
final BsonReader reader, final DecoderContext decoderContext) {
final BsonDocument document = (new BsonDocumentCodec()).decode(reader, decoderContext);
return fromBsonDocument(document);
}
};
}
| 28.277372
| 93
| 0.7016
|
632746ae1c82ad0d71d98ed22a161279a9feeacb
| 4,608
|
package org.observe;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A default implementation of observable
*
* @param <T> The type of values this observable provides
*/
public class DefaultObservable<T> implements Observable<T> {
/**
* Listens for subscriptions to an observable
*
* @param <T> The type of observable to listen for subscriptions to
*/
public static interface OnSubscribe<T> {
/** @param observer The new observer on the observable */
void onsubscribe(Observer<? super T> observer);
}
private OnSubscribe<T> theOnSubscribe;
private AtomicBoolean isAlive = new AtomicBoolean(true);
private AtomicBoolean hasIssuedController = new AtomicBoolean(false);
private Queue<Observer<? super T>> theListeners;
/** Creates the observable */
public DefaultObservable() {
/* Java's ConcurrentLinkedQueue has a problem (for me) that makes the class unusable here. As documented in fireNext() below, the
* behavior of observables is advertised such that if a listener is added by a listener, the new listener will be added at the end
* of the listeners and will be notified for the currently firing value. ConcurrentLinkedQueue allows for this except when the
* listener adding the new listener was previously the last listener in the queue. ConcurrentLinkedQueue's iterator looks ahead in
* the next() method, not hasNext(); so if a listener returned by that iterator adds another value to the queue, that iterator will
* not see it.
* That's why the following line is commented out and replaced with a possibly less efficient but more predictable implementation of
* mine.
*/
// theListeners = new ConcurrentLinkedQueue<>();
theListeners = new org.qommons.LinkedQueue<>();
}
/**
* Obtains control of the observable. This method may only be called once.
*
* @param onSubscribe The listener to call for each new subscription to the observable
* @return An observer whose methods control this observable
* @throws IllegalStateException If this observer is already controlled
*/
public Observer<T> control(OnSubscribe<T> onSubscribe) throws IllegalStateException {
if(hasIssuedController.getAndSet(true))
throw new IllegalStateException("This observable is already controlled");
theOnSubscribe = onSubscribe;
return new Observer<T>(){
@Override
public <V extends T> void onNext(V value) {
fireNext(value);
}
@Override
public <V extends T> void onCompleted(V value) {
fireCompleted(value);
}
@Override
public void onError(Throwable e) {
fireError(e);
}
};
}
@Override
public Subscription subscribe(Observer<? super T> observer) {
if(!isAlive.get()) {
observer.onCompleted(null);
return () -> {
};
} else {
theListeners.add(observer);
if(theOnSubscribe != null)
theOnSubscribe.onsubscribe(observer);
return () -> {
theListeners.remove(observer);
};
}
}
private void fireNext(T value) {
if(!isAlive.get())
throw new IllegalStateException("Firing a value on a completed observable");
// This allows listeners to be added by listeners. Those new listeners will be fired last.
for(Observer<? super T> observer : theListeners) {
try {
observer.onNext(value);
} catch(Throwable e) {
observer.onError(e);
}
}
}
private void fireCompleted(T value) {
if(isAlive.getAndSet(false)) {
Observer<? super T> [] observers = theListeners.toArray(new Observer[theListeners.size()]);
theListeners.clear();
for(Observer<? super T> observer : observers) {
try {
observer.onCompleted(value);
} catch(Throwable e) {
observer.onError(e);
}
}
}
}
private void fireError(Throwable e) {
if(!isAlive.get())
throw new IllegalStateException("Firing a value on a completed observable");
for(Observer<? super T> observer : theListeners)
observer.onError(e);
}
@Override
public boolean isSafe() {
return false;
}
/**
* Clones this value into a new observable that is NOT yet controlled. Note that this class does not implement {@link Cloneable}, so
* subclasses will need to implement Cloneable for this method to not throw the {@link CloneNotSupportedException}
*/
@Override
protected DefaultObservable<T> clone() throws CloneNotSupportedException {
DefaultObservable<T> ret = (DefaultObservable<T>) super.clone();
// ret.theListeners = new ConcurrentLinkedQueue<>();
ret.theListeners = new org.qommons.LinkedQueue<>();
ret.isAlive = new AtomicBoolean(true);
ret.hasIssuedController = new AtomicBoolean(false);
return ret;
}
}
| 32.914286
| 134
| 0.720269
|
62d25e249c0f9f2b010aff23a8f79c40a6466b5e
| 1,166
|
package io.soluble.pjb.script;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import junit.framework.TestCase;
public class TestException extends TestCase {
public TestException(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void test() throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine e = manager.getEngineByName("php");
OutputStream out = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(out);
e.getContext().setWriter(w);
e.getContext().setErrorWriter(w);
try {
e.eval("<?php bleh();?>");
} catch (ScriptException ex) {
if (out.toString().length() == 0) throw new Exception("test failed");
return;
}
fail("test failed");
}
}
| 26.5
| 81
| 0.651801
|
998bd7876a017caeb561c4a388b7a45bb9ba5752
| 939
|
package com.lezhin.test.vo;
import java.io.Serializable;
public class UserVO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3564282308084883008L;
private int userId = 0;
private String name = null;
private String showName = null;
private String apiAccessKey = null;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShowName() {
return showName;
}
public void setShowName(String showName) {
this.showName = showName;
}
public String getApiAccessKey() {
return apiAccessKey;
}
public void setApiAccessKey(String apiAccessKey) {
this.apiAccessKey = apiAccessKey;
}
}
| 18.78
| 70
| 0.623003
|
88a5ef2925efc2919a83a519da7ef2e226be5da7
| 3,814
|
package com.example.demosecurityweb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
// Disables standard security configuration
@EnableWebSecurity
public class DemoSecurityWebApplication {
public static final Logger log = LoggerFactory.getLogger(DemoSecurityWebApplication.class);
public static void main(String[] args) {
SpringApplication.run(DemoSecurityWebApplication.class, args);
}
@GetMapping("/service")
public String service() {
return "service";
}
@GetMapping("/user/service")
public String userService() {
return "user service";
}
@GetMapping("/admin/service")
public String appService() {
return "admin Service";
}
// TODO use method security (for managed operations)
// This adapter is only used for spring-web tomcat based deployment
@Configuration
public class BasicConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
log.info("init web security {}", web);
}
// Only works with DAOAuthenticationProvider
// If other type of authentication manager is used - ignored
// @Bean
// @Override
// public UserDetailsService userDetailsService() {
// log.info("configuring user details service");
// UserDetails user =
// User.withDefaultPasswordEncoder()
// .username("user")
// .password("password")
// .roles("USER")
// .build();
//
// return new InMemoryUserDetailsManager(user);
// }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO use apache DS server
// TODO use LDAP authentication
// https://memorynotfound.com/spring-security-spring-ldap-authentication-example/
// auth
// .ldapAuthentication()
// .userDnPatterns("uid={0},ou=people")
// .groupSearchBase("ou=groups");
// Using noop password encoder (store password as plain text)
// https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#pe-dpe
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}admin").roles("USER", "ADMIN");
log.info("init auth manager {}", auth);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// TODO different auth type - basic, form, etc. ?
http
.authorizeRequests()
.antMatchers("/service").permitAll()
.antMatchers("/actuator/*").hasRole("ADMIN")
.antMatchers("/admin/*").hasRole("ADMIN")
.anyRequest().authenticated() // Other requests
.and()
.httpBasic();
log.info("init http security {}", http);
}
}
}
| 33.752212
| 107
| 0.753802
|
45bc600ba77e219042b9c62146b0797bd236ecc8
| 5,861
|
/*
* Copyright (c) 2021 - for information on the respective copyright owner
* see the NOTICE file and/or the repository https://github.com/carbynestack/amphora.
*
* SPDX-License-Identifier: Apache-2.0
*/
package io.carbynestack.amphora.service.calculation;
import static io.carbynestack.castor.common.entities.TupleType.INPUT_MASK_GFP;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import io.carbynestack.amphora.common.MaskedInput;
import io.carbynestack.amphora.common.MaskedInputData;
import io.carbynestack.amphora.common.SecretShare;
import io.carbynestack.amphora.common.Tag;
import io.carbynestack.amphora.service.config.SpdzProperties;
import io.carbynestack.castor.common.entities.*;
import io.carbynestack.mpspdz.integration.MpSpdzIntegrationUtils;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
public class SecretShareUtilTest {
private final UUID testSecretId = UUID.fromString("3bcf8308-8f50-4d24-a37b-b0075bb5e779");
private SpdzProperties spdzProperties;
private SecretShareUtil secretShareUtil;
private MpSpdzIntegrationUtils spdzUtil;
@Before
public void prepare() {
spdzProperties = new SpdzProperties();
spdzProperties.setPrime(new BigInteger("198766463529478683931867765928436695041"));
spdzProperties.setR(new BigInteger("141515903391459779531506841503331516415"));
spdzProperties.setRInv(new BigInteger("133854242216446749056083838363708373830"));
spdzUtil =
MpSpdzIntegrationUtils.of(
spdzProperties.getPrime(), spdzProperties.getR(), spdzProperties.getRInv());
secretShareUtil = new SecretShareUtil(spdzUtil);
}
@Test
public void
givenLessInputMasksThanMaskedInput_whenConvertToSecretShare_thenThrowIllegalArgumentException() {
List<MaskedInputData> maskedInputDataList = new ArrayList<>();
maskedInputDataList.add(MaskedInputData.of(new byte[MpSpdzIntegrationUtils.WORD_WIDTH]));
TupleList inputMaskList =
new TupleList(INPUT_MASK_GFP.getTupleCls(), INPUT_MASK_GFP.getField());
MaskedInput maskedInput =
new MaskedInput(
UUID.fromString("93448822-fc76-4989-a927-450486ae0a08"),
maskedInputDataList,
new ArrayList<>());
IllegalArgumentException iae =
assertThrows(
IllegalArgumentException.class,
() -> secretShareUtil.convertToSecretShare(maskedInput, "", inputMaskList, false));
assertEquals("Received more input data than available inputMasks.", iae.getMessage());
}
@Test
public void givenCorrectArguments_whenConvertToSecretShare_thenReturnExpectedResult() {
List<Tag> tags =
Arrays.asList(
Tag.builder().key("key1").value("value1").build(),
Tag.builder().key("key2").value("value3").build());
BigInteger macKey =
new BigInteger("-33717010807885571165607137982809795379").mod(spdzProperties.getPrime());
List<MaskedInputData> maskedInputData =
maskedInputDataToList(
new BigInteger("37371993412255263319479925008425883363").mod(spdzProperties.getPrime()),
new BigInteger("0"));
MaskedInput maskedInput = new MaskedInput(testSecretId, maskedInputData, tags);
TupleList inputMasks =
inputMaskToList(
makeInputMask(
new BigInteger("-82730997414791468496799367418496881908")
.mod(spdzProperties.getPrime()),
new BigInteger("-60557275363670854182192939229091375859")
.mod(spdzProperties.getPrime())),
makeInputMask(
new BigInteger("45359004002536205186084333850157344582")
.mod(spdzProperties.getPrime()),
new BigInteger("-48604663536222227589564560476962533035")
.mod(spdzProperties.getPrime())));
SecretShare expectedSecretShare =
makeSecretShare(
testSecretId,
tags,
new BigInteger("-45359004002536205177319442410070998545")
.mod(spdzProperties.getPrime()),
new BigInteger("-170814686092998134911558977038957876158")
.mod(spdzProperties.getPrime()),
new BigInteger("45359004002536205186084333850157344582").mod(spdzProperties.getPrime()),
new BigInteger("-48604663536222227589564560476962533035")
.mod(spdzProperties.getPrime()));
assertEquals(
expectedSecretShare,
secretShareUtil.convertToSecretShare(maskedInput, macKey.toString(), inputMasks, false));
}
private List<MaskedInputData> maskedInputDataToList(BigInteger... maskedInputs) {
List<MaskedInputData> maskedInputList = new ArrayList<>();
for (BigInteger bi : maskedInputs) {
maskedInputList.add(MaskedInputData.of(spdzUtil.toGfp(bi)));
}
return maskedInputList;
}
private TupleList inputMaskToList(InputMask... inputMasks) {
TupleList inputMaskList =
new TupleList(TupleType.INPUT_MASK_GFP.getTupleCls(), TupleType.INPUT_MASK_GFP.getField());
inputMaskList.addAll(Arrays.asList(inputMasks));
return inputMaskList;
}
private InputMask makeInputMask(BigInteger value, BigInteger key) {
Share share = new Share(spdzUtil.toGfp(value), spdzUtil.toGfp(key));
InputMask inputMask = new InputMask(Field.GFP, share);
return inputMask;
}
private SecretShare makeSecretShare(UUID secretId, List<Tag> tags, BigInteger... words) {
ByteBuffer bb = ByteBuffer.allocate(words.length * MpSpdzIntegrationUtils.WORD_WIDTH);
for (BigInteger word : words) {
bb.put(spdzUtil.toGfp(word));
}
return SecretShare.builder().secretId(secretId).data(bb.array()).tags(tags).build();
}
}
| 42.471014
| 103
| 0.722744
|
2963fa02a975fad7d85df4112e105fe257da6206
| 3,601
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.math;
import org.apache.mahout.math.function.Functions;
import org.junit.Test;
public class WeightedVectorTest extends AbstractVectorTest {
@Test
public void testLength() {
Vector v = new DenseVector(new double[]{0.9921337470551008, 1.0031004325833064, 0.9963963182745947});
Centroid c = new Centroid(3, new DenseVector(v), 2);
assertEquals(c.getVector().getLengthSquared(), c.getLengthSquared(), 1.0e-17);
// previously, this wouldn't clear the cached squared length value correctly which would cause bad distances
c.set(0, -1);
System.out.printf("c = %.9f\nv = %.9f\n", c.getLengthSquared(), c.getVector().getLengthSquared());
assertEquals(c.getVector().getLengthSquared(), c.getLengthSquared(), 1.0e-17);
}
@Override
public Vector vectorToTest(int size) {
return new WeightedVector(new DenseVector(size), 4.52, 345);
}
@Test
public void testOrdering() {
WeightedVector v1 = new WeightedVector(new DenseVector(new double[]{1, 2, 3}), 5.41, 31);
WeightedVector v2 = new WeightedVector(new DenseVector(new double[]{1, 2, 3}), 5.00, 31);
WeightedVector v3 = new WeightedVector(new DenseVector(new double[]{1, 3, 3}), 5.00, 31);
WeightedVector v4 = (WeightedVector) v1.clone();
WeightedVectorComparator comparator = new WeightedVectorComparator();
assertTrue(comparator.compare(v1, v2) > 0);
assertTrue(comparator.compare(v3, v1) < 0);
assertTrue(comparator.compare(v3, v2) > 0);
assertEquals(0, comparator.compare(v4, v1));
assertEquals(0, comparator.compare(v1, v1));
}
@Test
public void testProjection() {
Vector v1 = new DenseVector(10).assign(Functions.random());
WeightedVector v2 = new WeightedVector(v1, v1, 31);
assertEquals(v1.dot(v1), v2.getWeight(), 1.0e-13);
assertEquals(31, v2.getIndex());
Matrix y = new DenseMatrix(10, 4).assign(Functions.random());
Matrix q = new QRDecomposition(y.viewPart(0, 10, 0, 3)).getQ();
Vector nullSpace = y.viewColumn(3).minus(q.times(q.transpose().times(y.viewColumn(3))));
WeightedVector v3 = new WeightedVector(q.viewColumn(0).plus(q.viewColumn(1)), nullSpace, 1);
assertEquals(0, v3.getWeight(), 1.0e-13);
Vector qx = q.viewColumn(0).plus(q.viewColumn(1)).normalize();
WeightedVector v4 = new WeightedVector(qx, q.viewColumn(0), 2);
assertEquals(Math.sqrt(0.5), v4.getWeight(), 1.0e-13);
WeightedVector v5 = WeightedVector.project(q.viewColumn(0), qx);
assertEquals(Math.sqrt(0.5), v5.getWeight(), 1.0e-13);
}
@Override
public void testSize() {
assertEquals("size", 3, getTestVector().getNumNonZeroElements());
}
@Override
Vector generateTestVector(int cardinality) {
return new WeightedVector(new DenseVector(cardinality), 3.14, 53);
}
}
| 40.460674
| 112
| 0.709803
|
d128a1ffa71a0c399f7a6266d6b52cc1256c6c31
| 654
|
package com.taoyuanx.auth.token.exception;
/**
* token失效异常
*/
public class TokenCancelException extends RuntimeException {
private static final long serialVersionUID = 8793672380339632040L;
private Integer errorCode;
public TokenCancelException(String msg) {
super(msg);
}
public TokenCancelException(Integer errorCode, String msg) {
super(msg);
if (errorCode != null) {
this.errorCode = errorCode;
}
}
public Integer getErrorCode() {
return errorCode;
}
public TokenCancelException(String message, Throwable cause) {
super(message, cause);
}
}
| 21.096774
| 70
| 0.655963
|
faa939b4350f539b8803e4f04d8df53f33b2a54a
| 1,194
|
package org.opencds.cqf.cql.engine.elm.execution;
import org.opencds.cqf.cql.engine.exception.InvalidOperatorArgument;
import org.opencds.cqf.cql.engine.execution.Context;
import org.opencds.cqf.cql.engine.runtime.DateTime;
import org.opencds.cqf.cql.engine.runtime.TemporalHelper;
/*
timezoneoffset from(argument DateTime) Decimal
NOTE: this is within the purview of DateTimeComponentFrom
Description available in that class
*/
public class TimezoneOffsetFromEvaluator extends org.cqframework.cql.elm.execution.TimezoneOffsetFrom {
public static Object timezoneOffsetFrom(Object operand) {
if (operand == null) {
return null;
}
if (operand instanceof DateTime) {
return TemporalHelper.zoneToOffset(((DateTime) operand).getDateTime().getOffset());
}
throw new InvalidOperatorArgument(
"TimezoneOffsetFrom(DateTime)",
String.format("TimezoneOffsetFrom(%s)", operand.getClass().getName())
);
}
@Override
protected Object internalEvaluate(Context context) {
Object operand = getOperand().evaluate(context);
return timezoneOffsetFrom(operand);
}
}
| 31.421053
| 103
| 0.710218
|
e4224c6757b8e3a3163df1992b1c7b9502d21943
| 418
|
package fricore;
public class FrLiteralArr4 extends FrLiteral
{
public FrLiteralArr4(FrVMImage img,
FrBytePointer cs, FrBytePointer cse)
{
FrBytePointer ct;
int a, n;
int i, j, k;
this.img=img;
n=cse.sub(cs)/4;
a=img.tryAllocData(n*4);
this.addr=img.vaData+a;
ct=new FrBytePointer(img.sec_data, a, img.mszData);
for(i=0; i<n; i++)
{
j=cs.getsi(i);
ct.seti_le(i, j);
}
}
}
| 15.481481
| 53
| 0.636364
|
9407ec39da573fe4fbb28c78b1cc2efb156056f3
| 533
|
package cn.org.autumn.modules.test.site;
import cn.org.autumn.menu.Menu;
import cn.org.autumn.base.ModuleMenu;
import org.springframework.stereotype.Service;
/**
* 测试例子
*
* @author User
* @email henryxm@163.com
* @date 2021-08
*/
@Service
@Menu(name = "测试例子", order = 0, ico = "fa-file-code-o")
public class TestMenu extends ModuleMenu {
public String[][] getLanguageItems() {
String[][] items = new String[][]{
{getLanguageKey(), "测试例子", "Test Example"},
};
return items;
}
}
| 22.208333
| 59
| 0.628518
|
22000bd38fe449d8a729fdec4aef710b747c02b9
| 1,936
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class p11_Students_Joined_to_Specialties {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<StudentSpeciality> students = new ArrayList<>();
List<StudentSpeciality> studentsSpeciality = new ArrayList<>();
while (true) {
String[] line = reader.readLine().split("\\s+");
if ("Students:".equalsIgnoreCase(line[0])) {
break;
}
studentsSpeciality.add(new StudentSpeciality(line[0] + " " + line[1], line[2]));
}
while (true) {
String[] line = reader.readLine().split("\\s+");
if ("END".equalsIgnoreCase(line[0])) {
break;
}
students.add(new StudentSpeciality(line[1] + " " + line[2], line[0]));
}
students.stream().sorted(Comparator.comparing(StudentSpeciality::getName))
.forEach(st -> studentsSpeciality.stream()
.filter((spec) -> spec.getNumber().equalsIgnoreCase(st.getNumber()))
.forEach(speciality -> System.out.printf("%s %s %s\n",
st.getName(), st.getNumber(), speciality.getName())));
}
}
class StudentSpeciality {
private String name;
private String number;
StudentSpeciality(String _name, String numb) {
this.setName(_name);
this.setNumber(numb);
}
String getName() {
return this.name;
}
private void setName(String name) {
this.name = name;
}
String getNumber() {
return this.number;
}
private void setNumber(String number) {
this.number = number;
}
}
| 29.784615
| 92
| 0.585227
|
03c2af0af802cf9e8e154c8d201ac8556fbf1213
| 677
|
package ticketsystem.service.factory;
import ticketsystem.service.CustomApplicationConfig;
import ticketsystem.service.logic.ITeamManager;
import ticketsystem.service.logic.TeamManager;
import ticketsystem.service.repository.team.ITeamContext;
public class TeamManagerFactory {
public static ITeamManager CreateTeamManager(){
ITeamContext context = TeamContextFactory.createTeamContext(CustomApplicationConfig.DATA_ENVIRONMENT);
return new TeamManager(context);
}
public static ITeamManager CreateTeamManager(String type){
ITeamContext context = TeamContextFactory.createTeamContext(type);
return new TeamManager(context);
}
}
| 37.611111
| 110
| 0.799114
|
b216107b33be81ce9637c51b085f8c471845284b
| 1,721
|
package com.wangfan.ioc.overview.container;
import com.wangfan.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
/**
* @author <a href="mailto:wangfan1996love@gmail">wf</a>
* @since 2021-08-30
*/
public class AnnotationApplicationContextAsIoCContainerDemo {
public static void main(String[] args) {
// 创建ApplicationContext (BeanFactory工厂)
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
// 将当前类 AnnotationApplicationContextAsIoCContainerDemo 作为配置类(Configuration Class)
applicationContext.register(AnnotationApplicationContextAsIoCContainerDemo.class);
// 启动并应用applicationContext
applicationContext.refresh();
// 依赖查找对象
lookupCollection(applicationContext);
// 关闭应用上下文
applicationContext.close();
}
@Bean
public User user(){
User user = new User();
user.setId("1");
user.setName("王凡");
return user;
}
private static void lookupCollection(BeanFactory beanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
Map<String, User> map = listableBeanFactory.getBeansOfType(User.class);
System.out.println(map);
}
}
| 36.617021
| 105
| 0.751888
|
3a8222435e37676834bf077c27689b33dfa5e2b1
| 1,704
|
package com.codimiracle.service.loveletter.controller.api.v1;
import com.codimiracle.service.loveletter.config.SpiderCrawledDataConfig;
import com.codimiracle.service.loveletter.entity.Theme;
import com.codimiracle.service.loveletter.model.Page;
import com.codimiracle.service.loveletter.model.RestDataModel;
import com.codimiracle.service.loveletter.model.RestPageModel;
import com.codimiracle.service.loveletter.service.ThemeService;
import com.codimiracle.service.loveletter.util.RestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.ConfigFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Objects;
/**
* @author Codimiracle
*/
@RestController
@RequestMapping("/api/v1/theme")
public class ThemeController {
@Value(value = "${spider.crawled-data.default-run-id}")
private String defaultRunId;
@Resource
ThemeService themeService;
@GetMapping("/{id}")
public RestDataModel<Theme> displayItem(@PathVariable String id, @RequestParam(required = false) String runId) {
if (Objects.isNull(runId)) {
runId = defaultRunId;
}
return RestUtil.success(themeService.findById(id, runId));
}
@GetMapping("/findAll")
public RestPageModel<Theme> displayList(@ModelAttribute Page page, @RequestParam(required = false) String runId) {
if (Objects.isNull(runId)) {
runId = defaultRunId;
}
return RestUtil.success(page, themeService.countAll(runId),themeService.findAll(page, runId));
}
}
| 36.255319
| 119
| 0.758216
|
b578f472cd6ec076981c724fb82a7261cc00c2fe
| 12,205
|
package cn.xfangfang.flyme6;
/**
* Created by FANGs on 2017/6/9.
*/
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Flyme6 ViewPager指示器
* @author Dawish_大D
* 博客地址:http://blog.csdn.net/u010072711
*/
public class TabStrip extends HorizontalScrollView {
private static final String TAG = "TabStrip";
/**
* 指示器容器
*/
private LinearLayout container;
/**
* 指示器个数
*/
private int tabCount;
/**
* 当前tab位置,默认为0
*/
private int currentPosition = 0;
/**
* 选中的tab位置
*/
private int selectedPosition;
/**
*
*/
private float currentPositionOffset = 0f;
/**
*
*/
private int lastScrollX = 0;
/**
* LayoutParams用于添加指示器到指示器容器中时使用,按等权重分配指示器宽度
*/
private LinearLayout.LayoutParams expandedTabLayoutParams;
private boolean isIndicatorTextBold;
/**
* 指示器颜色
*/
private int indicatorColor;
/**
* 文字颜色
*/
private int textColor;
/**
* 文字大小
*/
private int textSize;
/**
* 选中位置的文字大小
*/
private int selectedTextSize;
/**
* 指示器高度
*/
private int indicatorHeight;
/**
* 指示器左右间距
*/
private int indicatorMargin;
/**
* ViewPager
*/
private ViewPager viewPager;
/**
* viewpager的适配器
*/
private PagerAdapter pagerAdapter;
/**
* page改变监听器
*/
private final PagerStateChangeListener pagerStateChangeListener = new PagerStateChangeListener();
/**
* 画笔
*/
private Paint paint;
private Context context;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TabStrip(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
public TabStrip(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
public TabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public TabStrip(Context context) {
super(context);
init(context, null, 0, 0);
}
/**
* 初始化
*
* @param context
* @param attrs
* @param defStyleAttr
* @param defStyleRes
*/
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
this.context = context;
// 取消横向的滚动条
setHorizontalScrollBarEnabled(false);
// 指示器容器初始化
container = new LinearLayout(context);
container.setOrientation(LinearLayout.HORIZONTAL);
container.setLayoutParams(new LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.MATCH_PARENT));
// 添加指示器容器到scrollview
addView(container);
// 获取屏幕相关信息
DisplayMetrics dm = getResources().getDisplayMetrics();
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.FlymeTabStrip, defStyleAttr, defStyleRes);
int n = typedArray.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = typedArray.getIndex(i);
if (attr == R.styleable.FlymeTabStrip_indicatorColor) {
indicatorColor = typedArray.getColor(attr, Color.YELLOW);
// 指示器高度,默认2
} else if (attr == R.styleable.FlymeTabStrip_indicatorHeight) {
indicatorHeight = typedArray.getDimensionPixelSize(attr, 2);
// 指示器左右间距,默认20
} else if (attr == R.styleable.FlymeTabStrip_indicatorMargin) {
indicatorMargin = typedArray.getDimensionPixelSize(attr, 20);
// 文字颜色,默认黑色
} else if (attr == R.styleable.FlymeTabStrip_indicatorTextColor) {
textColor = typedArray.getColor(attr, Color.BLACK);
// 文字大小,默认15
} else if (attr == R.styleable.FlymeTabStrip_indicatorTextSize) {
textSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 15, dm)) / 3;
// 选中项的文字大小,默认18
} else if (attr == R.styleable.FlymeTabStrip_selectedIndicatorTextSize) {
selectedTextSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 18, dm)) / 3;
} else if (attr == R.styleable.FlymeTabStrip_indicatorTextBold){
isIndicatorTextBold = typedArray.getBoolean(attr,true);
} else{
}
}
// typedArray回收
typedArray.recycle();
expandedTabLayoutParams = new LinearLayout.LayoutParams(0,
LayoutParams.MATCH_PARENT, 1.0f);
// 初始化画笔
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 如果指示器个数为0,直接结束绘画
if (tabCount == 0) {
return;
}
// 获取onMeasure后的高
final int height = getHeight();
/*
* 画指示器下方的线
*/
// 设置颜色
paint.setColor(indicatorColor);
// 当前指示tab位置
View currentTab = container.getChildAt(currentPosition);
// 当前tab的左边相对父容器的左边距
float leftPadding = currentTab.getLeft();
// 当前tab的右边相对于父容器左边距
float rightPadding = currentTab.getRight();
float tempPadding = 20;
// 如果出现位移
float centerPosition = 0.0f;
if (currentPositionOffset >= 0f && currentPosition < tabCount - 1) {
View nextTab = container.getChildAt(currentPosition + 1);
final float nextTabLeft = nextTab.getLeft();
final float nextTabRight = nextTab.getRight();
// 位置是在滑动过程中不断变化的
leftPadding = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * leftPadding);
rightPadding = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * rightPadding);
}
centerPosition = (rightPadding - leftPadding)/2 + leftPadding;
float left = centerPosition - tempPadding - formatPercent(currentPositionOffset)*tempPadding;
float right = centerPosition + tempPadding + formatPercent(currentPositionOffset)*tempPadding;
// 绘制
canvas.drawRect(left, height - indicatorHeight, right, height, paint);
}
/**
* 设置ViewPager
*
* @param viewPager
*/
public void setViewPager(ViewPager viewPager) {
this.viewPager = viewPager;
if (viewPager.getAdapter() == null) {
throw new IllegalStateException(
"ViewPager does not has a adapter instance");
} else {
pagerAdapter = viewPager.getAdapter();
}
viewPager.addOnPageChangeListener((ViewPager.OnPageChangeListener) pagerStateChangeListener);
update();
}
/**
* 更新界面
*/
private void update() {
// 指示器容器移除所有子view
container.removeAllViews();
// 获取指示器个数
tabCount = pagerAdapter.getCount();
// 逐个添加指示器
for (int i = 0; i < tabCount; i++) {
addTab(i, pagerAdapter.getPageTitle(i));
}
// 更新Tab样式
updateTabStyle();
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
currentPosition = viewPager.getCurrentItem();
scrollToChild(currentPosition, 0);
}
});
}
/**
* 滑动ScrollView
*
* @param position
* @param offset
*/
private void scrollToChild(int position, int offset) {
if (tabCount == 0) {
return;
}
int newScrollX = container.getChildAt(position).getLeft() + offset;
if (newScrollX != lastScrollX) {
lastScrollX = newScrollX;
scrollTo(newScrollX, 0);
}
}
/**
* 添加指示器
*
* @param position
* @param title
*/
private void addTab(final int position, CharSequence title) {
TextView tvTab = new TextView(context);
tvTab.setText(title);
tvTab.setTextColor(textColor);
tvTab.setTextSize(textSize);
tvTab.setGravity(Gravity.CENTER);
if(isIndicatorTextBold){
TextPaint tp = tvTab.getPaint();
tp.setFakeBoldText(true);
}
tvTab.setSingleLine();
tvTab.setFocusable(true);
tvTab.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
viewPager.setCurrentItem(position);
}
});
tvTab.setPadding(indicatorMargin, 0, indicatorMargin, 0);
container.addView(tvTab, position, expandedTabLayoutParams);
}
/**
* 更新指示器样式
*/
private void updateTabStyle() {
for (int i = 0; i < tabCount; i++) {
TextView tab = (TextView) container.getChildAt(i);
if (i == selectedPosition) {
// 设置选中的指示器文字颜色和大小
tab.setTextColor(indicatorColor);
tab.setTextSize(selectedTextSize);
} else {
tab.setTextColor(textColor);
tab.setTextSize(textSize);
}
}
}
/**
* 对偏移百分比进行格式化 保证是一个小到大 然后到小的一个驼峰过程
* 这样才能保证滚动指示器是一个长度在随着滚动偏移不断变化的样子
* @param percent
* @return
*/
private float formatPercent(float percent){
float adsP = (float) Math.abs(percent - 0.5f);
float valueP = Math.abs(0.5f - adsP);
return valueP;
}
/**
* viewPager状态改变监听
*
*/
private class PagerStateChangeListener implements ViewPager.OnPageChangeListener {
/**
* viewpager状态监听
* @param state
*/
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) { // 0 空闲状态 pager处于空闲状态
scrollToChild(viewPager.getCurrentItem(), 0);
}else if(state == ViewPager.SCROLL_STATE_SETTLING){ // 2 正在自动沉降,相当于松手后,pager恢复到一个完整pager的过程
}else if(state == ViewPager.SCROLL_STATE_DRAGGING){ // 1 viewpager正在被滑动,处于正在拖拽中
}
}
/**
* viewpager正在滑动,会回调一些偏移量
* 滚动时,只要处理指示器下方横线的滚动
* @param position 当前页面
* @param positionOffset 当前页面偏移的百分比
* @param positionOffsetPixels 当前页面偏移的像素值
*/
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentPosition = position;
currentPositionOffset = positionOffset;
// 处理指示器下方横线的滚动,scrollToChild会不断调用ondraw方法,绘制在重绘下划线,这就是移动动画效果
scrollToChild(position, (int) (positionOffset * container.getChildAt(position).getWidth()));
invalidate();
}
/**
* page滚动结束
* @param position 滚动结束后选中的页面
*/
@Override
public void onPageSelected(int position) {
// 滚动结束后的未知
selectedPosition = position;
// 更新指示器状态
updateTabStyle();
}
}
}
| 29.768293
| 112
| 0.598935
|
ca85ef7373e622f61e7f11d3708627d3c69161f9
| 351
|
package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import view.ViewServices;
public class RulesController {
public Button buttonBack;
public AnchorPane mainPane;
@FXML
public void initialize(){
ViewServices.setBackToAccueil(buttonBack, mainPane);
}
}
| 20.647059
| 60
| 0.752137
|
c47405aeec6f5083d1c06d0736e0ba7e0fe062e6
| 2,670
|
package exa.free.ag;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import exa.free.interfaces.AppSelector;
class TerminalChooserAdapter extends BaseAdapter{
private List<ApplicationAdapterListItem> applicationAdapterListItems;
private AppSelector appSelector;
TerminalChooserAdapter(Context context, AppSelector appSelector, List<ApplicationAdapterListItem> applicationAdapterListItems) {
this.appSelector = appSelector;
this.applicationAdapterListItems = applicationAdapterListItems;
}
@Override
public int getCount() {
return applicationAdapterListItems.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_list, parent, false);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textView = convertView.findViewById(R.id.textView);
listViewHolder.textView2 = convertView.findViewById(R.id.textView2);
listViewHolder.imageView = convertView.findViewById(R.id.imageView);
listViewHolder.button = convertView.findViewById(R.id.button);
convertView.setTag(listViewHolder);
listViewHolder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
appSelector.selectApp(applicationAdapterListItems.get(position).getPackageName());
notifyDataSetChanged();
}
});
listViewHolder.textView.setText(applicationAdapterListItems.get(position).getName());
listViewHolder.textView2.setText(applicationAdapterListItems.get(position).getPackageName());
listViewHolder.imageView.setImageDrawable(applicationAdapterListItems.get(position).getIcon());
return convertView;
}
private static class ViewHolder {
private TextView textView;
private TextView textView2;
private ImageView imageView;
private Button button;
}
}
| 33.797468
| 132
| 0.712734
|
c42b58acd3a891086f43e6976b047216d0e15dcd
| 4,019
|
package net.backinclassic.procedures.player_relation;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.World;
import net.minecraft.world.IWorld;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.math.vector.Vector2f;
import net.minecraft.entity.Entity;
import net.minecraft.command.ICommandSource;
import net.minecraft.command.CommandSource;
import net.backinclassic.BackInClassicMod;
import java.util.Map;
public class NetherPortalSpawnCommandExecutedProcedure {
public static void executeProcedure(Map<String, Object> dependencies) {
if (dependencies.get("entity") == null) {
if (!dependencies.containsKey("entity"))
BackInClassicMod.LOGGER.warn("Failed to load dependency entity for procedure NetherPortalSpawnCommandExecuted!");
return;
}
if (dependencies.get("x") == null) {
if (!dependencies.containsKey("x"))
BackInClassicMod.LOGGER.warn("Failed to load dependency x for procedure NetherPortalSpawnCommandExecuted!");
return;
}
if (dependencies.get("y") == null) {
if (!dependencies.containsKey("y"))
BackInClassicMod.LOGGER.warn("Failed to load dependency y for procedure NetherPortalSpawnCommandExecuted!");
return;
}
if (dependencies.get("z") == null) {
if (!dependencies.containsKey("z"))
BackInClassicMod.LOGGER.warn("Failed to load dependency z for procedure NetherPortalSpawnCommandExecuted!");
return;
}
if (dependencies.get("world") == null) {
if (!dependencies.containsKey("world"))
BackInClassicMod.LOGGER.warn("Failed to load dependency world for procedure NetherPortalSpawnCommandExecuted!");
return;
}
Entity entity = (Entity) dependencies.get("entity");
double x = dependencies.get("x") instanceof Integer ? (int) dependencies.get("x") : (double) dependencies.get("x");
double y = dependencies.get("y") instanceof Integer ? (int) dependencies.get("y") : (double) dependencies.get("y");
double z = dependencies.get("z") instanceof Integer ? (int) dependencies.get("z") : (double) dependencies.get("z");
IWorld world = (IWorld) dependencies.get("world");
if ((entity.hasPermissionLevel((int) 4))) {
if (world instanceof ServerWorld) {
((World) world).getServer().getCommandManager().handleCommand(
new CommandSource(ICommandSource.DUMMY, new Vector3d(x, y, z), Vector2f.ZERO, (ServerWorld) world, 4, "",
new StringTextComponent(""), ((World) world).getServer(), null).withFeedbackDisabled(),
"/fill ~-1 ~ ~ ~1 ~ ~ obsidian");
}
if (world instanceof ServerWorld) {
((World) world).getServer().getCommandManager().handleCommand(
new CommandSource(ICommandSource.DUMMY, new Vector3d(x, y, z), Vector2f.ZERO, (ServerWorld) world, 4, "",
new StringTextComponent(""), ((World) world).getServer(), null).withFeedbackDisabled(),
"/fill ~-1 ~3 ~ ~1 ~3 ~ obsidian");
}
if (world instanceof ServerWorld) {
((World) world).getServer().getCommandManager().handleCommand(
new CommandSource(ICommandSource.DUMMY, new Vector3d(x, y, z), Vector2f.ZERO, (ServerWorld) world, 4, "",
new StringTextComponent(""), ((World) world).getServer(), null).withFeedbackDisabled(),
"/fill ~-1 ~ ~ ~-1 ~3 ~ obsidian");
}
if (world instanceof ServerWorld) {
((World) world).getServer().getCommandManager().handleCommand(
new CommandSource(ICommandSource.DUMMY, new Vector3d(x, y, z), Vector2f.ZERO, (ServerWorld) world, 4, "",
new StringTextComponent(""), ((World) world).getServer(), null).withFeedbackDisabled(),
"/fill ~1 ~ ~ ~1 ~3 ~ obsidian");
}
if (world instanceof ServerWorld) {
((World) world).getServer().getCommandManager().handleCommand(
new CommandSource(ICommandSource.DUMMY, new Vector3d(x, y, z), Vector2f.ZERO, (ServerWorld) world, 4, "",
new StringTextComponent(""), ((World) world).getServer(), null).withFeedbackDisabled(),
"/fill ~ ~1 ~ ~ ~2 ~ nether_portal");
}
}
}
}
| 48.421687
| 117
| 0.704902
|
5be554d24410dd83b54c226c6d126699c7badc81
| 482
|
package com.app.system.common.entity;
import com.app.system.common.h;
import com.google.gson.f;
public abstract class Notify
{
static final String REC_STATUS = "REC_STATUS";
static final String SCREEN_STATUS = "SCREEN_STATUS";
static final String WIFI_STATUS = "WIFI_STATUS";
public abstract String a();
public String b()
{
return h.b().a(this);
}
}
/* Location: ~/com/app/system/common/entity/Notify.class
*
* Reversed by: J
*/
| 20.083333
| 69
| 0.665975
|
ef07de7b3a3e809fa0511f51c933f32471dfe118
| 4,688
|
package pro.taskana.impl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import pro.taskana.Classification;
import pro.taskana.Task;
import pro.taskana.TaskState;
import pro.taskana.TaskanaEngine;
import pro.taskana.Workbasket;
import pro.taskana.WorkbasketPermission;
import pro.taskana.WorkbasketService;
import pro.taskana.configuration.TaskanaEngineConfiguration;
import pro.taskana.exceptions.InvalidStateException;
import pro.taskana.exceptions.NotAuthorizedException;
import pro.taskana.exceptions.TaskNotFoundException;
import pro.taskana.exceptions.WorkbasketNotFoundException;
import pro.taskana.mappings.AttachmentMapper;
import pro.taskana.mappings.ObjectReferenceMapper;
import pro.taskana.mappings.TaskMapper;
/**
* Unit Test for TaskServiceImpl.
*
* @author EH
*/
@ExtendWith(MockitoExtension.class)
class TaskTransferrerTest {
private TaskTransferrer cut;
@Mock private TaskServiceImpl taskServiceImplMock;
@Mock private TaskanaEngineConfiguration taskanaEngineConfigurationMock;
@Mock private InternalTaskanaEngine internalTaskanaEngineMock;
@Mock private TaskanaEngine taskanaEngineMock;
@Mock private TaskMapper taskMapperMock;
@Mock private ObjectReferenceMapper objectReferenceMapperMock;
@Mock private WorkbasketService workbasketServiceMock;
@Mock private ClassificationServiceImpl classificationServiceImplMock;
@Mock private AttachmentMapper attachmentMapperMock;
@Mock private ClassificationQueryImpl classificationQueryImplMock;
@Mock private SqlSession sqlSessionMock;
@Test
void testTransferTaskToDestinationWorkbasketWithoutSecurity()
throws TaskNotFoundException, WorkbasketNotFoundException, NotAuthorizedException,
InvalidStateException {
when(internalTaskanaEngineMock.getEngine()).thenReturn(taskanaEngineMock);
when(taskanaEngineMock.getWorkbasketService()).thenReturn(workbasketServiceMock);
cut = new TaskTransferrer(internalTaskanaEngineMock, taskMapperMock, taskServiceImplMock);
final TaskTransferrer cutSpy = Mockito.spy(cut);
Workbasket destinationWorkbasket = TaskServiceImplTest.createWorkbasket("2", "k1");
Workbasket sourceWorkbasket = TaskServiceImplTest.createWorkbasket("47", "key47");
Classification dummyClassification = TaskServiceImplTest.createDummyClassification();
TaskImpl task =
TaskServiceImplTest.createUnitTestTask(
"1", "Unit Test Task 1", "key47", dummyClassification);
task.setWorkbasketSummary(sourceWorkbasket.asSummary());
task.setRead(true);
when(workbasketServiceMock.getWorkbasket(destinationWorkbasket.getId()))
.thenReturn(destinationWorkbasket);
doReturn(task).when(taskServiceImplMock).getTask(task.getId());
final Task actualTask = cutSpy.transfer(task.getId(), destinationWorkbasket.getId());
verify(internalTaskanaEngineMock, times(1)).openConnection();
verify(workbasketServiceMock, times(1))
.checkAuthorization(destinationWorkbasket.getId(), WorkbasketPermission.APPEND);
verify(workbasketServiceMock, times(1))
.checkAuthorization(sourceWorkbasket.getId(), WorkbasketPermission.TRANSFER);
verify(workbasketServiceMock, times(1)).getWorkbasket(destinationWorkbasket.getId());
verify(taskMapperMock, times(1)).update(any());
verify(internalTaskanaEngineMock, times(1)).returnConnection();
verify(internalTaskanaEngineMock, times(1)).getEngine();
verify(internalTaskanaEngineMock).getHistoryEventProducer();
verify(taskanaEngineMock).getWorkbasketService();
verifyNoMoreInteractions(
attachmentMapperMock,
taskanaEngineConfigurationMock,
taskanaEngineMock,
internalTaskanaEngineMock,
taskMapperMock,
objectReferenceMapperMock,
workbasketServiceMock,
sqlSessionMock,
classificationQueryImplMock);
assertThat(actualTask.isRead(), equalTo(false));
assertThat(actualTask.getState(), equalTo(TaskState.READY));
assertThat(actualTask.isTransferred(), equalTo(true));
assertThat(actualTask.getWorkbasketKey(), equalTo(destinationWorkbasket.getKey()));
}
}
| 39.728814
| 94
| 0.799061
|
ee20cf9cacc9c34ef4134268c04ab1b69917e039
| 2,163
|
package org.datasyslab.geospark.rangeFilter;
import java.io.Serializable;
import java.util.ArrayList;
import org.apache.spark.api.java.function.Function;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;
public class RectangleRangeFilter implements Function<Envelope,Boolean>,Serializable
{
Integer condition=0;
Envelope rangeRectangle=new Envelope();
Polygon rangePolygon;
Integer rangeFlag=0;
public RectangleRangeFilter(Envelope envelope,Integer condition)
{
this.condition=condition;
this.rangeRectangle=envelope;
this.rangeFlag=0;
}
// public RectangleRangeFilter(Polygon polygon,Integer condition)
// {
// this.condition=condition;
// this.rangePolygon=polygon;
// this.rangeFlag=1;
// }
public Boolean call(Envelope tuple) throws Exception {
if(rangeFlag==0){
if(condition==0)
{
if(rangeRectangle.contains(tuple))
{
return true;
}
else return false;
}
else
{
if(rangeRectangle.intersects(tuple))
{
return true;
}
else return false;
}
}
//todo: fix later;
else {
return false;
}
// else
// {
// ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
// coordinates.add(new Coordinate(tuple.getMinX(),tuple.getMinY()));
// coordinates.add(new Coordinate(tuple.getMinX(),tuple.getMaxY()));
// coordinates.add(new Coordinate(tuple.getMaxX(),tuple.getMaxY()));
// coordinates.add(new Coordinate(tuple.getMaxX(),tuple.getMinY()));
// coordinates.add(new Coordinate(tuple.getMinX(),tuple.getMinY()));
// GeometryFactory fact = new GeometryFactory();
// LinearRing linear = new GeometryFactory().createLinearRing((Coordinate[]) coordinates.toArray());
// Polygon polygon = new Polygon(linear, null, fact);
// if(condition==0)
// {
//
// if(rangePolygon.contains(polygon))
// {
// return true;
// }
// else return false;
// }
// else
// {
// if(rangePolygon.intersects(polygon))
// {
// return true;
// }
// else return false;
// }
// }
}
}
| 25.151163
| 101
| 0.705502
|
32b7984843d8e547a80b73939b54a13eb3f49ded
| 6,792
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.brooklyn.location.jclouds.provider;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.brooklyn.api.location.NoMachinesAvailableException;
import org.apache.brooklyn.core.internal.BrooklynProperties;
import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
import org.apache.brooklyn.location.jclouds.JcloudsLocation;
import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation;
import org.apache.brooklyn.location.ssh.SshMachineLocation;
import org.apache.brooklyn.util.collections.MutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
/**
* Tests vcloud, with Carrenza. Uses the cloudsoft test account (hard-coding its NAT Mapping,
* and one of its private vApp templates). Note that the template is for a Windows 2008
* machine with winsshd installed.
*
* TODO Will only work with >= jclouds 1.5, due to jclouds issues 994 and 995. Therefore it
* will not work in brooklyn 0.4.0-M2 etc.
*/
class CarrenzaLocationLiveTest {
private static final Logger LOG = LoggerFactory.getLogger(CarrenzaLocationLiveTest.class);
private static final String PROVIDER = "vcloud";
private static final String ENDPOINT = "https://myvdc.carrenza.net/api";
private static final String LOCATION_ID = "jclouds:"+PROVIDER+":"+ENDPOINT;
private static final String WINDOWS_IMAGE_ID = "https://myvdc.carrenza.net/api/v1.0/vAppTemplate/vappTemplate-2bd5b0ff-ecd9-405e-8306-2f4f6c092a1b";
private BrooklynProperties brooklynProperties;
private LocalManagementContext managementContext;
private JcloudsLocation loc;
private Collection<SshMachineLocation> machines = new ArrayList<>();
// TODO Has not been tested since updating ot remove use of deleted LocationRegistry!
@BeforeMethod(groups = "Live")
public void setUp() {
System.out.println("classpath="+System.getProperty("java.class.path"));
brooklynProperties = BrooklynProperties.Factory.newDefault();
brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-description-regex");
brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-name-regex");
brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-id");
brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".inboundPorts");
brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".hardware-id");
// Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty")
brooklynProperties.remove("brooklyn.ssh.config.scriptHeader");
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".jclouds.endpoint", ENDPOINT);
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".imageId", WINDOWS_IMAGE_ID);
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".noDefaultSshKeys", true);
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".userName", "Administrator");
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".dontCreateUser", true);
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".overrideLoginUser", "Administrator");
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".waitForSshable", false);
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".runAsRoot", false);
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".inboundPorts", ImmutableList.of(22, 3389));
brooklynProperties.put("brooklyn.jclouds."+PROVIDER+".natMapping", ImmutableMap.of("192.168.0.100", "195.3.186.200", "192.168.0.101", "195.3.186.42"));
managementContext = new LocalManagementContext(brooklynProperties);
loc = (JcloudsLocation) managementContext.getLocationRegistry().getLocationManaged(LOCATION_ID);
}
@AfterMethod(groups = "Live")
public void tearDown() throws Exception {
List<Exception> exceptions = new ArrayList<>();
for (SshMachineLocation machine : machines) {
try {
loc.release(machine);
} catch (Exception e) {
LOG.warn("Error releasing machine $it; continuing...", e);
exceptions.add(e);
}
}
if (!exceptions.isEmpty()) {
throw exceptions.get(0);
}
machines.clear();
}
// FIXME Disabled because of jclouds issues #994 and #995 (fixed in jclouds 1.5, so not in brooklyn 0.4.0-M2 etc)
// Note the careful settings in setUp (e.g. so don't try to install ssh-keys etc
// Also, the windows image used has winsshd installed
@Test(enabled=false, groups = "Live")
public void testProvisionWindowsVm() throws NoMachinesAvailableException {
JcloudsSshMachineLocation machine = (JcloudsSshMachineLocation) obtainMachine(MutableMap.of(
"imageId", WINDOWS_IMAGE_ID));
LOG.info("Provisioned Windows VM {}; checking if has password", machine);
String password = machine.waitForPassword();
assertNotNull(password);
LOG.info("Checking can ssh to windows machine {} using password {}", machine, password);
assertEquals(machine.execCommands(MutableMap.of("password", password), "check-reachable", ImmutableList.of("hostname")), 0);
}
// Use this utility method to ensure machines are released on tearDown
protected SshMachineLocation obtainMachine(Map<?, ?> flags) throws NoMachinesAvailableException {
SshMachineLocation result = (SshMachineLocation) loc.obtain(flags);
machines.add(result);
return result;
}
}
| 49.941176
| 159
| 0.719965
|
90165e9af2df35677ccf72ca435c38154a14232d
| 457
|
package com.leyou.item.pojo;
import lombok.Data;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Table(name="tb_spu_detail")
public class SpuDetail {
@Id
private Long spuId;// 对应的SPU的id
private String description;// 商品描述
private String specTemplate;// 商品特殊规格的名称及可选值模板
private String specifications;// 商品的全局规格属性
private String packingList;// 包装清单
private String afterService;// 售后服务
// 省略getter和setter
}
| 24.052632
| 50
| 0.741794
|
39dcfcce9ccd58a238467ecef5a271013df49b2d
| 3,103
|
package com.xwintop.xJavaFxTool.controller.epmsTools;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.net.URL;
import java.util.ResourceBundle;
import com.xwintop.xJavaFxTool.services.epmsTools.TextToHibernateXmlService;
import com.xwintop.xJavaFxTool.services.epmsTools.XmlToBeanService;
import com.xwintop.xJavaFxTool.services.epmsTools.XmlToCodeService;
import com.xwintop.xJavaFxTool.services.epmsTools.XmlToSqlService;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
public class GeneratingCodeController extends AnchorPane implements Initializable {
@FXML
private TextField textField1;
@FXML
private TextField textField2;
@FXML
private TextArea textArea1;
@FXML
private TextArea textArea2;
@FXML
private TextArea textArea3;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
@FXML
private void xmlToSql(ActionEvent event){
String string = XmlToSqlService.xmlToSql(textArea1.getText(),textField1.getText(),textField2.getText());
textArea3.setText(string);
}
@FXML
private void xmlToBean(ActionEvent event){
String string = XmlToBeanService.xmlTobean(textArea1.getText());
textArea3.setText(string);
}
@FXML
private void xmlTemplateToCode(ActionEvent event) throws Exception{
String string = XmlToCodeService.xmlTemplateToCode(textArea1.getText(),textArea2.getText(),textField1.getText(),textField2.getText());
textArea3.setText(string);
}
@FXML
private void textToHibernateXml(ActionEvent event) throws Exception{
String string = TextToHibernateXmlService.textToHibernateXml(textArea1.getText(),textField1.getText(),textField2.getText());
textArea3.setText(string);
}
@FXML
private void sqlToHibernateXml(ActionEvent event) throws Exception{
String string = TextToHibernateXmlService.sqlToHibernateXml(textArea1.getText(),textField1.getText(),textField2.getText());
textArea3.setText(string);
}
@FXML
private void sqlToJdbcInsertAction(ActionEvent event) throws Exception{
String string = XmlToBeanService.sqlToJdbcInsert(textArea1.getText(),textField2.getText());
textArea3.setText(string);
}
@FXML
private void sqlToJdbcUpdateAction(ActionEvent event) throws Exception{
String string = XmlToBeanService.sqlToJdbcUpdate(textArea1.getText(),textField2.getText());
textArea3.setText(string);
}
@FXML
private void xmlElementToSqlAction(ActionEvent event) throws Exception{
String string = XmlToSqlService.xmlElementToSqlAction(textArea1.getText(),textField1.getText(),textField2.getText());
textArea3.setText(string);
}
/**
* @Title: copyTextValueToClipboard
* @Description: 拷贝内容到剪贴板
*/
@FXML
private void copyTextValueToClipboard(ActionEvent event) throws Exception{
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // 获得系统剪贴板
clipboard.setContents(new StringSelection(textArea3.getText()), null);
}
}
| 32.663158
| 136
| 0.802772
|
ba8a4c0e3672f06b8d56467e0309f76e33057c04
| 14,574
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.ballerina.test.context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
/**
* This class hold the server information and manage the a server instance.
*/
public class ServerInstance implements Server {
private static final Logger log = LoggerFactory.getLogger(ServerInstance.class);
private String serverHome;
private String serverDistribution;
private String[] args;
private Process process;
private ServerLogReader serverInfoLogReader;
private ServerLogReader serverErrorLogReader;
private boolean isServerRunning;
public ServerInstance(String serverDistributionPath) {
this.serverDistribution = serverDistributionPath;
}
/**
* Start a server instance y extracting a server zip distribution.
*
* @throws Exception
*/
@Override
public void start() throws Exception {
Utils.checkPortAvailability(Constant.DEFAULT_HTTP_PORT);
if (serverHome == null) {
serverHome = setUpServerHome(serverDistribution);
log.info("Server Home " + serverHome);
configServer();
}
if (args == null | args.length == 0) {
throw new IllegalArgumentException("No Argument provided for server startup.");
}
log.info("Starting server..");
startProcess(args);
serverInfoLogReader = new ServerLogReader("inputStream", process.getInputStream());
serverInfoLogReader.start();
serverErrorLogReader = new ServerLogReader("errorStream", process.getErrorStream());
serverErrorLogReader.start();
log.info("Waiting for port " + Constant.DEFAULT_HTTP_PORT + " to open");
Utils.waitForPort(Constant.DEFAULT_HTTP_PORT, 1000 * 60 * 2, false, "localhost");
log.info("Server Started Successfully.");
isServerRunning = true;
}
/**
* Stop the server instance which is started by start method.
*
* @throws InterruptedException
*/
@Override
public void stop() throws InterruptedException {
log.info("Stopping server..");
if (process != null) {
String pid;
try {
pid = getServerPID();
if (Utils.getOSName().toLowerCase().contains("windows")) {
Process killServer = Runtime.getRuntime().exec("TASKKILL -F /PID " + pid);
log.info(readProcessInputStream(killServer.getInputStream()));
killServer.waitFor(15, TimeUnit.SECONDS);
killServer.destroy();
} else {
Process killServer = Runtime.getRuntime().exec("kill -9 " + pid);
killServer.waitFor(15, TimeUnit.SECONDS);
killServer.destroy();
}
} catch (IOException e) {
log.error("Error while getting the server process id", e);
}
process.destroy();
serverInfoLogReader.stop();
serverErrorLogReader.stop();
process = null;
//wait until port to close
Utils.waitForPortToClosed(Constant.DEFAULT_HTTP_PORT, 30000);
log.info("Server Stopped Successfully");
}
}
/**
* Restart the server instance.
*
* @throws Exception
*/
@Override
public void restart() throws Exception {
log.info("Restarting Server...");
stop();
start();
log.info("Server Restarted Successfully");
}
/**
* Checking whether server instance is up and running.
*
* @return true if the server is up and running
*/
@Override
public boolean isRunning() {
return isServerRunning;
}
/**
* setting the list of command line argument while server startup.
*
* @param args list of service files
*/
public void setArguments(String[] args) {
this.args = args;
}
/**
* to change the server configuration if required. This method can be overriding when initialising
* the object of this class.
*/
protected void configServer() {
}
/**
* Return server home path.
*
* @return absolute path of the server location
*/
public String getServerHome() {
return serverHome;
}
/**
* Return the service URL.
*
* @param servicePath - http url of the given service
* @return
*/
public String getServiceURLHttp(String servicePath) {
return "http://localhost:" + Constant.DEFAULT_HTTP_PORT + "/" + servicePath;
}
/**
* Unzip carbon zip file and return the carbon home. Based on the coverage configuration
* in automation.xml.
* This method will inject jacoco agent to the carbon server startup scripts.
*
* @param serverZipFile - Carbon zip file, which should be specified in test module pom
* @return - carbonHome - carbon home
* @throws IOException - If pack extraction fails
*/
private String setUpServerHome(String serverZipFile)
throws IOException {
if (process != null) { // An instance of the server is running
return serverHome;
}
int indexOfZip = serverZipFile.lastIndexOf(".zip");
if (indexOfZip == -1) {
throw new IllegalArgumentException(serverZipFile + " is not a zip file");
}
String fileSeparator = (File.separator.equals("\\")) ? "\\" : "/";
if (fileSeparator.equals("\\")) {
serverZipFile = serverZipFile.replace("/", "\\");
}
String extractedCarbonDir =
serverZipFile.substring(serverZipFile.lastIndexOf(fileSeparator) + 1,
indexOfZip);
String extractDir = "ballerinatmp" + System.currentTimeMillis();
String baseDir = (System.getProperty(Constant.SYSTEM_PROP_BASE_DIR, ".")) + File.separator + "target";
log.info("Extracting ballerina zip file.. ");
Utils.extractFile(serverZipFile, baseDir + File.separator + extractDir);
String serverExtractedPath = new File(baseDir).getAbsolutePath() + File.separator
+ extractDir + File.separator +
extractedCarbonDir;
return serverExtractedPath;
}
/**
* Executing the sh or bat file to start the server.
*
* @param args - command line arguments to pass when executing the sh or bat file
* @throws IOException
*/
private void startProcess(String[] args) throws IOException {
String scriptName = Constant.BALLERINA_SERVER_SCRIPT_NAME;
String[] cmdArray;
File commandDir = new File(serverHome);
if (Utils.getOSName().toLowerCase().contains("windows")) {
commandDir = new File(serverHome + File.separator + "bin");
cmdArray = new String[]{"cmd.exe", "/c", scriptName + ".bat"};
String[] cmdArgs = Stream.concat(Arrays.stream(cmdArray), Arrays.stream(args))
.toArray(String[]::new);
process = Runtime.getRuntime().exec(cmdArgs, null, commandDir);
} else {
cmdArray = new String[]{"bash", "bin/" + scriptName, "service"};
String[] cmdArgs = Stream.concat(Arrays.stream(cmdArray), Arrays.stream(args))
.toArray(String[]::new);
process = Runtime.getRuntime().exec(cmdArgs, null, commandDir);
}
}
/**
* reading the server process id.
*
* @return process id
* @throws IOException
*/
private String getServerPID() throws IOException {
String pid = null;
if (Utils.getOSName().toLowerCase().contains("windows")) {
//reading the process id from netstat
Process tmp = Runtime.getRuntime().exec("netstat -a -n -o");
String outPut = readProcessInputStream(tmp.getInputStream());
String[] lines = outPut.split("\r\n");
for (String line : lines) {
String[] column = line.trim().split("\\s+");
if (column != null && column.length < 5) {
continue;
}
if (column[1].contains(":" + Constant.DEFAULT_HTTP_PORT) && column[3].contains("LISTENING")) {
log.info(line);
pid = column[4];
break;
}
}
tmp.destroy();
} else {
BufferedReader bufferedReader = null;
FileReader fileReader = null;
try {
//reading the pid form carbon.pid file in server home dir
fileReader = new FileReader(serverHome + File.separator + Constant.SERVER_PID_FILE_NAME);
bufferedReader = new BufferedReader(fileReader);
pid = bufferedReader.readLine();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
//ignore
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
//ignore
}
}
}
}
log.info("Server process id in " + Utils.getOSName() + " : " + pid);
return pid;
}
/**
* Reading output from input stream.
*
* @param inputStream input steam of a process
* @return the output string generated by java process
*/
private String readProcessInputStream(InputStream inputStream) {
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
inputStreamReader = new InputStreamReader(inputStream, Charset.defaultCharset());
bufferedReader = new BufferedReader(inputStreamReader);
int x;
while ((x = bufferedReader.read()) != -1) {
stringBuilder.append((char) x);
}
} catch (Exception ex) {
log.error("Error reading process id", ex);
} finally {
if (inputStreamReader != null) {
try {
inputStream.close();
inputStreamReader.close();
} catch (IOException e) {
log.error("Error occurred while closing stream: " + e.getMessage(), e);
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
log.error("Error occurred while closing stream: " + e.getMessage(), e);
}
}
}
return stringBuilder.toString();
}
/**
* This class will read the log messages of the server started by this listener.
*/
private class ServerLogReader implements Runnable {
private final Logger log = LoggerFactory.getLogger(ServerLogReader.class);
private String streamType;
private InputStream inputStream;
private static final String STREAM_TYPE_IN = "inputStream";
private static final String STREAM_TYPE_ERROR = "errorStream";
private Thread thread;
private volatile boolean running = true;
public ServerLogReader(String name, InputStream is) {
this.streamType = name;
this.inputStream = is;
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() {
running = false;
}
public void run() {
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
inputStreamReader = new InputStreamReader(inputStream, Charset.defaultCharset());
bufferedReader = new BufferedReader(inputStreamReader);
while (running) {
if (bufferedReader.ready()) {
String s = bufferedReader.readLine();
if (s == null) {
break;
}
if (STREAM_TYPE_IN.equals(streamType)) {
log.info(s);
} else if (STREAM_TYPE_ERROR.equals(streamType)) {
log.error(s);
}
}
}
} catch (Exception ex) {
log.error("Problem reading the [" + streamType + "] due to: " + ex.getMessage(), ex);
} finally {
if (inputStreamReader != null) {
try {
inputStream.close();
inputStreamReader.close();
} catch (IOException e) {
log.error("Error occurred while closing the server log stream: " + e.getMessage(), e);
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
log.error("Error occurred while closing the server log stream: " + e.getMessage(), e);
}
}
}
}
}
}
| 36.80303
| 110
| 0.560519
|
ca6bf29656a23a6b523a81fbe5637eb3d35b78ae
| 2,035
|
package bitwise.gui.imageview;
import java.io.IOException;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
public class AspectImageView extends Pane {
@FXML private ImageView imageView;
public AspectImageView() throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("AspectImageView.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
fxmlLoader.load();
}
private ReadOnlyDoubleProperty fitWidth = this.widthProperty();
private ReadOnlyDoubleProperty fitHeight = this.heightProperty();
public void setFitDimensions(ReadOnlyDoubleProperty in_fitWidth, ReadOnlyDoubleProperty in_fitHeight) {
fitWidth = in_fitWidth;
fitWidth.addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
if (null != image)
setImage(image);
}
});
fitHeight = in_fitHeight;
fitHeight.addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
if (null != image)
setImage(image);
}
});
}
private Image image = null;
public void setImage(Image in) {
image = in;
double tw = fitWidth.doubleValue();
double th = fitHeight.doubleValue();
double iw = in.getWidth();
double ih = in.getHeight();
if (0 == tw || 0 == th || 0 == iw || 0 == ih) {
imageView.fitWidthProperty().set(tw);
imageView.fitHeightProperty().set(th);
}
else {
double scaleBy = 1;
if (tw / th < iw / ih)
scaleBy = tw / iw;
else
scaleBy = th / ih;
if (scaleBy > 1)
scaleBy = 1;
imageView.fitWidthProperty().set(iw * scaleBy);
imageView.fitHeightProperty().set(ih * scaleBy);
}
imageView.setImage(in);
}
}
| 27.876712
| 104
| 0.714005
|
bb234fa0f90677990e5a057fdf1457c15839475a
| 350
|
package cn.czfshine.wechat.emoji;
import java.util.HashMap;
public class EmojiPool {
private static HashMap<String,Emoji> allEmoji=new HashMap<>();
public static Emoji getEmoji(String md5){
return allEmoji.getOrDefault(md5,null);
}
public static void add(String md5,Emoji emoji){
allEmoji.put(md5,emoji);
}
}
| 20.588235
| 66
| 0.691429
|
8d3386e7456320fc322ebc4444ed11a3b957528a
| 2,568
|
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
public class CalculatorController {
public TextField text;
private int x;
private String operation;
public void inputDigit(ActionEvent actionEvent) {
String digit = ((Button) actionEvent.getSource()).getText();
text.setText(text.getText() + digit);
}
public void removeLastDigit(ActionEvent actionEvent) {
text.setText(text.getText(0, text.getLength() - 1));
}
public void inputKey(KeyEvent keyEvent) {
String key = keyEvent.getText();
switch (key) {
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
text.setText(text.getText() + key);
break;
case "+":
case "-":
case "*":
case "/":
x = Integer.parseInt(text.getText());
text.setText("");
this.operation = key;
break;
}
if (keyEvent.getCode().toString().equals("ENTER")) {
processEnter();
}
}
private void processEnter() {
switch (operation) {
case "+":
x = x + Integer.parseInt(text.getText());
text.setText(String.valueOf(x));
operation = "";
break;
case "-":
x = x - Integer.parseInt(text.getText());
text.setText(String.valueOf(x));
operation = "";
break;
case "*":
x = x * Integer.parseInt(text.getText());
text.setText(String.valueOf(x));
operation = "";
break;
case "/":
x = x / Integer.parseInt(text.getText());
text.setText(String.valueOf(x));
operation = "";
}
}
private String processLength(String text) {
// TODO: 21.11.2020 1000000000 -> 1 000 000 0000
return null;
}
public void calculate(ActionEvent actionEvent) {
String operation = ((Button) actionEvent.getSource()).getText();
x = Integer.parseInt(text.getText());
text.setText("");
this.operation = operation;
}
public void enter(ActionEvent actionEvent) {
processEnter();
}
}
| 28.533333
| 72
| 0.492601
|
eaad8454d538cb95cbe29b63ccbd6fea9d067583
| 1,502
|
/*
* (C) Copyright 2021 Radix DLT Ltd
*
* Radix DLT Ltd licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
*/
package com.radixdlt.constraintmachine;
import com.radixdlt.atom.TxAction;
import java.util.List;
import java.util.Objects;
/**
* Action which was parsed by constraint machine from a transaction
*/
public final class REParsedAction {
private final TxAction txAction;
private final List<REParsedInstruction> instructions;
private REParsedAction(
TxAction txAction,
List<REParsedInstruction> instructions
) {
this.txAction = txAction;
this.instructions = instructions;
}
public static REParsedAction create(
TxAction txAction,
List<REParsedInstruction> instructions
) {
Objects.requireNonNull(txAction);
Objects.requireNonNull(instructions);
return new REParsedAction(txAction, instructions);
}
public TxAction getTxAction() {
return txAction;
}
public List<REParsedInstruction> getInstructions() {
return instructions;
}
}
| 25.896552
| 68
| 0.756991
|
b3eee16bdd7e03d571b559fe9156c4552fa0471e
| 6,541
|
/**
* Copyright 2009-2018 PrimeTek.
*
* 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.primefaces.model;
import org.primefaces.component.fileupload.FileUpload;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import javax.faces.FacesException;
import javax.servlet.http.Part;
import org.apache.commons.io.input.BoundedInputStream;
import org.primefaces.util.FileUploadUtils;
public class NativeUploadedFile implements UploadedFile, Serializable {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final String CONTENT_DISPOSITION_FILENAME_ATTR = "filename";
private Part part;
private String filename;
private byte[] cachedContent;
private Long sizeLimit;
private List<Part> parts;
private List<String> filenames;
public NativeUploadedFile() {
}
public NativeUploadedFile(Part part, FileUpload fileUpload) {
this.part = part;
this.filename = resolveFilename(part);
this.sizeLimit = fileUpload.getSizeLimit();
}
public NativeUploadedFile(List<Part> parts, FileUpload fileUpload) {
this.parts = parts;
this.filenames = resolveFilenames(parts);
this.sizeLimit = fileUpload.getSizeLimit();
}
@Override
public String getFileName() {
return filename;
}
@Override
public List<String> getFileNames() {
return filenames;
}
@Override
public InputStream getInputstream() throws IOException {
return sizeLimit == null ? part.getInputStream() : new BoundedInputStream(part.getInputStream(), sizeLimit);
}
@Override
public long getSize() {
return part.getSize();
}
@Override
public byte[] getContents() {
if (cachedContent != null) {
return cachedContent;
}
InputStream input = null;
try {
input = getInputstream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
cachedContent = output.toByteArray();
}
catch (IOException ex) {
cachedContent = null;
throw new FacesException(ex);
}
finally {
if (input != null) {
try {
input.close();
}
catch (IOException ex) {
}
}
}
return cachedContent;
}
@Override
public String getContentType() {
return part.getContentType();
}
@Override
public void write(String filePath) throws Exception {
String validFilePath = FileUploadUtils.getValidFilePath(filePath);
if (parts != null) {
for (int i = 0; i < parts.size(); i++) {
Part p = parts.get(i);
p.write(validFilePath);
}
}
else {
part.write(validFilePath);
}
}
public Part getPart() {
return part;
}
private String resolveFilename(Part part) {
return FileUploadUtils.getValidFilename(getContentDispositionFileName(part.getHeader("content-disposition")));
}
private List<String> resolveFilenames(List<Part> parts) {
filenames = new ArrayList<>();
for (int i = 0; i < parts.size(); i++) {
Part p = parts.get(i);
filenames.add(resolveFilename(p));
}
return filenames;
}
protected String getContentDispositionFileName(final String line) {
// skip to 'filename'
int i = line.indexOf(CONTENT_DISPOSITION_FILENAME_ATTR);
if (i == -1) {
return null; // does not contain 'filename'
}
// skip past 'filename'
i += CONTENT_DISPOSITION_FILENAME_ATTR.length();
final int lineLength = line.length();
// skip whitespace
while (i < lineLength && Character.isWhitespace(line.charAt(i))) {
i++;
}
// expect '='
if (i == lineLength || line.charAt(i++) != '=') {
throw new FacesException("Content-Disposition filename property did not have '='.");
}
// skip whitespace again
while (i < lineLength && Character.isWhitespace(line.charAt(i))) {
i++;
}
// expect '"'
if (i == lineLength || line.charAt(i++) != '"') {
throw new FacesException("Content-Disposition filename property was not quoted.");
}
// buffer to hold the file name
final StringBuilder b = new StringBuilder();
for (; i < lineLength; i++) {
final char c = line.charAt(i);
if (c == '"') {
return decode(b.toString());
}
// only unescape double quote, leave all others as-is, but still skip 2 characters
if (c == '\\' && i + 2 != lineLength) {
char next = line.charAt(++i);
if (next == '"') {
b.append('"');
}
else {
b.append(c);
b.append(next);
}
}
else {
b.append(c);
}
}
return decode(b.toString());
}
private String decode(String encoded) {
try {
// GitHub #3916 escape + and % before decode
encoded = encoded.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
encoded = encoded.replaceAll("\\+", "%2B");
return URLDecoder.decode(encoded, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
throw new FacesException(ex);
}
}
}
| 28.942478
| 118
| 0.574989
|
6bf797aa426d0a98f3f7a774d20249a57a08d9f4
| 13,357
|
package org.orienteer.core;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OClassImpl;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import org.apache.wicket.util.string.Strings;
import java.io.Serializable;
import java.util.*;
/**
* Orienteer needs in additional attributes specified for {@link OClass} and {@link OProperty}
* This class allow flexibly access to that custom parameters.
*/
public final class CustomAttribute implements Serializable
{
private static final Map<String, CustomAttribute> CACHE = new HashMap<String, CustomAttribute>();
/**
* Is this property calculable or not
*/
public static final CustomAttribute CALCULABLE = create("orienteer.calculable", OType.BOOLEAN, false, false, true);
/**
* Script to calculate value of the property
*/
public static final CustomAttribute CALC_SCRIPT = create("orienteer.script", OType.STRING, null, true, true);
/**
* Is this property displayable or not
*/
public static final CustomAttribute DISPLAYABLE = create("orienteer.displayable", OType.BOOLEAN, false, false, true);
/**
* Is this property should be readonly in UI
*/
public static final CustomAttribute UI_READONLY = create("orienteer.uireadonly", OType.BOOLEAN, false, false, true);
/**
* Is this property value should not be visible
*/
public static final CustomAttribute HIDDEN = create("orienteer.hidden", OType.BOOLEAN, false, false, true);
/**
* Order of this property in a table/tab
*/
public static final CustomAttribute ORDER = create("orienteer.order", OType.INTEGER, 0, false, true);
/**
* Name of the tab where this parameter should be shown
*/
public static final CustomAttribute TAB = create("orienteer.tab", OType.STRING, null, false, true);
/**
* Name of the property which is storing name of this entity
*/
public static final CustomAttribute PROP_NAME = create("orienteer.prop.name", OType.LINK, OProperty.class, null, false, true);
/**
* Name of property which is storing link to a parent entity
*/
public static final CustomAttribute PROP_PARENT = create("orienteer.prop.parent", OType.LINK, OProperty.class, null, false, true);
/**
* Name of a visualization that should be used for property visualization
*/
public static final CustomAttribute VISUALIZATION_TYPE = create("orienteer.visualization", OType.STRING, "default", false, true);
/**
* Link to an inverse property in respect to this one
*/
public static final CustomAttribute PROP_INVERSE = create("orienteer.inverse", OType.LINK, OProperty.class, null, false, true);
/**
* Description of {@link OProperty} or {@link OClass}
*/
public static final CustomAttribute DESCRIPTION = create("orienteer.description",OType.STRING,null,true, false);
/**
* Access levels ("_allow", "_allowRead", "_allowUpdate", or "_allowDelete") granted on document creation.
*/
public static final CustomAttribute ON_CREATE_FIELDS = create("onCreate.fields",OType.STRING,null,true, true);
/**
* Identity type ("user" or "role") who will get access rights on document creation.
*/
public static final CustomAttribute ON_CREATE_IDENTITY_TYPE = create("onCreate.identityType",OType.STRING,null,true, true);
/**
* Property name by which to sort data by default
*/
public static final CustomAttribute SORT_BY = create("orienteer.sortby", OType.LINK, OProperty.class, null, false, true);
/**
* Order in which to sort data
*/
public static final CustomAttribute SORT_ORDER = create("orienteer.sortorder", OType.BOOLEAN, null, null, false, true);
/**
* Default search query for class
*/
public static final CustomAttribute SEARCH_QUERY = create("orienteer.searchquery", OType.STRING, null, null, true, true);
/**
* Domain of a class
*/
public static final CustomAttribute DOMAIN = create("orienteer.domain", OType.STRING, OClassDomain.class, OClassDomain.BUSINESS, false, true);
/**
* Feature ID for a property
*/
public static final CustomAttribute FEATURE = create("orienteer.feature",OType.STRING,null,true, true);
/**
* DAO InterfaceClass
*/
@Deprecated
public static final CustomAttribute DAO_CLASS = create("orienteer.dao.class",OType.STRING,null,true, true);
/**
* Custom CSS Class(es) to be associated with OClass or OProperty
*/
public static final CustomAttribute CSS_CLASS = create("orienteer.cssclass", OType.STRING, null, true, true);
private final String name;
private final OType type;
private final Object defaultValue;
private final Class<?> javaClass;
private final boolean encode;
private final boolean hiearchical;
private CustomAttribute(String name, OType type, Class<?> javaClass, Object defaultValue, boolean encode, boolean hiearchical)
{
this.name = name;
this.type = type;
this.javaClass = javaClass!=null?javaClass:type.getDefaultJavaType();
this.defaultValue = defaultValue;
this.encode = encode;
this.hiearchical = hiearchical;
CACHE.put(name, this);
}
/*public static CustomAttribute create(String name, OType type, Object defaultValue, boolean encode) {
return create(name, type, null, defaultValue, encode, false);
}*/
/*public static CustomAttribute create(String name, OType type, Class<?> javaClass, Object defaultValue, boolean encode) {
return create(name, type, javaClass, defaultValue, encode, false);
}*/
public static CustomAttribute create(String name, OType type, Object defaultValue, boolean encode, boolean hiearchical) {
return create(name, type, null, defaultValue, encode, hiearchical);
}
public static CustomAttribute create(String name, OType type, Class<?> javaClass, Object defaultValue, boolean encode, boolean hiearchical) {
CustomAttribute ret = getIfExists(name);
if(ret!=null) throw new IllegalArgumentException("Custom attribute with name '"+name+"' is already exist");
ret = new CustomAttribute(name, type, javaClass, defaultValue, encode, hiearchical);
return ret;
}
public static CustomAttribute get(String name) {
CustomAttribute ret = getIfExists(name);
if(ret==null) throw new IllegalArgumentException("Custom attribute with name '"+name+"' was not found");
return ret;
}
public static CustomAttribute getOrCreate(String name, OType type, Object defaultValue, boolean encode, boolean hiearchical) {
return getOrCreate(name, type, null, defaultValue, encode, hiearchical);
}
public static CustomAttribute getOrCreate(String name, OType type, Class<?> javaClass, Object defaultValue, boolean encode, boolean hiearchical) {
CustomAttribute ret = getIfExists(name);
return ret != null ? ret : create(name, type, javaClass, defaultValue, encode, hiearchical);
}
public static CustomAttribute getIfExists(String name) {
return CACHE.get(name);
}
public static Collection<CustomAttribute> values() {
return Collections.unmodifiableCollection(CACHE.values());
}
public String getName() {
return name;
}
public boolean match(String critery)
{
return name.equals(critery);
}
public boolean matchAny(String... criteries)
{
if(criteries==null || criteries.length==0) return false;
for(String critery : criteries) {
if(name.equals(critery)) return true;
}
return false;
}
public boolean matchAny(CustomAttribute... criteries)
{
if(criteries==null || criteries.length==0) return false;
for(CustomAttribute critery : criteries) {
if(equals(critery)) return true;
}
return false;
}
public OType getType() {
return type;
}
public Class<?> getJavaClass() {
return javaClass;
}
public Object getDefaultValue() {
return defaultValue;
}
public boolean isEncode() {
return encode;
}
@SuppressWarnings("unchecked")
public <V> V getValue(OProperty property)
{
return getValue(property, (V) defaultValue);
}
@SuppressWarnings("unchecked")
public <V> V getValue(OProperty property, V defaultValue)
{
String stringValue = property.getCustom(name);
if(encode) stringValue = decodeCustomValue(stringValue);
V ret;
if(OProperty.class.isAssignableFrom(javaClass))
{
ret = (V)resolveProperty(property.getOwnerClass(), stringValue);
}
else
{
ret = (V) OType.convert(stringValue, javaClass);
}
return ret!=null?ret:defaultValue;
}
public <V> void setValue(OProperty property, V value)
{
if(OProperty.class.isAssignableFrom(javaClass) && value instanceof OProperty)
{
OProperty valueProperty = (OProperty)value;
boolean fullNameRequired = !Objects.equals(property.getOwnerClass(), valueProperty.getOwnerClass());
property.setCustom(name, fullNameRequired?valueProperty.getFullName():valueProperty.getName());
}
else
{
if(defaultValue!=null && defaultValue.equals(value)) value = null;
String stringValue = value!=null?value.toString():null;
if(stringValue!=null && stringValue.length()==0) stringValue=null;
if(encode) stringValue = encodeCustomValue(stringValue);
property.setCustom(name, stringValue);
}
}
public <V> V getValue(OClass oClass) {
return getValue(oClass, hiearchical);
}
@SuppressWarnings("unchecked")
public <V> V getValue(OClass oClass, boolean hiearchical)
{
return getValue(oClass, (V) defaultValue, hiearchical);
}
public <V> V getValue(OClass oClass, V defaultValue) {
return getValue(oClass, defaultValue, hiearchical);
}
@SuppressWarnings("unchecked")
public <V> V getValue(OClass oClass, V defaultValue, boolean hiearchical)
{
String stringValue = oClass.getCustom(name);
if(encode) stringValue = decodeCustomValue(stringValue);
V ret;
if(OProperty.class.isAssignableFrom(javaClass))
{
ret = (V)resolveProperty(oClass, stringValue);
}
else
{
ret = (V) OType.convert(stringValue, javaClass);
}
if(ret==null && hiearchical) {
for(OClass superClass : oClass.getSuperClasses()) {
if((ret=getValue(superClass, null, true))!=null) break;
}
}
return ret!=null?ret:defaultValue;
}
public <V> void setValue(OClass oClass, V value) {
setValue(oClass, value, hiearchical);
}
public <V> void setValue(OClass oClass, V value, boolean hiearchical)
{
if(hiearchical && Objects.equals(value, getValue(oClass, true))) return;
if(OProperty.class.isAssignableFrom(javaClass) && value instanceof OProperty)
{
OProperty valueProperty = (OProperty)value;
boolean fullNameRequired = !Objects.equals(oClass, valueProperty.getOwnerClass());
oClass.setCustom(name, fullNameRequired?valueProperty.getFullName():valueProperty.getName());
}
else
{
if(!hiearchical && defaultValue!=null && defaultValue.equals(value)) value = null;
String stringValue = value!=null?value.toString():null;
if(stringValue!=null && stringValue.length()==0) stringValue=null;
if(encode) stringValue = encodeCustomValue(stringValue);
oClass.setCustom(name, stringValue);
}
}
private OProperty resolveProperty(OClass oClass, String propertyName)
{
if(Strings.isEmpty(propertyName)) return null;
int indx = propertyName.indexOf('.');
if(indx>0)
{
String className = propertyName.substring(0, indx);
propertyName = propertyName.substring(indx+1);
oClass = ((OClassImpl)oClass).getOwner().getClass(className);
if(oClass==null) return null;
}
return oClass.getProperty(propertyName);
}
public static boolean match(String critery, CustomAttribute... attrs)
{
for (CustomAttribute customAttributes : attrs)
{
if(customAttributes.match(critery)) return true;
}
return false;
}
public static String encodeCustomValue(String value)
{
if(value==null) return null;
StringBuilder sb = new StringBuilder(value.length());
for(int i=0; i<value.length();i++)
{
char ch = value.charAt(i);
switch (ch)
{
case '=':
sb.append("\\e");
break;
case '\\':
sb.append("\\\\");
break;
case '\r':
sb.append("\\r");
break;
case '\n':
sb.append("\\n");
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
public static String decodeCustomValue(String value)
{
if(value==null) return null;
StringBuilder sb = new StringBuilder(value.length());
for(int i=0; i<value.length();i++)
{
char ch = value.charAt(i);
if(ch!='\\')
{
sb.append(ch);
}
else
{
if(++i>=value.length())
{
sb.append('\\');
break;
}
else
{
ch = value.charAt(i);
switch (ch)
{
case 'e':
sb.append('=');
break;
case '\\':
sb.append('\\');
break;
case 'r':
sb.append('\r');
break;
case 'n':
sb.append('\n');
break;
default:
sb.append('\\').append(ch);
break;
}
}
}
}
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomAttribute other = (CustomAttribute) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
| 30.356818
| 147
| 0.706296
|
53d1e103ff407d0e2efd28f522a7423cc17aa61a
| 2,742
|
/*
* Copyright 2010-2012 VMware and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springsource.loaded.testgen;
import org.junit.Assert;
import org.springsource.loaded.MethodInvokerRewriter;
import org.springsource.loaded.ReloadableType;
import org.springsource.loaded.TypeRegistry;
import org.springsource.loaded.test.SpringLoadedTests;
/**
* Implements IClassProvider for a test execution context where classes are loaded and instrumented by SpringLoaded.
*
* @author kdvolder
*/
public class SpringLoadedClassProvider extends SpringLoadedTests implements IClassProvider {
private TypeRegistry typeRegistry;
public SpringLoadedClassProvider(String typeRegistryConfig) throws Exception {
setup();
typeRegistry = getTypeRegistry(typeRegistryConfig);
}
public Class<?> loadClassVersion(String typeName, String version) {
if (typeRegistry.isReloadableTypeName(typeName.replace('.', '/'))) {
ReloadableType rtype = reloadableClass(typeName);
if (!version.equals("")) {
int targetVersion = Integer.valueOf(version);
int loadedVersion = 1; //By convention version numbers of reloaded types start from "002".
while (loadedVersion < targetVersion) {
String nextVersion = String.format("%03d", ++loadedVersion);
reloadType(rtype, nextVersion);
}
Assert.assertEquals(targetVersion, loadedVersion);
}
return rtype.getClazz();
}
else {
Assert.assertEquals("Non reloadable types shouldn't have versions!", "", version);
return nonReloadableClass(typeName);
}
}
protected ReloadableType reloadableClass(String className) {
return typeRegistry.addType(className, loadBytesForClass(className));
}
protected Class<?> nonReloadableClass(String className) {
byte[] rewrittenBytes = MethodInvokerRewriter.rewrite(typeRegistry, loadBytesForClass(className));
return loadit(className, rewrittenBytes);
}
protected void reloadType(ReloadableType target, String version) {
String targetClassName = target.getClazz().getName();
target.loadNewVersion(version, retrieveRename(targetClassName, targetClassName + version));
}
/**
* Only for testing purposes
*/
public ClassLoader getClassLoader() {
return binLoader;
}
}
| 33.851852
| 116
| 0.761123
|
0b04d5c12aeaf4d76acb752c3d481049ab0f9270
| 1,030
|
package org.jglr.sbm.instructions;
import org.jglr.sbm.InfoPool;
import org.jglr.sbm.Opcodes;
import org.jglr.sbm.types.Type;
public class SpecConstantBoolInstruction extends ResultInstruction implements ResolvableInstruction {
private final long resultTypeID;
private final boolean defaultValue;
private Type resultType;
public SpecConstantBoolInstruction(long resultType, long resultID, boolean defaultValue) {
super(defaultValue ? OpSpecConstantTrue : OpSpecConstantFalse, 4, resultID);
this.resultTypeID = resultType;
this.defaultValue = defaultValue;
}
public long getResultTypeID() {
return resultTypeID;
}
public boolean isDefaultValue() {
return defaultValue;
}
@Override
public void onVisitEnd(InfoPool infoPool) {
resultType = infoPool.getType(resultTypeID);
}
@Override
public String toString() {
return Opcodes.getName(getOpcode())+" "+nameOrID(resultTypeID, resultType)+" = "+defaultValue;
}
}
| 28.611111
| 102
| 0.715534
|
3557d444be47c87f3ec8b9efe1bf7a383e087751
| 3,663
|
package Hashtable;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Scanner;
public class Studentdetails {
static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
Hashtable<Integer,Student>atable= new Hashtable<Integer,Student>();
Studentdetails stud=new Studentdetails();
while (true) {
System.out.println("1,addstudent");
System.out.println("2,search student");
System.out.println("3,delete student");
System.out.println("4,print all the studentdetails");
System.out.println("5,exit");
System.out.println(" Please enter the operation to perform");
int ch = sc.nextInt();
switch (ch) {
case 1:
atable=stud.addStud(atable);
break;
case 2:
stud.searchstud(atable);
break;
case 3:
atable=stud.removestud(atable);
break;
case 4:
stud.updatestud(atable);
break;
case 5:
stud.displayAll(atable);
break;
case 6:
System.out.println("Thank you for your use");
System.exit(0);
break;
default:
System.out.println("You have entered invalid number");
}
}
}
private void updatestud(Hashtable<Integer, Student> atable) {
System.out.println("\n Enter key to update: ");
int key1=sc.nextInt();
for(Map.Entry<Integer,Student> eachvalue : atable.entrySet())
{
Student str= eachvalue.getValue();
if (eachvalue.getKey() == key1) {
Student student1 = new Student();
System.out.println("Enter KEY:");
int key2=sc.nextInt();
System.out.println("Enter Student Id");
int id1 =sc.nextInt();
System.out.println("Enter Student name");
String name2=sc.next();
System.out.println("Enter Student address");
String hr=sc.next();
atable.replace(key1,student1);
}
}
}
private void displayAll(Hashtable<Integer, Student> atable) {
for (Map.Entry<Integer, Student> entry : atable.entrySet()) {
Student str = entry.getValue();
System.out.println(
entry.getKey() + " " + "student id:" + str.id + "name:" + str.name + "address:" + str.address);
}
}
private Hashtable<Integer, Student> removestud(Hashtable<Integer, Student> atable) {
System.out.println(" enter the id want to remove");
int id1=sc.nextInt();
for(Map.Entry<Integer, Student>entry:atable.entrySet())
{
Student str=entry.getValue();
if(entry.getKey()==id1)
{
atable.remove(entry.getKey());
System.out.println(entry.getKey()+" "+ "student id:"+str.id+"name:"+str.name+"address:"+str.address+" was deleted successfully");
}
}
return atable;
}
private void searchstud(Hashtable<Integer, Student> atable) {
System.out.println(" enter the id want to search");
int id3=sc.nextInt();
for(Map.Entry<Integer, Student>entry:atable.entrySet())
{
Student str=entry.getValue();
if(str.id==id3)
{
System.out.println(entry.getKey()+" "+ "student id:"+str.id+"name:"+str.name+"address:"+str.address);
}
}
}
private Hashtable<Integer, Student> addStud(Hashtable<Integer, Student> atable) {
System.out.println(" enter the no of students want to enter");
int num=sc.nextInt();
Student stud=new Student();
for(int index=0;index<num;index++)
{
System.out.println("Enter KEY:");
int key=sc.nextInt();
System.out.println("please enter"+(index+1)+"student id");
int id=sc.nextInt();
System.out.println("please enter"+(index+1)+"student name");
String name=sc.next();
System.out.println("please enter"+(index+1)+"student address");
String add=sc.next();
atable.put(key,stud);
}
return atable;
}
}
| 24.098684
| 133
| 0.650287
|
afb34315260aca0e88cb4b83a75163050dd04c83
| 2,201
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.gestures;
import static android.provider.Settings.Secure.VOLUME_HUSH_GESTURE;
import static android.provider.Settings.Secure.VOLUME_HUSH_MUTE;
import static android.provider.Settings.Secure.VOLUME_HUSH_VIBRATE;
import android.content.Context;
import android.provider.Settings;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
public class PreventRingingParentPreferenceController extends BasePreferenceController {
final String SECURE_KEY = VOLUME_HUSH_GESTURE;
public PreventRingingParentPreferenceController(Context context, String preferenceKey) {
super(context, preferenceKey);
}
@Override
public int getAvailabilityStatus() {
return mContext.getResources().getBoolean(
com.android.internal.R.bool.config_volumeHushGestureEnabled)
? AVAILABLE_UNSEARCHABLE : UNSUPPORTED_ON_DEVICE;
}
@Override
public CharSequence getSummary() {
int value = Settings.Secure.getInt(
mContext.getContentResolver(), SECURE_KEY, VOLUME_HUSH_VIBRATE);
int summary;
switch (value) {
case VOLUME_HUSH_VIBRATE:
summary = R.string.prevent_ringing_option_vibrate_summary;
break;
case VOLUME_HUSH_MUTE:
summary = R.string.prevent_ringing_option_mute_summary;
break;
default:
summary = R.string.prevent_ringing_option_none_summary;
}
return mContext.getText(summary);
}
}
| 35.5
| 92
| 0.715584
|
475ad1f0765754886cd6c59c1d3d58ee633b39be
| 485
|
package cn.edu.gdut.douyintoutiao.net;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Url;
@Deprecated
public interface ImageApi {
@GET
Call<ResponseBody> getImg(@Url String url);
/**
* 单例内部类
*/
class Singleton {
static ImageApi imageApi = RetrofitSingleton.getInstance().create(ImageApi.class);
}
static ImageApi getImageApi() {
return ImageApi.Singleton.imageApi;
}
}
| 17.962963
| 90
| 0.68866
|
2b9e96b50bdb12f6d823d28afa554be410f62a40
| 193
|
class Solution {
public int XXX(int x) {
long n = x;
while(n*n>x){
n = (n+x/n)/2;
System.out.println(n);
}
return (int)n;
}
}
| 13.785714
| 34
| 0.388601
|
459acc98ae3ceae1b0169caab00c410773514181
| 1,106
|
/*
* Copyright 2018 ARP Network
*
* 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.arpnetwork.arpdevice.contracts.tasks;
import org.arpnetwork.arpdevice.ui.bean.Miner;
import org.arpnetwork.arpdevice.ui.miner.BindMinerHelper;
public class GetBoundTask extends AbsExceptionTask<String, String, Miner> {
public GetBoundTask(OnValueResult<Miner> onValueResult) {
super(onValueResult);
}
@Override
public Miner onInBackground(String... param) throws Exception {
String address = param[0];
return BindMinerHelper.getBound(address);
}
}
| 31.6
| 75
| 0.73689
|
877f50a517f01ae32b042a502878ee6dc0075805
| 832
|
package de.larsgrefer.sass.embedded.importer;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class CanonicalizationHelperTest {
@Test
void resolvePossiblePaths_noExt() {
List<String> strings = CanonicalizationHelper.resolvePossiblePaths("foo/bar/baz");
assertThat(strings).containsExactly(
"foo/bar/baz.sass",
"foo/bar/baz.scss",
"foo/bar/_baz.sass",
"foo/bar/_baz.scss"
);
}
@Test
void resolvePossiblePaths_ext() {
List<String> strings = CanonicalizationHelper.resolvePossiblePaths("foo/bar/baz.scss");
assertThat(strings).containsExactly(
"foo/bar/baz.scss",
"foo/bar/_baz.scss"
);
}
}
| 26
| 95
| 0.620192
|
dfef48a0329fedec4b39b87a623b3b85fd67dc62
| 1,227
|
class SimpleLocal {
class Inher {}
public int field = 15;
public void inc(int x) {
class Local3 {
public int anonField = 4;
public void run (int a) {
int x = 15;
// omp parallel
{
int foo = anonField + this.anonField + x + a + field;
foo = anonField;
foo = this.anonField;
foo = x;
foo = a;
foo = field;
}
}
}
}
// complex example - params and locals must be declared final
class Nested1 {
int f1 = 0;
void m1(final int n1) {
final int l1 = 0;
class Local1 {
int f2 = 0;
class Nested2 {
int f3 = 0;
void m2(final int n2){
final int l2 = 0;
class Local2 {
int f4 = 0;
void m3(final int n3) {
final int l3 = 0;
// omp parallel
{
int temp =
field +
f1 +
f2 +
f3 +
f4 +
n1 +
n2 +
n3 +
l1 +
l2 +
l3;
}
}
}
}
}
}
}
}
class Nested2 {
int field1;
void m1(final int x) {
// omp parallel
{
class Local {
int field2;
void m2(int y) {
int tmp = x + y + field1 + field2;
}
}
}
}
}
}
| 15.531646
| 62
| 0.440098
|
825a7a7131bc8b7b1e18f31a517d16630187c01e
| 48
|
package org.w3c.dom.ls;
public class Toto {
}
| 8
| 23
| 0.6875
|
f834ea6e34b33b547ee60cbff99cd3d85dfc83ba
| 1,552
|
package com.alibaba.rocketmq.filtersrv.stats;
import com.alibaba.rocketmq.common.ThreadFactoryImpl;
import com.alibaba.rocketmq.common.constant.LoggerName;
import com.alibaba.rocketmq.common.stats.StatsItemSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class FilterServerStatsManager {
private static final Logger log = LoggerFactory.getLogger(LoggerName.FiltersrvLoggerName);
private final ScheduledExecutorService scheduledExecutorService = Executors
.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("FSStatsThread"));
// ConsumerGroup Get Nums
private final StatsItemSet groupGetNums = new StatsItemSet("GROUP_GET_NUMS",
this.scheduledExecutorService, log);
// ConsumerGroup Get Size
private final StatsItemSet groupGetSize = new StatsItemSet("GROUP_GET_SIZE",
this.scheduledExecutorService, log);
public FilterServerStatsManager() {
}
public void start() {
}
public void shutdown() {
this.scheduledExecutorService.shutdown();
}
public void incGroupGetNums(final String group, final String topic, final int incValue) {
this.groupGetNums.addValue(topic + "@" + group, incValue, 1);
}
public void incGroupGetSize(final String group, final String topic, final int incValue) {
this.groupGetSize.addValue(topic + "@" + group, incValue, 1);
}
}
| 31.673469
| 95
| 0.721005
|
fda99049e7c3750457823dc6850b8a4d80ff9256
| 1,205
|
package com.lachesis.support.common.util.crypt.bootstrap;
import java.io.PrintStream;
import com.lachesis.support.common.util.crypt.CryptUtils;
import com.lachesis.support.common.util.exception.CryptException;
public class PasswordCryptTool {
public static void main(String[] args) {
if(args.length < 1){
printUsage(System.out);
System.exit(-1);
}
String plaintext = args[0];
printUsageIfHelp(args[0]);
try {
String digestData = CryptUtils.digest(plaintext);
printResult(digestData);
} catch (CryptException e) {
printResult(e.getMessage(),System.err);
}
}
private static void printUsageIfHelp(String cmd){
if("-h".equalsIgnoreCase(cmd) || "--help".equalsIgnoreCase(cmd)){
printUsage(System.out);
System.exit(-1);
}
}
private static void printUsage(PrintStream ps){
String msg = "Usage:\n";
msg += "pwtool <text>\n";
msg += "java com.lachesis.support.common.util.crypt.bootstrap.PasswordCryptTool <password>";
ps.println(msg);
}
private static void printResult(String s){
printResult(s,null);
}
private static void printResult(String s, PrintStream ps){
if(ps == null){
ps = System.out;
}
ps.println(s);
}
}
| 21.517857
| 94
| 0.693776
|
b2eccee8cbb16ec8cb8b8a622b29aff98f937d45
| 11,210
|
package eu.inloop.knight;
import android.app.Activity;
import android.app.Application;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic;
import eu.inloop.knight.builder.ActivityBuilders;
import eu.inloop.knight.builder.AppBuilders;
import eu.inloop.knight.builder.Injectable;
import eu.inloop.knight.name.EClass;
import eu.inloop.knight.util.ProcessorError;
import eu.inloop.knight.util.ProcessorUtils;
import static eu.inloop.knight.util.ProcessorUtils.getParamClasses;
/**
* Class {@link KnightProcessor}
*
* @author FrantisekGazo
* @version 2015-10-15
*/
@AutoService(Processor.class)
public class KnightProcessor extends AbstractProcessor {
private Messager mMessager;
private Filer mFiler;
private boolean mProcessed;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
mMessager = processingEnv.getMessager();
mFiler = processingEnv.getFiler();
mProcessed = false;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return annotations(
KnightApp.class,
KnightActivity.class,
Extra.class,
AppProvided.class,
ScreenProvided.class,
ActivityProvided.class,
Inject.class
);
}
private Set<String> annotations(Class... annotations) {
Set<String> set = new HashSet<>();
for (Class a : annotations) {
set.add(a.getCanonicalName());
}
return set;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (mProcessed) return false;
mProcessed = true;
try {
// collect all classes with some @Inject field
Map<ClassName, Injectable> classesWithInject = new HashMap<>();
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Inject.class);
for (Element e : elements) {
System.out.printf("@KnightProcessor : Inject %s", e.getSimpleName());
if (e instanceof VariableElement && e.getEnclosingElement() instanceof TypeElement) {
TypeElement enclosing = (TypeElement) e.getEnclosingElement();
classesWithInject.put(ClassName.get(enclosing), new Injectable(enclosing));
System.out.printf(" is injectable in %s", enclosing.getSimpleName());
}
System.out.println();
}
// create Knight Application Builders
elements = roundEnv.getElementsAnnotatedWith(KnightApp.class);
TypeElement appElement = getKnightAppName(elements);
ClassName appClassName = ClassName.get(appElement);
AppBuilders appBuilders = new AppBuilders(appClassName);
// add injectable classes
appBuilders.setInjectables(getParamClasses(appElement.getAnnotation(KnightApp.class),
new ProcessorUtils.IGetter<KnightApp, Class<?>[]>() {
@Override
public Class<?>[] get(KnightApp a) {
return a.value();
}
}), classesWithInject);
// go through Knight Activities
elements = roundEnv.getElementsAnnotatedWith(KnightActivity.class);
Map<ClassName, ActivityBuilders> activityBuildersMap = new HashMap<>();
for (Element e : elements) {
// create Knight Activity Builders
ClassName activityName = getKnightActivityName((TypeElement) e);
ActivityBuilders activityBuilders = new ActivityBuilders(activityName);
activityBuildersMap.put(activityName, activityBuilders);
// add injectable classes
activityBuilders.setInjectables(getParamClasses(e.getAnnotation(KnightActivity.class),
new ProcessorUtils.IGetter<KnightActivity, Class<?>[]>() {
@Override
public Class<?>[] get(KnightActivity a) {
return a.value();
}
}), classesWithInject);
// create navigator methods
appBuilders.Navigator.integrate((TypeElement) e, activityBuilders);
}
// add method to Injector
for (Map.Entry<ClassName, Injectable> entry : classesWithInject.entrySet()) {
if (entry.getValue().isValid()) {
appBuilders.Injector.addInjectMethod(appBuilders.Knight, entry.getValue());
}
}
// add Provided
elements = roundEnv.getElementsAnnotatedWith(AppProvided.class);
for (Element e : elements) {
switch (e.getKind()) {
case CONSTRUCTOR:
appBuilders.AppM.addProvidesConstructor((ExecutableElement) e);
break;
case METHOD:
appBuilders.AppM.addProvidesMethod((ExecutableElement) e);
break;
case CLASS:
appBuilders.AppC.addModule((TypeElement) e);
break;
}
}
elements = roundEnv.getElementsAnnotatedWith(ScreenProvided.class);
for (Element e : elements) {
List<ClassName> in = getParamClasses(e.getAnnotation(ScreenProvided.class), new ProcessorUtils.IGetter<ScreenProvided, Class<?>[]>() {
@Override
public Class<?>[] get(ScreenProvided annotation) {
return annotation.value();
}
});
ActivityBuilders activityBuilders;
for (ClassName activity : in) {
activityBuilders = activityBuildersMap.get(activity);
if (activityBuilders == null) {
throw new ProcessorError(e, ErrorMsg.Provided_outside_Scoped_Activity);
}
switch (e.getKind()) {
case CONSTRUCTOR:
activityBuilders.SM.addProvidesConstructor((ExecutableElement) e);
break;
case METHOD:
activityBuilders.SM.addProvidesMethod((ExecutableElement) e);
break;
case CLASS:
activityBuilders.SC.addModule((TypeElement) e);
break;
}
}
}
elements = roundEnv.getElementsAnnotatedWith(ActivityProvided.class);
for (Element e : elements) {
List<ClassName> in = getParamClasses(e.getAnnotation(ActivityProvided.class), new ProcessorUtils.IGetter<ActivityProvided, Class<?>[]>() {
@Override
public Class<?>[] get(ActivityProvided annotation) {
return annotation.value();
}
});
ActivityBuilders activityBuilders;
for (ClassName activity : in) {
activityBuilders = activityBuildersMap.get(activity);
if (activityBuilders == null) {
throw new ProcessorError(e, ErrorMsg.Provided_outside_Scoped_Activity);
}
switch (e.getKind()) {
case CONSTRUCTOR:
activityBuilders.AM.addProvidesConstructor((ExecutableElement) e);
break;
case METHOD:
activityBuilders.AM.addProvidesMethod((ExecutableElement) e);
break;
case CLASS:
activityBuilders.AC.addModule((TypeElement) e);
break;
}
}
}
// build everything
for (Map.Entry<ClassName, ActivityBuilders> activityBuildersEntry : activityBuildersMap.entrySet()) {
activityBuildersEntry.getValue().buildAll(appBuilders, mFiler);
}
appBuilders.add(activityBuildersMap.values());
appBuilders.buildAll(mFiler);
} catch (ProcessorError pe) {
error(pe);
} catch (IOException ioe) {
ioe.printStackTrace();
}
return false;
}
private TypeElement getKnightAppName(Set<? extends Element> elements) throws ProcessorError {
if (elements.isEmpty()) {
throw new ProcessorError(null, ErrorMsg.Missing_Knight_App);
}
TypeElement appElement = null;
for (Element e : elements) {
checkKnightApp((TypeElement) e);
if (appElement != null) {
throw new ProcessorError(e, ErrorMsg.More_Knight_Apps);
} else {
appElement = (TypeElement) e;
}
}
return appElement;
}
private void checkKnightApp(TypeElement e) throws ProcessorError {
if (!e.getModifiers().contains(Modifier.PUBLIC)) {
throw new ProcessorError(e, ErrorMsg.Invalid_Knight_App);
}
if (!ProcessorUtils.isSubClassOf(e, Application.class)) {
throw new ProcessorError(e, ErrorMsg.Invalid_Knight_App);
}
}
private ClassName getKnightActivityName(TypeElement e) throws ProcessorError {
if (!ProcessorUtils.isSubClassOf(e, EClass.AppCompatActivity.getName(), ClassName.get(Activity.class))) {
throw new ProcessorError(e, ErrorMsg.Scoped_invalid);
}
return ClassName.get(e);
}
private void error(ProcessorError error) {
mMessager.printMessage(Diagnostic.Kind.ERROR, error.getMessage(), error.getElement());
}
private void error(Element e, ErrorMsg msg, Object... args) {
mMessager.printMessage(Diagnostic.Kind.ERROR, String.format(msg.toString(), args), e);
}
}
| 41.062271
| 154
| 0.582426
|
c2d4bdb2276e53e6ee93a800ff4169501c61ff70
| 4,714
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.expr.fn;
import com.google.common.collect.Lists;
import mockit.Invocation;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import org.apache.drill.categories.SqlFunctionTest;
import org.apache.drill.test.TestTools;
import org.apache.drill.exec.util.JarUtil;
import org.codehaus.janino.Java;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(JMockit.class)
@Category(SqlFunctionTest.class)
public class FunctionInitializerTest {
private static final String CLASS_NAME = "com.drill.udf.CustomLowerFunction";
private static URLClassLoader classLoader;
@BeforeClass
public static void init() throws Exception {
Path jars = TestTools.WORKING_PATH
.resolve(TestTools.TEST_RESOURCES)
.resolve("jars");
String binaryName = "DrillUDF-1.0.jar";
String sourceName = JarUtil.getSourceName(binaryName);
URL[] urls = {jars.resolve(binaryName).toUri().toURL(), jars.resolve(sourceName).toUri().toURL()};
classLoader = new URLClassLoader(urls);
}
@Test
public void testGetImports() {
FunctionInitializer functionInitializer = new FunctionInitializer(CLASS_NAME, classLoader);
List<String> actualImports = functionInitializer.getImports();
List<String> expectedImports = Lists.newArrayList(
"import io.netty.buffer.DrillBuf;",
"import org.apache.drill.exec.expr.DrillSimpleFunc;",
"import org.apache.drill.exec.expr.annotations.FunctionTemplate;",
"import org.apache.drill.exec.expr.annotations.Output;",
"import org.apache.drill.exec.expr.annotations.Param;",
"import org.apache.drill.exec.expr.holders.VarCharHolder;",
"import javax.inject.Inject;"
);
assertEquals("List of imports should match", expectedImports, actualImports);
}
@Test
public void testGetMethod() {
FunctionInitializer functionInitializer = new FunctionInitializer(CLASS_NAME, classLoader);
String actualMethod = functionInitializer.getMethod("eval");
assertTrue("Method body should match", actualMethod.contains("CustomLowerFunction_eval:"));
}
@Test
public void testConcurrentFunctionBodyLoad() throws Exception {
final FunctionInitializer functionInitializer = new FunctionInitializer(CLASS_NAME, classLoader);
final AtomicInteger counter = new AtomicInteger();
new MockUp<FunctionInitializer>() {
@Mock
Java.CompilationUnit convertToCompilationUnit(Invocation inv, Class<?> clazz) {
counter.incrementAndGet();
return inv.proceed();
}
};
int threadsNumber = 5;
ExecutorService executor = Executors.newFixedThreadPool(threadsNumber);
try {
List<Future<String>> results = executor.invokeAll(Collections.nCopies(threadsNumber, new Callable<String>() {
@Override
public String call() throws Exception {
return functionInitializer.getMethod("eval");
}
}));
final Set<String> uniqueResults = new HashSet<>();
for (Future<String> result : results) {
uniqueResults.add(result.get());
}
assertEquals("All threads should have received the same result", 1, uniqueResults.size());
assertEquals("Number of function body loads should match", 1, counter.intValue());
} finally {
executor.shutdownNow();
}
}
}
| 36.261538
| 115
| 0.741196
|
acc62697b9d686bc86899f1101e4add7f68e43c0
| 809
|
package hdr.mnist.weka;
public class MeanFilter {
public static int[][] blur(int[][] image, int numRows, int numCols, int filterSize) {
int[][] padding = new int[numRows + filterSize / 2 * 2][numCols + filterSize / 2 * 2];
for (int row = filterSize / 2; row < padding.length - filterSize / 2; row++) {
for (int col = filterSize / 2; col < padding[row].length - filterSize / 2; col++)
padding[row][col] = image[row - filterSize / 2][col - filterSize / 2];
}
for (int row = 0; row < image.length; row++) {
for (int col = 0; col < image[row].length; col++) {
int sum = 0;
for (int i = 0; i < filterSize; i++) {
for (int j = 0; j < filterSize; j++)
sum += padding[row + i][col + j];
}
image[row][col] = sum / (filterSize * filterSize);
}
}
return image;
}
}
| 35.173913
| 88
| 0.580964
|
83f6d2a4ebc3f07d4dd918166c8053b8e88c1ddc
| 2,404
|
// Copyright 2017 JanusGraph Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.janusgraph.core.schema;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public interface SchemaManager extends SchemaInspector {
/**
* Returns a {@link org.janusgraph.core.schema.PropertyKeyMaker} instance to define a new {@link org.janusgraph.core.PropertyKey} with the given name.
* By defining types explicitly (rather than implicitly through usage) one can control various
* aspects of the key and associated consistency constraints.
* <p>
* The key constructed with this maker will be created in the context of this transaction.
*
* @return a {@link org.janusgraph.core.schema.PropertyKeyMaker} linked to this transaction.
* @see org.janusgraph.core.schema.PropertyKeyMaker
* @see org.janusgraph.core.PropertyKey
*/
public PropertyKeyMaker makePropertyKey(String name);
/**
* Returns a {@link org.janusgraph.core.schema.EdgeLabelMaker} instance to define a new {@link org.janusgraph.core.EdgeLabel} with the given name.
* By defining types explicitly (rather than implicitly through usage) one can control various
* aspects of the label and associated consistency constraints.
* <p>
* The label constructed with this maker will be created in the context of this transaction.
*
* @return a {@link org.janusgraph.core.schema.EdgeLabelMaker} linked to this transaction.
* @see org.janusgraph.core.schema.EdgeLabelMaker
* @see org.janusgraph.core.EdgeLabel
*/
public EdgeLabelMaker makeEdgeLabel(String name);
/**
* Returns a {@link VertexLabelMaker} to define a new vertex label with the given name. Note, that the name must
* be unique.
*
* @param name
* @return
*/
public VertexLabelMaker makeVertexLabel(String name);
}
| 40.745763
| 154
| 0.721298
|
189bdaf11c3824c5c932087df0a8e9494d05800c
| 1,263
|
package alpha.nomagichttp.internal;
import alpha.nomagichttp.message.Attributes;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Small tests for {@link DefaultAttributes}
*
* @author Martin Andersson (webmaster at martinandersson.com)
*/
class DefaultAttributesTest {
private final Attributes testee = new DefaultAttributes();
@Test
void attributes_set_get() {
Object o = testee.set("msg", "hello");
assertThat(o).isNull();
String n = testee.getAny("msg");
assertThat(n).isEqualTo("hello");
}
@Test
void class_cast_exception_immediate() {
testee.set("int", 123);
assertThatThrownBy(() -> {
String crash = testee.getAny("int");
}).isExactlyInstanceOf(ClassCastException.class);
}
@Test
void class_cast_exception_delayed() {
testee.set("int", 123);
Optional<String> opt = testee.getOptAny("int");
assertThatThrownBy(() -> {
String crash = opt.get();
}).isExactlyInstanceOf(ClassCastException.class);
}
}
| 29.372093
| 66
| 0.633413
|
04630fd3734298d6c5220a4f523425d8e252307b
| 5,748
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.hadoop.mapred.lib.db
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|mapred
operator|.
name|lib
operator|.
name|db
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|NullWritable
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|mapred
operator|.
name|JobConf
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertNull
import|;
end_import
begin_class
DECL|class|TestConstructQuery
specifier|public
class|class
name|TestConstructQuery
block|{
DECL|field|fieldNames
specifier|private
name|String
index|[]
name|fieldNames
init|=
operator|new
name|String
index|[]
block|{
literal|"id"
block|,
literal|"name"
block|,
literal|"value"
block|}
decl_stmt|;
DECL|field|nullFieldNames
specifier|private
name|String
index|[]
name|nullFieldNames
init|=
operator|new
name|String
index|[]
block|{
literal|null
block|,
literal|null
block|,
literal|null
block|}
decl_stmt|;
DECL|field|expected
specifier|private
name|String
name|expected
init|=
literal|"INSERT INTO hadoop_output (id,name,value) VALUES (?,?,?);"
decl_stmt|;
DECL|field|nullExpected
specifier|private
name|String
name|nullExpected
init|=
literal|"INSERT INTO hadoop_output VALUES (?,?,?);"
decl_stmt|;
DECL|field|format
specifier|private
name|DBOutputFormat
argument_list|<
name|DBWritable
argument_list|,
name|NullWritable
argument_list|>
name|format
init|=
operator|new
name|DBOutputFormat
argument_list|<
name|DBWritable
argument_list|,
name|NullWritable
argument_list|>
argument_list|()
decl_stmt|;
annotation|@
name|Test
DECL|method|testConstructQuery ()
specifier|public
name|void
name|testConstructQuery
parameter_list|()
block|{
name|String
name|actual
init|=
name|format
operator|.
name|constructQuery
argument_list|(
literal|"hadoop_output"
argument_list|,
name|fieldNames
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
name|actual
operator|=
name|format
operator|.
name|constructQuery
argument_list|(
literal|"hadoop_output"
argument_list|,
name|nullFieldNames
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|nullExpected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
DECL|method|testSetOutput ()
specifier|public
name|void
name|testSetOutput
parameter_list|()
throws|throws
name|IOException
block|{
name|JobConf
name|job
init|=
operator|new
name|JobConf
argument_list|()
decl_stmt|;
name|DBOutputFormat
operator|.
name|setOutput
argument_list|(
name|job
argument_list|,
literal|"hadoop_output"
argument_list|,
name|fieldNames
argument_list|)
expr_stmt|;
name|DBConfiguration
name|dbConf
init|=
operator|new
name|DBConfiguration
argument_list|(
name|job
argument_list|)
decl_stmt|;
name|String
name|actual
init|=
name|format
operator|.
name|constructQuery
argument_list|(
name|dbConf
operator|.
name|getOutputTableName
argument_list|()
argument_list|,
name|dbConf
operator|.
name|getOutputFieldNames
argument_list|()
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
name|job
operator|=
operator|new
name|JobConf
argument_list|()
expr_stmt|;
name|dbConf
operator|=
operator|new
name|DBConfiguration
argument_list|(
name|job
argument_list|)
expr_stmt|;
name|DBOutputFormat
operator|.
name|setOutput
argument_list|(
name|job
argument_list|,
literal|"hadoop_output"
argument_list|,
name|nullFieldNames
operator|.
name|length
argument_list|)
expr_stmt|;
name|assertNull
argument_list|(
name|dbConf
operator|.
name|getOutputFieldNames
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|nullFieldNames
operator|.
name|length
argument_list|,
name|dbConf
operator|.
name|getOutputFieldCount
argument_list|()
argument_list|)
expr_stmt|;
name|actual
operator|=
name|format
operator|.
name|constructQuery
argument_list|(
name|dbConf
operator|.
name|getOutputTableName
argument_list|()
argument_list|,
operator|new
name|String
index|[
name|dbConf
operator|.
name|getOutputFieldCount
argument_list|()
index|]
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|nullExpected
argument_list|,
name|actual
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
| 16.10084
| 814
| 0.802714
|
132b2260287d911b5c98cee6e7acfedcd1fec6ec
| 500
|
package com.imef.uiwidget.activity.transition;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Window;
import com.imef.uiwidget.activity.BaseActivity;
/**
* Created by yqzheng on 2017/4/27.
*/
public class Explode1Activity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
}
}
| 23.809524
| 71
| 0.764
|
609a1471ff7510990e5cb60d2d7d6c118feb2ef7
| 4,048
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.support;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Pointcut and method matcher for use in simple <b>cflow</b>-style pointcut.
* Note that evaluating such pointcuts is 10-15 times slower than evaluating
* normal pointcuts, but they are useful in some cases.
*
* @author Rod Johnson
* @author Rob Harrop
* @author Juergen Hoeller
* @author Sam Brannen
* 控制流切入点
*/
@SuppressWarnings("serial")
public class ControlFlowPointcut implements Pointcut, ClassFilter, MethodMatcher, Serializable {
private final Class<?> clazz;
@Nullable
private final String methodName;
private final AtomicInteger evaluations = new AtomicInteger(0);
/**
* Construct a new pointcut that matches all control flows below that class.
* @param clazz the clazz
*/
public ControlFlowPointcut(Class<?> clazz) {
this(clazz, null);
}
/**
* Construct a new pointcut that matches all calls below the given method
* in the given class. If no method name is given, matches all control flows
* below the given class.
* @param clazz the clazz
* @param methodName the name of the method (may be {@code null})
*/
public ControlFlowPointcut(Class<?> clazz, @Nullable String methodName) {
Assert.notNull(clazz, "Class must not be null");
this.clazz = clazz;
this.methodName = methodName;
}
/**
* Subclasses can override this for greater filtering (and performance).
*/
@Override
public boolean matches(Class<?> clazz) {
return true;
}
/**
* Subclasses can override this if it's possible to filter out some candidate classes.
*/
@Override
public boolean matches(Method method, Class<?> targetClass) {
return true;
}
@Override
public boolean isRuntime() {
return true;
}
@Override
public boolean matches(Method method, Class<?> targetClass, Object... args) {
this.evaluations.incrementAndGet();
for (StackTraceElement element : new Throwable().getStackTrace()) {
if (element.getClassName().equals(this.clazz.getName()) &&
(this.methodName == null || element.getMethodName().equals(this.methodName))) {
return true;
}
}
return false;
}
/**
* It's useful to know how many times we've fired, for optimization.
*/
public int getEvaluations() {
return this.evaluations.get();
}
@Override
public ClassFilter getClassFilter() {
return this;
}
@Override
public MethodMatcher getMethodMatcher() {
return this;
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ControlFlowPointcut)) {
return false;
}
ControlFlowPointcut that = (ControlFlowPointcut) other;
return (this.clazz.equals(that.clazz)) && ObjectUtils.nullSafeEquals(this.methodName, that.methodName);
}
@Override
public int hashCode() {
int code = this.clazz.hashCode();
if (this.methodName != null) {
code = 37 * code + this.methodName.hashCode();
}
return code;
}
@Override
public String toString() {
return getClass().getName() + ": class = " + this.clazz.getName() + "; methodName = " + methodName;
}
}
| 26.285714
| 105
| 0.72085
|
0a827bbce0bac6ac5c5de73d8fcc88cd8ff2b56b
| 4,017
|
/*
* PreEquipped.java
* Copyright 2001 (C) Bryan McRoberts <merton_monk@yahoo.com>
* Copyright 2003 (C) Chris Ward <frugal@purplewombat.co.uk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Created on November 28, 2003
*
* Current Ver: $Revision$
* Last Editor: $Author$
* Last Edited: $Date$
*
*/
package pcgen.core.prereq;
import pcgen.cdom.base.Constants;
import pcgen.cdom.enumeration.EquipmentLocation;
import pcgen.core.Equipment;
import pcgen.core.PlayerCharacter;
import pcgen.core.character.WieldCategory;
import pcgen.system.LanguageBundle;
/**
* @author wardc
*/
public abstract class PreEquippedTester extends AbstractPrerequisiteTest {
/**
* Process the tokens and return the number that is not passed.
*
* @param prereq
* @param character The pc to use.
* @param equippedType The equipped type to look for (e.g. Equipment.EQUIPPED_TWO_HANDS)
*
* @return the number that did not pass
* @throws PrerequisiteException
*/
public int passesPreEquipHandleTokens(final Prerequisite prereq, final PlayerCharacter character, final EquipmentLocation equippedType) throws PrerequisiteException
{
// TODO refactor this code with PreEquipTester
boolean isEquipped = false;
if (character.hasEquipment())
{
String aString = prereq.getKey();
for ( Equipment eq : character.getDisplay().getEquippedEquipmentSet() )
{
//
// Only check equipment of the type we are interested in
//
if (eq.getLocation() != equippedType)
{
continue;
}
if (aString.startsWith("WIELDCATEGORY=") || aString.startsWith("WIELDCATEGORY."))
{
final WieldCategory wCat = eq.getEffectiveWieldCategory(character);
if ((wCat != null) && wCat.getKeyName().equalsIgnoreCase(aString.substring(14)))
{
isEquipped = true;
break;
}
}
else if (aString.startsWith("TYPE=") || aString.startsWith("TYPE.")) //$NON-NLS-1$ //$NON-NLS-2$
{
isEquipped = eq.isType(aString);
break;
}
else //not a TYPE string
{
String eqName;
if (aString.startsWith("BASEITEM=")) //$NON-NLS-1$ //$NON-NLS-2$
{
eqName = eq.getBaseItemName();
aString = aString.substring(aString.indexOf(Constants.EQUALS) + 1);
}
else
{
eqName = eq.getName();
}
if (aString.indexOf('%') >= 0)
{
//handle wildcards (always assume they
// end the line)
final int percentPos = aString.indexOf('%');
if (eqName.regionMatches(true, 0, aString, 0, percentPos))
{
isEquipped = true;
break;
}
}
else if (eqName.equalsIgnoreCase(aString))
{
//just a straight String compare
isEquipped = true;
break;
}
}
}
}
final PrerequisiteOperator operator = prereq.getOperator();
int runningTotal;
if (operator.equals(PrerequisiteOperator.EQ) || operator.equals(PrerequisiteOperator.GTEQ))
{
runningTotal = isEquipped ? 1 : 0;
}
else if (operator.equals(PrerequisiteOperator.NEQ) || operator.equals(PrerequisiteOperator.LT))
{
runningTotal = isEquipped ? 0 : 1;
}
else
{
throw new PrerequisiteException(LanguageBundle.getFormattedString(
"PreEquipped.error.invalid_comparison", prereq.toString())); //$NON-NLS-1$
}
return countedTotal(prereq, runningTotal);
}
}
| 29.108696
| 165
| 0.68235
|
6b8478151d4dc157c2f24a6220504243194446f9
| 11,188
|
/**
* Copyright 2018-2028 Akaxin Group
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.akaxin.site.storage.sqlite;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.akaxin.common.utils.TimeFormats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.akaxin.common.logs.LogUtils;
import com.akaxin.site.storage.bean.GroupMessageBean;
import com.akaxin.site.storage.sqlite.manager.SQLiteJDBCManager;
import com.akaxin.site.storage.sqlite.sql.SQLConst;
/**
* 群消息数据库相关操作
*
* @author Sam{@link an.guoyue254@gmail.com}
* @since 2018-01-25 16:15:32
*/
public class SQLiteGroupMessageDao {
private static final Logger logger = LoggerFactory.getLogger(SQLiteGroupMessageDao.class);
private final String GROUP_MESSAGE_TABLE = SQLConst.SITE_GROUP_MESSAGE;
private final String GROUP_POINTER_TABLE = SQLConst.SITE_GROUP_MESSAGE_POINTER;
private static SQLiteGroupMessageDao instance = new SQLiteGroupMessageDao();
public static SQLiteGroupMessageDao getInstance() {
return instance;
}
public boolean saveGroupMessage(GroupMessageBean bean) throws SQLException {
long startTime = System.currentTimeMillis();
String sql = "INSERT INTO " + GROUP_MESSAGE_TABLE
+ "(site_group_id,msg_id,send_user_id,send_device_id,msg_type,content,msg_time) VALUES(?,?,?,?,?,?,?);";
PreparedStatement preStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
preStatement.setString(1, bean.getSiteGroupId());
preStatement.setString(2, bean.getMsgId());
preStatement.setString(3, bean.getSendUserId());
preStatement.setString(4, bean.getSendDeviceId());
preStatement.setLong(5, bean.getMsgType());
preStatement.setString(6, bean.getContent());
preStatement.setLong(7, bean.getMsgTime());
int insertResult = preStatement.executeUpdate();
LogUtils.dbDebugLog(logger, startTime, insertResult, sql, bean.getSiteGroupId(), bean.getMsgId(),
bean.getSendUserId(), bean.getSendDeviceId(), bean.getMsgType(), bean.getContent(), bean.getMsgTime());
return insertResult == 1;
}
/**
* 查询的结果,排除发送者的deviceId
*
* @param groupId
* @param userId
* @param deviceId
* @param start
* @return
* @throws SQLException
*/
public List<GroupMessageBean> queryGroupMessage(String groupId, String userId, String deviceId, long start,
int limit) throws SQLException {
long startTime = System.currentTimeMillis();
List<GroupMessageBean> gmsgList = new ArrayList<GroupMessageBean>();
String sql = "SELECT a.id,a.site_group_id,a.msg_id,a.send_user_id,a.send_device_id,a.msg_type,a.content,a.msg_time FROM "
+ GROUP_MESSAGE_TABLE
+ " AS a LEFT JOIN site_group_profile AS b WHERE a.site_group_id=b.site_group_id AND a.site_group_id=? AND a.id>? AND b.group_status=1 AND a.send_device_id IS NOT ? LIMIT ?;";
start = queryGroupPointer(groupId, userId, deviceId, start);
if (start == 0) {
start = queryMaxGroupPointerWithUser(groupId, userId);
}
PreparedStatement statement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
statement.setString(1, groupId);
statement.setLong(2, start);
statement.setString(3, deviceId);
statement.setInt(4, limit);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
GroupMessageBean gmsgBean = new GroupMessageBean();
gmsgBean.setId(rs.getInt(1));
gmsgBean.setSiteGroupId(rs.getString(2));
gmsgBean.setMsgId(rs.getString(3));
gmsgBean.setSendUserId(rs.getString(4));
gmsgBean.setSendDeviceId(rs.getString(5));
gmsgBean.setMsgType(rs.getInt(6));
gmsgBean.setContent(rs.getString(7));
gmsgBean.setMsgTime(rs.getLong(8));
gmsgList.add(gmsgBean);
}
LogUtils.dbDebugLog(logger, startTime, gmsgList.size(), sql, groupId, start, deviceId, limit);
return gmsgList;
}
public boolean updateGroupMessagePointer(String groupId, String siteUserId, String deviceId, long finishPointer)
throws SQLException {
int result = updateGroupPointer(groupId, siteUserId, deviceId, finishPointer);
if (result >= 1) {
return true;
}
return saveGroupPointer(groupId, siteUserId, deviceId, finishPointer);
}
public boolean saveGroupPointer(String groupId, String userId, String deviceId, long finish) throws SQLException {
long startTime = System.currentTimeMillis();
int result = 0;
String sql = "INSERT INTO " + GROUP_POINTER_TABLE
+ "(site_group_id,site_user_id,device_id,pointer) VALUES(?,?,?,?);";
PreparedStatement pStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
pStatement.setString(1, groupId);
pStatement.setString(2, userId);
pStatement.setString(3, deviceId);
pStatement.setLong(4, finish);
result = pStatement.executeUpdate();
LogUtils.dbDebugLog(logger, startTime, result, sql, groupId, userId, deviceId, finish);
return result == 1;
}
private int updateGroupPointer(String groupId, String userId, String deviceId, long finish) throws SQLException {
long startTime = System.currentTimeMillis();
int result = 0;
String sql = "UPDATE " + GROUP_POINTER_TABLE
+ " SET pointer=? WHERE site_user_id=? AND site_group_id=? AND device_id=?;";
PreparedStatement pStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
pStatement.setLong(1, finish);
pStatement.setString(2, userId);
pStatement.setString(3, groupId);
pStatement.setString(4, deviceId);
result = pStatement.executeUpdate();
LogUtils.dbDebugLog(logger, startTime, result, sql, finish, userId, groupId, deviceId);
return result;
}
public long queryGroupPointer(String groupId, String userId, String deviceId, long start) {
long startTime = System.currentTimeMillis();
long pointer = 0;
String sql = "SELECT pointer FROM " + GROUP_POINTER_TABLE
+ " WHERE site_user_id=? AND site_group_id=? AND device_id=?;";
try {
PreparedStatement pStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
pStatement.setString(1, userId);
pStatement.setString(2, groupId);
pStatement.setString(3, deviceId);
ResultSet prs = pStatement.executeQuery();
if (prs.next()) {
pointer = prs.getLong(1);
}
} catch (SQLException e) {
logger.error("query group message pointer error.", e);
}
LogUtils.dbDebugLog(logger, startTime, "pointer:" + pointer + ",start:" + start, sql, userId, groupId,
deviceId);
return pointer > start ? pointer : start;
}
private long queryMaxGroupPointerWithUser(String groupId, String siteUserId) {
long startTime = System.currentTimeMillis();
long pointer = 0;
String sql = "SELECT max(pointer) FROM " + GROUP_POINTER_TABLE + " WHERE site_user_id=? AND site_group_id=?;";
try {
PreparedStatement pStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
pStatement.setString(1, siteUserId);
pStatement.setString(2, groupId);
ResultSet prs = pStatement.executeQuery();
if (prs.next()) {
pointer = prs.getLong(1);
}
} catch (SQLException e) {
logger.error("query group message pointer error.", e);
}
LogUtils.dbDebugLog(logger, startTime, pointer, sql, siteUserId, groupId);
return pointer;
}
public long queryMaxGroupPointer(String groupId) {
long startTime = System.currentTimeMillis();
long pointer = 0;
String sql = "SELECT MAX(id) FROM " + GROUP_MESSAGE_TABLE + " WHERE site_group_id=?;";
try {
PreparedStatement pStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
pStatement.setString(1, groupId);
ResultSet prs = pStatement.executeQuery();
if (prs.next()) {
pointer = prs.getLong(1);
}
} catch (SQLException e) {
logger.error("query max group message pointer error.", e);
}
LogUtils.dbDebugLog(logger, startTime, pointer, sql, groupId);
return pointer;
}
public long queryMaxUserGroupPointer(String groupId, String siteUserId) {
long startTime = System.currentTimeMillis();
long pointer = 0;
String sql = "SELECT MAX(pointer) FROM " + GROUP_POINTER_TABLE + " WHERE site_user_id=? AND site_group_id=?;";
try {
PreparedStatement pStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
pStatement.setString(1, groupId);
ResultSet prs = pStatement.executeQuery();
if (prs.next()) {
pointer = prs.getLong(1);
}
} catch (SQLException e) {
logger.error("query max user group message pointer error.", e);
}
LogUtils.dbDebugLog(logger, startTime, pointer, sql, groupId);
return pointer;
}
public int queryNumMessagePerDay(long now, int day) throws SQLException {
long startTime = System.currentTimeMillis();
String sql = "SELECT COUNT(*) FROM " + GROUP_MESSAGE_TABLE + " WHERE msg_time BETWEEN ? and ? ";
long startTimeOfDay = TimeFormats.getStartTimeOfDay(now);
long endTimeOfDay = TimeFormats.getEndTimeOfDay(now);
if (day != 0) {
startTimeOfDay = startTimeOfDay - TimeUnit.DAYS.toMillis(day);
endTimeOfDay = endTimeOfDay - TimeUnit.DAYS.toMillis(day);
}
PreparedStatement preparedStatement = SQLiteJDBCManager.getConnection().prepareStatement(sql);
preparedStatement.setLong(1, startTimeOfDay);
preparedStatement.setLong(2, endTimeOfDay);
ResultSet resultSet = preparedStatement.executeQuery();
int groupCount = resultSet.getInt(1);
LogUtils.dbDebugLog((logger), startTime, groupCount, sql);
return groupCount;
}
}
| 41.591078
| 191
| 0.65749
|
d0431212d80a3dc86c0b68df43d32387cbc3c5f4
| 3,310
|
package com.huaweicloud.sdk.sdrs.v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huaweicloud.sdk.core.SdkResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/** Response Object */
public class ListProtectionGroupsResponse extends SdkResponse {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "server_groups")
private List<ShowProtectionGroupParams> serverGroups = null;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "count")
private Integer count;
public ListProtectionGroupsResponse withServerGroups(List<ShowProtectionGroupParams> serverGroups) {
this.serverGroups = serverGroups;
return this;
}
public ListProtectionGroupsResponse addServerGroupsItem(ShowProtectionGroupParams serverGroupsItem) {
if (this.serverGroups == null) {
this.serverGroups = new ArrayList<>();
}
this.serverGroups.add(serverGroupsItem);
return this;
}
public ListProtectionGroupsResponse withServerGroups(Consumer<List<ShowProtectionGroupParams>> serverGroupsSetter) {
if (this.serverGroups == null) {
this.serverGroups = new ArrayList<>();
}
serverGroupsSetter.accept(this.serverGroups);
return this;
}
/** 保护组的信息列表。
*
* @return serverGroups */
public List<ShowProtectionGroupParams> getServerGroups() {
return serverGroups;
}
public void setServerGroups(List<ShowProtectionGroupParams> serverGroups) {
this.serverGroups = serverGroups;
}
public ListProtectionGroupsResponse withCount(Integer count) {
this.count = count;
return this;
}
/** 此参数为满足过滤条件的列表中包含的保护组个数。
*
* @return count */
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListProtectionGroupsResponse listProtectionGroupsResponse = (ListProtectionGroupsResponse) o;
return Objects.equals(this.serverGroups, listProtectionGroupsResponse.serverGroups)
&& Objects.equals(this.count, listProtectionGroupsResponse.count);
}
@Override
public int hashCode() {
return Objects.hash(serverGroups, count);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ListProtectionGroupsResponse {\n");
sb.append(" serverGroups: ").append(toIndentedString(serverGroups)).append("\n");
sb.append(" count: ").append(toIndentedString(count)).append("\n");
sb.append("}");
return sb.toString();
}
/** Convert the given object to string with each line indented by 4 spaces (except the first line). */
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 30.090909
| 120
| 0.660725
|
46975af81253c16863ca6db6aa0e79a2779e5eea
| 1,754
|
package com.zwy.kutils.utils;
import java.util.Calendar;
/**
* ================================================================
* 创建时间:2017/7/27 下午2:07
* 创建人:Alan
* 文件描述:时期格式
* 至尊宝:长夜漫漫无心睡眠,我以为只有我睡不着,原来晶晶姑娘你也睡不着 !
* ================================================================
*/
public class DateFormat {
/**
* 英文简写如:2010
*/
public static String FORMAT_Y = "yyyy";
/**
* 英文简写如:12:01
*/
public static String FORMAT_HM = "HH:mm";
/**
* 英文简写如:1-12 12:01
*/
public static String FORMAT_MDHM = "MM-dd HH:mm";
/**
* 英文简写(默认)如:2010-12-01
*/
public static String FORMAT_YMD = "yyyy-MM-dd";
/**
* 英文全称 如:2010-12-01 23:15
*/
public static String FORMAT_YMDHM = "yyyy-MM-dd HH:mm";
/**
* 英文全称 如:2010-12-01 23:15:06
*/
public static String FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
/**
* 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S
*/
public static String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.S";
/**
* 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S
*/
public static String FORMAT_FULL_SN = "yyyyMMddHHmmssS";
/**
* 中文简写 如:2010年12月01日
*/
public static String FORMAT_YMD_CN = "yyyy年MM月dd日";
/**
* 中文简写 如:2010年12月01日 12时
*/
public static String FORMAT_YMDH_CN = "yyyy年MM月dd日 HH时";
/**
* 中文简写 如:2010年12月01日 12时12分
*/
public static String FORMAT_YMDHM_CN = "yyyy年MM月dd日 HH时mm分";
/**
* 中文全称 如:2010年12月01日 23时15分06秒
*/
public static String FORMAT_YMDHMS_CN = "yyyy年MM月dd日 HH时mm分ss秒";
/**
* 精确到毫秒的完整中文时间
*/
public static String FORMAT_FULL_CN = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒";
public static Calendar calendar = null;
}
| 21.654321
| 72
| 0.541049
|
3b8cedaa84749b9cf24830cb5e2eb999f644da12
| 913
|
package main;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Window{
public static final int WIDTH = 445, HEIGHT = 629;
private Board board;
private Title title;
private JFrame window;
public Window(){
window = new JFrame("Tetris");
window.setSize(WIDTH, HEIGHT);
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setResizable(false);
board = new Board();
title = new Title(this);
window.addKeyListener(board);
window.addMouseMotionListener(title);
window.addMouseListener(title);
window.add(title);
window.setVisible(true);
}
public void startTetris(){
window.remove(title);
window.addMouseMotionListener(board);
window.addMouseListener(board);
window.add(board);
board.startGame();
window.revalidate();
}
public static void main(String[] args) {
new Window();
}
}
| 18.632653
| 59
| 0.715225
|
50196ab8e7e72d3574cb5e5f9a16da9615020105
| 2,360
|
package com.google.android.apps.common.testing.ui.espresso;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import android.test.AndroidTestCase;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.StringDescription;
/** Unit tests for {@link AmbiguousViewMatcherException}. */
public class AmbiguousViewMatcherExceptionTest extends AndroidTestCase {
private Matcher<View> alwaysTrueMatcher;
private RelativeLayout testView;
private View child1;
private View child2;
private View child3;
private View child4;
@Override
public void setUp() throws Exception {
super.setUp();
alwaysTrueMatcher = Matchers.<View>notNullValue();
testView = new RelativeLayout(getContext());
child1 = new TextView(getContext());
child1.setId(1);
child2 = new TextView(getContext());
child2.setId(2);
child3 = new TextView(getContext());
child3.setId(3);
child4 = new TextView(getContext());
child4.setId(4);
testView.addView(child1);
testView.addView(child2);
testView.addView(child3);
testView.addView(child4);
}
public void testExceptionContainsMatcherDescription() {
StringBuilder matcherDescription = new StringBuilder();
alwaysTrueMatcher.describeTo(new StringDescription(matcherDescription));
assertThat(createException().getMessage(), containsString(matcherDescription.toString()));
}
@SuppressWarnings("unchecked")
public void testExceptionContainsView() {
String exceptionMessage = createException().getMessage();
assertThat("missing elements", exceptionMessage,
allOf(
containsString("{id=1,"), // child1
containsString("{id=2,"), // child2
containsString("{id=3,"), // child3
containsString("{id=4,"), // child4
containsString("{id=-1,"))); // root
}
private AmbiguousViewMatcherException createException() {
return new AmbiguousViewMatcherException.Builder()
.withViewMatcher(alwaysTrueMatcher)
.withRootView(testView)
.withView1(testView)
.withView2(child1)
.withOtherAmbiguousViews(child2, child3, child4)
.build();
}
}
| 31.466667
| 94
| 0.723729
|
bafec0ddaf6dc262072691ae2f3c4b7cf7fa0127
| 5,638
|
package com.ece.cov19.Functions;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import com.ece.cov19.DataModels.UserDataModel;
import com.ece.cov19.LoginActivity;
import com.ece.cov19.R;
import com.ece.cov19.RetroServices.RetroInstance;
import com.ece.cov19.RetroServices.RetroInterface;
import com.ece.cov19.SplashActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.Context.MODE_PRIVATE;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserAge;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserBloodGroup;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserDistrict;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserDivision;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserDonorInfo;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserGender;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserName;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserPass;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserPhone;
import static com.ece.cov19.DataModels.LoggedInUserData.loggedInUserThana;
import static com.ece.cov19.LoginActivity.LOGIN_SHARED_PREFS;
import static com.ece.cov19.LoginActivity.LOGIN_USER_PASS;
import static com.ece.cov19.LoginActivity.LOGIN_USER_PHONE;
import static com.ece.cov19.SplashActivity.progressBar;
import static com.ece.cov19.SplashActivity.tryAgain;
public class LoginUser {
public static String checkLoginStat(){
if(loggedInUserPhone.equals("Didn't Load") || loggedInUserName.equals("Didn't Load") || loggedInUserAge.equals("Didn't Load")
|| loggedInUserBloodGroup.equals("Didn't Load") || loggedInUserDistrict.equals("Didn't Load") || loggedInUserDivision.equals("Didn't Load")
|| loggedInUserGender.equals("Didn't Load") || loggedInUserDonorInfo.equals("Didn't Load")||loggedInUserThana.equals("Didn't Load")
){
return "failed";
}
return "success";
}
public static void loginUser(Context ctx, String phone, String password,Class<?> toActivity){
RetroInterface retroInterface = RetroInstance.getRetro();
Call<UserDataModel> sendingData = retroInterface.loginRetroMethod(phone, password);
sendingData.enqueue(new Callback<UserDataModel>() {
@Override
public void onResponse(Call<UserDataModel> call, Response<UserDataModel> response) {
if (response.body().getServerMsg().toLowerCase().equals("success")) {
ToastCreator.toastCreatorGreen(ctx, ctx.getResources().getString(R.string.welcome)+" " + response.body().getName());
// Storing phone and password to shared preferences
SharedPreferences loginSharedPrefs = ctx.getSharedPreferences(LOGIN_SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor loginPrefsEditor = loginSharedPrefs.edit();
loginPrefsEditor.putString(LOGIN_USER_PHONE, response.body().getPhone());
loginPrefsEditor.putString(LOGIN_USER_PASS, response.body().getPassword());
loginPrefsEditor.apply();
// setting all logged in info
loggedInUserName = response.body().getName();
loggedInUserPhone = response.body().getPhone();
loggedInUserGender = response.body().getGender();
loggedInUserBloodGroup = response.body().getBloodGroup();
loggedInUserDivision = response.body().getDivision();
loggedInUserDistrict = response.body().getDistrict();
loggedInUserThana = response.body().getThana();
loggedInUserAge = response.body().getAge();
loggedInUserDonorInfo = response.body().getDonor();
loggedInUserPass = response.body().getPassword();
// going to Dashboard
if(ctx.getClass()!=toActivity) {
Intent intent = new Intent(ctx, toActivity);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ctx.startActivity(intent);
}
}
else if(response.body().getServerMsg().toLowerCase().equals("wrong phone or password")){
if(ctx.getClass()== SplashActivity.class){
Intent intent=new Intent(ctx,LoginActivity.class);
ctx.startActivity(intent);
((SplashActivity) ctx).finishAffinity();
}
else {
ToastCreator.toastCreatorRed(ctx, ctx.getResources().getString(R.string.login_activity_wrong));
}
}
else {
ToastCreator.toastCreatorRed(ctx,ctx.getResources().getString(R.string.connection_error));
progressBar.setVisibility(View.GONE);
tryAgain.setVisibility(View.VISIBLE);
}
}
@Override
public void onFailure(Call<UserDataModel> call, Throwable t) {
ToastCreator.toastCreatorRed(ctx,ctx.getResources().getString(R.string.connection_error));
progressBar.setVisibility(View.GONE);
tryAgain.setVisibility(View.VISIBLE);
}
});
}
}
| 45.837398
| 155
| 0.659631
|
43a5bc261b2c54a4759560e13a5cf7b061374a1e
| 3,773
|
/**
* Copyright 2016 Antony Holmes
*
* 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 edu.columbia.rdf.matcalc.figure;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Box;
import org.jebtk.core.event.ChangeEvent;
import org.jebtk.core.event.ChangeListener;
import org.jebtk.graphplot.figure.Axis;
import org.jebtk.modern.ModernWidget;
import org.jebtk.modern.panel.HBox;
import org.jebtk.modern.panel.ModernPanel;
import org.jebtk.modern.panel.VBox;
import org.jebtk.modern.text.ModernAutoSizeLabel;
import org.jebtk.modern.text.ModernClipboardTextField;
import org.jebtk.modern.text.ModernTextBorderPanel;
import org.jebtk.modern.text.ModernTextField;
import org.jebtk.modern.window.ModernWindow;
/**
* The class LimitsPlotControl.
*/
public class LimitsPlotControl extends VBox {
/**
* The constant serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* The min text field.
*/
private ModernTextField mMinTextField = new ModernClipboardTextField();
/**
* The max text field.
*/
private ModernTextField mMaxTextField = new ModernClipboardTextField();
/**
* The member axis.
*/
private Axis mAxis;
/**
* The class KeyEvents.
*/
private class KeyEvents implements KeyListener {
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
*/
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER) {
return;
}
mAxis.setLimits(Double.parseDouble(mMinTextField.getText()), Double.parseDouble(mMaxTextField.getText()));
}
/*
* (non-Javadoc)
*
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
*/
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
/**
* Instantiates a new limits plot control.
*
* @param parent the parent
* @param axis the axis
*/
public LimitsPlotControl(ModernWindow parent, Axis axis) {
mAxis = axis;
Box box = HBox.create();
ModernAutoSizeLabel label = new ModernAutoSizeLabel("Limits");
// Ui.setSize(label, ModernWidget.STANDARD_SIZE);
box.add(label);
box.add(Box.createHorizontalGlue());
box.add(new ModernTextBorderPanel(mMinTextField, ModernWidget.SMALL_SIZE));
box.add(ModernPanel.createHGap());
box.add(new ModernTextBorderPanel(mMaxTextField, ModernWidget.SMALL_SIZE));
add(box);
add(ModernPanel.createVGap());
mMinTextField.addKeyListener(new KeyEvents());
mMaxTextField.addKeyListener(new KeyEvents());
mAxis.addChangeListener(new ChangeListener() {
@Override
public void changed(ChangeEvent e) {
update();
}
});
update();
}
/**
* Update.
*/
private void update() {
mMinTextField.setText(Double.toString(mAxis.getLimits().getMin()));
mMaxTextField.setText(Double.toString(mAxis.getLimits().getMax()));
}
}
| 25.322148
| 112
| 0.692552
|
7a65728c532247de5484b83c1652822db6bcaa33
| 10,379
|
/* ###
* IP: GHIDRA
*
* 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.
*/
// Companion script to MSLibBatchImportGenerator.
//
// This script polls a directory on the file system for files queued there by the generator
// and imports the single file specified in each queue control file that it processes.
// Multiple instances of this script can run against the same work queue
// directory.
//
// This script will exit when its input queue is empty for several seconds.
//
// Queue internals:
//
// __queuebasedir/
// ____new/
// ____work/
// ____done/
//
// This scripts polls the "new" directory, grabs a single file and tries to move it
// (using filesystem level atomic move/rename) to the "work" directory. If that succeeds,
// the information in the queue file is used to perform an import operation.
// When the import operation is finished, the queue file is moved from the "work" directory
// to the "done" directory.
//
// To rerun the import process, simply move all the files from the "done" directory back
// to the "new" directory after resetting your project.
//
// If a script instance dies while importing a file, the troublesome binary's queue
// control file will be left in the "work" directory. The user can move it back to
// the "new" directory (it will probably need renaming to remove some script metadata
// from the filename) to re-submit the binary for processing.
//
// Example usage with analyzeHeadless:
//
// ./analyzeHeadless "ghidra://localhost/myproject" -preScript MSLibBatchImportWorker.java
//
//@category FunctionID
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.function.Predicate;
import org.apache.commons.io.FileUtils;
import generic.stl.Pair;
import ghidra.app.script.GhidraScript;
import ghidra.app.util.bin.*;
import ghidra.app.util.bin.format.coff.*;
import ghidra.app.util.bin.format.coff.archive.CoffArchiveHeader;
import ghidra.app.util.bin.format.coff.archive.CoffArchiveMemberHeader;
import ghidra.app.util.importer.*;
import ghidra.app.util.opinion.Loader;
import ghidra.app.util.opinion.MSCoffLoader;
import ghidra.framework.model.DomainFile;
import ghidra.framework.model.DomainFolder;
import ghidra.framework.store.local.LocalFileSystem;
import ghidra.program.model.listing.Program;
import ghidra.util.InvalidNameException;
import ghidra.util.exception.*;
import ghidra.util.task.TaskMonitor;
import utilities.util.FileUtilities;
public class MSLibBatchImportWorker extends GhidraScript {
final static Predicate<Loader> LOADER_FILTER = new SingleLoaderFilter(MSCoffLoader.class);
final static LoadSpecChooser LOADSPEC_CHOOSER = new CsHintLoadSpecChooser("windows");
private static String getProcessId(String fallback) {
// something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
int index = jvmName.indexOf('@');
if (index > 0) {
try {
return Long.toString(Long.parseLong(jvmName.substring(0, index)));
}
catch (NumberFormatException e) {
// ignore
}
}
return fallback;
}
String pid = getProcessId("fakepid_" + System.currentTimeMillis());
String initalCheckInComment = "Initial import";
@Override
protected void run() throws Exception {
// If running this via 'HeadlessAnalyzer', a MSLibBatchImportWorker.properties
// file needs to be created with a single line specifying the queue directory:
// "Choose queue directory Choose=/path/to/queue/dir"
// (without any quotes)
// Which corresponds to the askDirectory() prompt in the next line:
File directory = askDirectory("Choose queue directory", "Choose");
// or the value could be hard-coded:
// File directory = new File("/path/to/queue/dir");
File newDir = new File(directory, "new");
File workDir = new File(directory, "work");
File doneDir = new File(directory, "done");
newDir.mkdir();
workDir.mkdir();
doneDir.mkdir();
int totalFilesProcessed = 0;
long lastWorkTS = System.currentTimeMillis();
int maxIdleMS = 10 * 1000;
while ((System.currentTimeMillis() - lastWorkTS) < maxIdleMS) {
if (monitor.isCancelled()) {
break;
}
int filesProcessed = 0;
Iterator<File> files = FileUtils.iterateFiles(newDir, null, false);
while (files.hasNext()) {
File newFile = files.next();
File workFile = new File(workDir, ".work_" + pid + "_" + newFile.getName());
if (!newFile.renameTo(workFile)) {
continue;
}
workFile.setLastModified(System.currentTimeMillis());
List<String> lines = FileUtilities.getLines(workFile);
if (lines.size() != 2) {
println("Found bad file: " + workFile);
continue;
}
String importFilePath = lines.get(0);
String destFolderPath = lines.get(1);
File importFile = new File(importFilePath);
if (!importFile.exists()) {
println("Can not find import file: " + importFile);
continue;
}
DomainFolder destFolder = getFolder(
state.getProject().getProjectData().getRootFolder(), destFolderPath, true);
MessageLog log = new MessageLog();
importLibrary(destFolder, importFile, log);
File doneFile = new File(doneDir, newFile.getName());
if (!workFile.renameTo(doneFile)) {
throw new IOException("Failed to move " + workFile + " to " + doneFile);
}
doneFile.setLastModified(System.currentTimeMillis());
filesProcessed++;
totalFilesProcessed++;
}
lastWorkTS = (filesProcessed != 0) ? System.currentTimeMillis() : lastWorkTS;
Thread.sleep(500);
}
println("Exiting import wait loop, total files processed: " + totalFilesProcessed);
}
private void importLibrary(DomainFolder currentLibraryFolder, File file, MessageLog log)
throws CancelledException, DuplicateNameException, InvalidNameException,
VersionException, IOException {
try (RandomAccessByteProvider provider = new RandomAccessByteProvider(file)) {
if (!CoffArchiveHeader.isMatch(provider)) {
return;
}
CoffArchiveHeader coffArchiveHeader =
CoffArchiveHeader.read(provider, TaskMonitor.DUMMY);
HashSet<Long> offsetsSeen = new HashSet<Long>();
for (CoffArchiveMemberHeader archiveMemberHeader : coffArchiveHeader.getArchiveMemberHeaders()) {
if (offsetsSeen.contains(archiveMemberHeader.getPayloadOffset())) {
continue;
}
offsetsSeen.add(archiveMemberHeader.getPayloadOffset());
if (archiveMemberHeader.isCOFF()) {
try (ByteProvider coffProvider = new ByteProviderWrapper(provider,
archiveMemberHeader.getPayloadOffset(), archiveMemberHeader.getSize())) {
CoffFileHeader header = new CoffFileHeader(coffProvider);
if (CoffMachineType.isMachineTypeDefined(header.getMagic())) {
String preferredName = archiveMemberHeader.getName();
Pair<DomainFolder, String> pair =
getFolderAndUniqueFile(currentLibraryFolder, preferredName);
List<Program> programs = AutoImporter.importFresh(coffProvider,
pair.first, this, log, monitor, LOADER_FILTER, LOADSPEC_CHOOSER,
pair.second, OptionChooser.DEFAULT_OPTIONS,
MultipleProgramsStrategy.ONE_PROGRAM_OR_EXCEPTION);
if (programs != null) {
for (Program program : programs) {
println("Imported " + program.getDomainFile().getPathname());
DomainFile progFile = program.getDomainFile();
program.release(this);
if (!progFile.isVersioned()) {
progFile.addToVersionControl(initalCheckInComment, false,
monitor);
}
}
}
}
}
}
}
}
catch (CoffException e) {
//TODO
}
}
private static DomainFolder getFolder(DomainFolder folder, String path,
boolean createIfMissing) throws InvalidNameException, IOException {
for (String pathpart : path.split("[/\\\\]")) {
if (pathpart.isEmpty()) {
continue;
}
pathpart = ensureSafeProjectObjName(pathpart);
DomainFolder tmp = folder.getFolder(pathpart);
if (tmp == null) {
if (!createIfMissing) {
return null;
}
tmp = folder.createFolder(pathpart);
}
folder = tmp;
}
return folder;
}
private static Pair<DomainFolder, String> getFolderAndUniqueFile(DomainFolder current,
String preferredName) throws InvalidNameException, IOException {
int pathSepIndex;
for(pathSepIndex = preferredName.length() - 1; pathSepIndex >= 0; pathSepIndex--) {
if ( "/\\".indexOf(preferredName.charAt(pathSepIndex)) != -1 ) {
break;
}
}
String folderStr = (pathSepIndex >= 0) ? preferredName.substring(0, pathSepIndex) : "";
String fileStr = ensureSafeProjectObjName(preferredName.substring(pathSepIndex + 1));
DomainFolder folder = getFolder(current, folderStr, true);
return new Pair<DomainFolder, String>(folder, getUniqueDomainFileName(folder, fileStr));
}
private static String ensureSafeProjectObjName(String name) {
switch (name) {
case ".":
return "dot";
case "..":
return "dotdot";
}
StringBuilder sb = new StringBuilder();
for (char c : name.toCharArray()) {
sb.append(LocalFileSystem.isValidNameCharacter(c) ? c : '_');
}
return sb.toString();
}
private static String getUniqueDomainFileName(DomainFolder folder, String baseName) {
int highestNum = -1;
for (DomainFile domainFile : folder.getFiles()) {
String fname = domainFile.getName();
if (fname.startsWith(baseName)) {
String suffix = fname.substring(baseName.length());
if (suffix.isEmpty()) {
highestNum = Math.max(0, highestNum);
}
else if (suffix.matches("^[1-9][0-9]*")) {
try {
int val = Integer.parseInt(suffix);
highestNum = Math.max(val, highestNum);
}
catch (NumberFormatException nfe) {
// ignore
}
}
}
}
return (highestNum == -1) ? baseName : String.format("%s%d", baseName, highestNum + 1);
}
}
| 33.918301
| 100
| 0.711533
|
8e9b246bc40f2cec0d85368b1f162fb474bdf2dc
| 550
|
package org.fordes.subview.view;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLView;
import javafx.stage.Stage;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
/**
* 主程序
*
* @author fordes on 2020/10/2
*/
@Component
@FXMLView(value = "/fxml/Application.fxml", stageStyle = "TRANSPARENT")
public class ApplicationView extends AbstractFxmlView {
@SneakyThrows
@Override
public void afterInitView(final Stage stage) {
stage.getScene().setFill(null);
}
}
| 23.913043
| 71
| 0.750909
|
4a088c4853a761cbff2c9b0f850fc7b23b5a77a9
| 3,730
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.elastic.index;
import org.apache.jackrabbit.oak.plugins.index.ContextAwareCallback;
import org.apache.jackrabbit.oak.plugins.index.IndexEditorProvider;
import org.apache.jackrabbit.oak.plugins.index.IndexUpdateCallback;
import org.apache.jackrabbit.oak.plugins.index.IndexingContext;
import org.apache.jackrabbit.oak.plugins.index.elastic.ElasticConnection;
import org.apache.jackrabbit.oak.plugins.index.elastic.ElasticIndexDefinition;
import org.apache.jackrabbit.oak.plugins.index.search.ExtractedTextCache;
import org.apache.jackrabbit.oak.spi.commit.Editor;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.apache.jackrabbit.oak.plugins.index.elastic.ElasticIndexDefinition.TYPE_ELASTICSEARCH;
public class ElasticIndexEditorProvider implements IndexEditorProvider {
private final ElasticConnection elasticConnection;
private final ExtractedTextCache extractedTextCache;
public ElasticIndexEditorProvider(@NotNull ElasticConnection elasticConnection,
ExtractedTextCache extractedTextCache) {
this.elasticConnection = elasticConnection;
this.extractedTextCache = extractedTextCache != null ? extractedTextCache : new ExtractedTextCache(0, 0);
}
@Override
public @Nullable Editor getIndexEditor(@NotNull String type,
@NotNull NodeBuilder definition, @NotNull NodeState root,
@NotNull IndexUpdateCallback callback) {
if (TYPE_ELASTICSEARCH.equals(type)) {
if (!(callback instanceof ContextAwareCallback)) {
throw new IllegalStateException("callback instance not of type ContextAwareCallback [" + callback + "]");
}
IndexingContext indexingContext = ((ContextAwareCallback) callback).getIndexingContext();
String indexPath = indexingContext.getIndexPath();
ElasticIndexDefinition indexDefinition =
new ElasticIndexDefinition(root, definition.getNodeState(), indexPath, elasticConnection.getIndexPrefix());
ElasticIndexWriterFactory writerFactory = new ElasticIndexWriterFactory(elasticConnection);
ElasticIndexEditorContext context = new ElasticIndexEditorContext(root,
definition, indexDefinition,
callback,
writerFactory,
extractedTextCache,
indexingContext,
true, elasticConnection.getIndexPrefix());
return new ElasticIndexEditor(context);
}
return null;
}
public ExtractedTextCache getExtractedTextCache() {
return extractedTextCache;
}
}
| 47.820513
| 127
| 0.722788
|
89302c395983721361766f7bd9986dd43accd2e4
| 952
|
/*
* Created on 10/01/2005
*
* @author Rene Wooller
*/
package music;
import jm.music.data.Tempo;
import ren.gui.ParameterMap;
/**
* @author wooller
*
*10/01/2005
*
* Copyright JEDI/Rene Wooller
*
*/
public class TempoPC extends Tempo {
private ParameterMap tempoParam;
/**
*
*/
public TempoPC() {
this(120.0);
}
/**
* @param initTempo
*/
public TempoPC(double initTempo) {
//super(initTempo);
tempoParam = (new ParameterMap()).construct(0, 21000, 40.0, 250.0, initTempo, "tempo");
}
public TempoPC(ParameterMap pc) {
this.tempoParam = pc;
}
protected double getValue() {
return tempoParam.getValue();
}
public void setTempo(double newTempo) {
tempoParam.setValue(newTempo);
}
public ParameterMap getTempoParam() {
return tempoParam;
}
public void setTempoParam(ParameterMap tempoParam) {
this.tempoParam = tempoParam;
}
}
| 16.135593
| 90
| 0.628151
|
92cd9d965b46701e8c62550bf9333da0a30572b3
| 4,706
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ctakes.temporal.ae.feature;
import java.util.List;
import org.apache.ctakes.relationextractor.ae.features.RelationFeaturesExtractor;
import org.apache.ctakes.typesystem.type.textsem.EventMention;
import org.apache.ctakes.typesystem.type.textsem.IdentifiedAnnotation;
import org.apache.ctakes.typesystem.type.textsem.Predicate;
import org.apache.ctakes.typesystem.type.textsem.SemanticArgument;
import org.apache.ctakes.typesystem.type.textsem.SemanticRoleRelation;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.FSList;
import org.apache.uima.jcas.cas.NonEmptyFSList;
import org.cleartk.ml.Feature;
import org.apache.uima.fit.util.JCasUtil;
import com.google.common.collect.Lists;
public class SRLRelationFeaturesExtractor implements RelationFeaturesExtractor<IdentifiedAnnotation,IdentifiedAnnotation> {
/*
* (non-Javadoc)
* @see org.apache.ctakes.relationextractor.ae.features.RelationFeaturesExtractor#extract(org.apache.uima.jcas.JCas, org.apache.ctakes.typesystem.type.textsem.IdentifiedAnnotation, org.apache.ctakes.typesystem.type.textsem.IdentifiedAnnotation)
* This feature extractor uses semantic role labeling features -- is either
* argument a predicate, if so what frame, and if so is the other argument a semantic arg to that predicate.
* Also are features for whether individual args are just any semantic arg to any semantic relation and what arg type.
*/
public List<Feature> extract(JCas jCas, IdentifiedAnnotation arg1,
IdentifiedAnnotation arg2) throws AnalysisEngineProcessException {
List<Feature> feats = Lists.newArrayList();
if(arg1 instanceof EventMention){
List<Predicate> preds = JCasUtil.selectCovered(Predicate.class, arg1);
if(preds.size() > 0){
feats.add(new Feature("Arg1_Pred", true));
feats.add(new Feature("Arg1_Frame", preds.get(0).getFrameSet()));
// check if arg2 is one of its SRL args
FSList relList = preds.get(0).getRelations();
while(relList instanceof NonEmptyFSList){
SemanticRoleRelation rel = (SemanticRoleRelation) ((NonEmptyFSList)relList).getHead();
SemanticArgument arg = rel.getArgument();
if(arg.getBegin() == arg2.getBegin() && arg.getEnd() == arg2.getEnd()){
feats.add(new Feature("Arg1_Pred_Arg2_Role", true));
break;
}
relList = ((NonEmptyFSList)relList).getTail();
}
}
List<SemanticArgument> args = JCasUtil.selectCovered(SemanticArgument.class, arg1);
if(args.size() > 0){
feats.add(new Feature("Arg1_SemArg", true));
feats.add(new Feature("Arg1_SemArgType", args.get(0).getLabel()));
}
}
if(arg2 instanceof EventMention){
List<Predicate> preds = JCasUtil.selectCovered(Predicate.class, arg2);
if(preds.size() > 0){
feats.add(new Feature("Arg2_Pred", true));
feats.add(new Feature("Arg2_Frame", preds.get(0).getFrameSet()));
// check if arg2 is one of its SRL args
FSList relList = preds.get(0).getRelations();
while(relList instanceof NonEmptyFSList){
SemanticRoleRelation rel = (SemanticRoleRelation) ((NonEmptyFSList)relList).getHead();
SemanticArgument arg = rel.getArgument();
if(arg.getBegin() == arg1.getBegin() && arg.getEnd() == arg1.getEnd()){
feats.add(new Feature("Arg2_Pred_Arg1_Role", true));
break;
}
relList = ((NonEmptyFSList)relList).getTail();
}
}
List<SemanticArgument> args = JCasUtil.selectCovered(SemanticArgument.class, arg2);
if(args.size() > 0){
feats.add(new Feature("Arg2_SemArg", true));
feats.add(new Feature("Arg2_SemArgType", args.get(0).getLabel()));
}
}
return feats;
}
}
| 45.68932
| 246
| 0.71037
|
38915adb08af108133a6e7e1d83e897673307bd9
| 3,565
|
package org.zstack.test.storage.ceph;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.storage.backup.BackupStorageInventory;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.simulator.kvm.KVMSimulatorConfig;
import org.zstack.storage.ceph.backup.CephBackupStorageSimulatorConfig;
import org.zstack.storage.ceph.primary.CephPrimaryStorageSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import java.util.List;
/**
* 1. test APIGetCandidateBackupStorageForCreatingImageMsg
*/
public class TestCeph20 {
Deployer deployer;
Api api;
ComponentLoader loader;
CloudBus bus;
DatabaseFacade dbf;
SessionInventory session;
CephPrimaryStorageSimulatorConfig config;
KVMSimulatorConfig kconfig;
CephBackupStorageSimulatorConfig bconfig;
@Before
public void setUp() throws Exception {
DBUtil.reDeployDB();
WebBeanConstructor con = new WebBeanConstructor();
deployer = new Deployer("deployerXml/ceph/TestCeph20.xml", con);
deployer.addSpringConfig("ceph.xml");
deployer.addSpringConfig("cephSimulator.xml");
deployer.addSpringConfig("KVMRelated.xml");
deployer.build();
api = deployer.getApi();
loader = deployer.getComponentLoader();
bus = loader.getComponent(CloudBus.class);
dbf = loader.getComponent(DatabaseFacade.class);
config = loader.getComponent(CephPrimaryStorageSimulatorConfig.class);
kconfig = loader.getComponent(KVMSimulatorConfig.class);
bconfig = loader.getComponent(CephBackupStorageSimulatorConfig.class);
session = api.loginAsAdmin();
}
@Test
public void test() throws ApiSenderException {
VmInstanceInventory vm1 = deployer.vms.get("TestVm1");
VmInstanceInventory vm2 = deployer.vms.get("TestVm2");
BackupStorageInventory sftp = deployer.backupStorages.get("sftp");
BackupStorageInventory ceph = deployer.backupStorages.get("ceph-bk");
VolumeInventory root1 = vm1.getRootVolume();
VolumeInventory root2 = vm2.getRootVolume();
List<BackupStorageInventory> bs1 = api.getCandidateBackupStorageForCreatingImage(root1.getUuid(), null, null);
Assert.assertEquals(1, bs1.size());
Assert.assertEquals(ceph.getUuid(), bs1.get(0).getUuid());
bs1 = api.getCandidateBackupStorageForCreatingImage(root2.getUuid(), null, null);
Assert.assertEquals(1, bs1.size());
Assert.assertEquals(sftp.getUuid(), bs1.get(0).getUuid());
VolumeSnapshotInventory sp = api.createSnapshot(root1.getUuid());
bs1 = api.getCandidateBackupStorageForCreatingImage(null, sp.getUuid(), null);
Assert.assertEquals(1, bs1.size());
Assert.assertEquals(ceph.getUuid(), bs1.get(0).getUuid());
sp = api.createSnapshot(root2.getUuid());
bs1 = api.getCandidateBackupStorageForCreatingImage(null, sp.getUuid(), null);
Assert.assertEquals(1, bs1.size());
Assert.assertEquals(sftp.getUuid(), bs1.get(0).getUuid());
}
}
| 40.977011
| 118
| 0.734081
|
0057d87ac245ee7fc79943647485a4b3d2fb8391
| 433
|
package com.jn.langx.util.reflect;
import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
import java.util.Collection;
public interface MemberAttributes<M extends Member> {
String getName();
<T extends Annotation> T getAnnotation(Class<T> annotation);
Collection<Annotation> getAnnotations();
boolean hasModifier(int modifier);
Class getDeclaringClass();
int getModifier();
M get();
}
| 27.0625
| 64
| 0.743649
|
2455a8b17436d1b4f1093d3e0ea0d337dfe0813e
| 78,462
|
/*
Derby - Class com.pivotal.gemfirexd.internal.client.net.Request
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* Changes for GemFireXD distributed data platform (some marked by "GemStone changes")
*
* Portions Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.client.net;
import com.pivotal.gemfirexd.internal.client.am.DisconnectException;
import com.pivotal.gemfirexd.internal.client.am.EncryptionManager;
import com.pivotal.gemfirexd.internal.client.am.ClientMessageId;
import com.pivotal.gemfirexd.internal.client.am.SqlException;
import com.pivotal.gemfirexd.internal.client.am.Utils;
import com.pivotal.gemfirexd.internal.iapi.reference.DRDAConstants;
import com.pivotal.gemfirexd.internal.shared.common.io.DynamicByteArrayOutputStream;
import com.pivotal.gemfirexd.internal.shared.common.reference.SQLState;
import com.pivotal.gemfirexd.internal.shared.common.sanity.SanityManager;
import java.io.BufferedInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
public class Request {
// byte array buffer used for constructing requests.
// currently requests are built starting at the beginning of the buffer.
protected byte[] bytes_;
// keeps track of the next position to place a byte in the buffer.
// so the last valid byte in the message is at bytes_[offset - 1]
protected int offset_;
// a stack is used to keep track of offsets into the buffer where 2 byte
// ddm length values are located. these length bytes will be automatically updated
// by this object when construction of a particular object has completed.
// right now the max size of the stack is 10. this is an arbitrary number which
// should be sufficiently large enough to handle all situations.
private final static int MAX_MARKS_NESTING = 10;
private int[] markStack_ = new int[MAX_MARKS_NESTING];
private int top_ = 0;
// the ccsid manager for the connection is stored in this object. it will
// be used when constructing character ddm data. it will NOT be used for
// building any FDOCA data.
protected CcsidManager ccsidManager_;
// This Object tracks the location of the current
// Dss header length bytes. This is done so
// the length bytes can be automatically
// updated as information is added to this stream.
protected /* GemStone change: private */ int dssLengthLocation_ = 0;
// tracks the request correlation ID to use for commands and command objects.
// this is automatically updated as commands are built and sent to the server.
private int correlationID_ = 0;
private boolean simpleDssFinalize = false;
// Used to mask out password when trace is on.
protected boolean passwordIncluded_ = false;
protected int passwordStart_ = 0;
protected int passwordLength_ = 0;
protected NetAgent netAgent_;
// GemStone changes BEGIN
protected static final int DSS_CONTINUATION_LEN = DssConstants.MAX_DSS_LEN - 2;
// GemStone changes END
// construct a request object specifying the minimum buffer size
// to be used to buffer up the built requests. also specify the ccsid manager
// instance to be used when building ddm character data.
Request(NetAgent netAgent, int minSize, CcsidManager ccsidManager) {
netAgent_ = netAgent;
bytes_ = new byte[minSize];
ccsidManager_ = ccsidManager;
clearBuffer();
}
// construct a request object specifying the ccsid manager instance
// to be used when building ddm character data. This will also create
// a buffer using the default size (see final static DEFAULT_BUFFER_SIZE value).
Request(NetAgent netAgent, CcsidManager ccsidManager, int bufferSize) {
//this (netAgent, Request.DEFAULT_BUFFER_SIZE, ccsidManager);
this(netAgent, bufferSize, ccsidManager);
}
protected final void clearBuffer() {
offset_ = 0;
top_ = 0;
for (int i = 0; i < markStack_.length; i++) {
if (markStack_[i] != 0) {
markStack_[i] = 0;
} else {
break;
}
}
dssLengthLocation_ = 0;
}
final void initialize() {
clearBuffer();
correlationID_ = 0;
}
// set the ccsid manager value. this method allows the ccsid manager to be
// changed so a request object can be reused by different connections with
// different ccsid managers.
final void setCcsidMgr(CcsidManager ccsidManager) {
ccsidManager_ = ccsidManager;
}
// ensure length at the end of the buffer for a certain amount of data.
// if the buffer does not contain sufficient room for the data, the buffer
// will be expanded by the larger of (2 * current size) or (current size + length).
// the data from the previous buffer is copied into the larger buffer.
protected final void ensureLength(int length) {
if (length > bytes_.length) {
byte newBytes[] = new byte[Math.max(bytes_.length << 1, length)];
System.arraycopy(bytes_, 0, newBytes, 0, offset_);
bytes_ = newBytes;
}
}
// creates an request dss in the buffer to contain a ddm command
// object. calling this method means any previous dss objects in
// the buffer are complete and their length and chaining bytes can
// be updated appropriately.
protected final void createCommand() {
buildDss(false, false, false, DssConstants.GDSFMT_RQSDSS, ++correlationID_, false);
}
// creates an request dss in the buffer to contain a ddm command
// object. calling this method means any previous dss objects in
// the buffer are complete and their length and chaining bytes can
// be updated appropriately.
protected void createXACommand() {
buildDss(false, false, false, DssConstants.GDSFMT_RQSDSS_NOREPLY, ++correlationID_, false);
}
// creates an object dss in the buffer to contain a ddm command
// data object. calling this method means any previous dss objects in
// the buffer are complete and their length and chaining bytes can
// be updated appropriately.
final void createCommandData() {
buildDss(true,
false,
false,
DssConstants.GDSFMT_OBJDSS,
correlationID_,
false);
}
final void createEncryptedCommandData() {
if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA ||
netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) {
buildDss(true, false, false, DssConstants.GDSFMT_ENCOBJDSS, correlationID_, false);
} else {
buildDss(true,
false,
false,
DssConstants.GDSFMT_OBJDSS,
correlationID_,
false);
}
}
// experimental lob section
private final void buildDss(boolean dssHasSameCorrelator,
boolean chainedToNextStructure,
boolean nextHasSameCorrelator,
int dssType,
int corrId,
boolean simpleFinalizeBuildingNextDss) {
if (doesRequestContainData()) {
if (simpleDssFinalize) {
finalizeDssLength();
} else {
finalizePreviousChainedDss(dssHasSameCorrelator);
}
}
ensureLength(offset_ + 6);
// save the length position and skip
// note: the length position is saved so it can be updated
// with a different value later.
dssLengthLocation_ = offset_;
// always turn on chaining flags... this is helpful for lobs...
// these bytes will get rest if dss lengths are finalized.
bytes_[offset_++] = (byte) 0xFF;
bytes_[offset_++] = (byte) 0xFF;
// insert the manditory 0xD0 and the dssType
bytes_[offset_++] = (byte) 0xD0;
if (chainedToNextStructure) {
dssType |= DssConstants.GDSCHAIN;
if (nextHasSameCorrelator) {
dssType |= DssConstants.GDSCHAIN_SAME_ID;
}
}
bytes_[offset_++] = (byte) (dssType & 0xff);
// write the request correlation id
// use method that writes a short
bytes_[offset_++] = (byte) ((corrId >>> 8) & 0xff);
bytes_[offset_++] = (byte) (corrId & 0xff);
simpleDssFinalize = simpleFinalizeBuildingNextDss;
}
final void writeScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
int codePoint,
java.io.InputStream in,
boolean writeNullByte,
int parameterIndex) throws DisconnectException, SqlException {
writePlainScalarStream(chained,
chainedWithSameCorrelator,
codePoint,
in,
writeNullByte,
parameterIndex);
}
final void writeScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
int codePoint,
int length,
java.io.InputStream in,
boolean writeNullByte,
int parameterIndex) throws DisconnectException, SqlException {
if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA ||
netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) {
writeEncryptedScalarStream(chained,
chainedWithSameCorrelator,
codePoint,
length,
in,
writeNullByte,
parameterIndex);
}else{
writePlainScalarStream(chained,
chainedWithSameCorrelator,
codePoint,
length,
in,
writeNullByte,
parameterIndex);
}
}
// We need to reuse the agent's sql exception accumulation mechanism
// for this write exception, pad if the length is too big, and truncation if the length is too small
final private void writeEncryptedScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
int codePoint,
int length,
java.io.InputStream in,
boolean writeNullByte,
int parameterIndex) throws DisconnectException, SqlException {
int leftToRead = length;
int extendedLengthByteCount = prepScalarStream(chained,
chainedWithSameCorrelator,
writeNullByte,
leftToRead);
int bytesToRead;
if (writeNullByte) {
bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - 1 - extendedLengthByteCount);
} else {
bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - extendedLengthByteCount);
}
byte[] lengthAndCodepoint;
lengthAndCodepoint = buildLengthAndCodePointForEncryptedLob(codePoint,
leftToRead,
writeNullByte,
extendedLengthByteCount);
// we need to stream the input, rather than fully materialize it
// write the data
byte[] clearedBytes = new byte[leftToRead];
int bytesRead = 0;
int totalBytesRead = 0;
int pos = 0;
do {
try {
bytesRead = in.read(clearedBytes, pos, leftToRead);
totalBytesRead += bytesRead;
} catch (java.io.IOException e) {
padScalarStreamForError(leftToRead, bytesToRead);
// set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable.
netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ),
new Integer(parameterIndex), e.getMessage(), e));
return;
}
if (bytesRead == -1) {
//padScalarStreamForError(leftToRead, bytesToRead);
// set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable.
/*throw new SqlException(netAgent_.logWriter_,
"End of Stream prematurely reached while reading InputStream, parameter #" +
parameterIndex +
". Remaining data has been padded with 0x0.");*/
//is it OK to do a chain break Exception here. It's not good to
//pad it with 0 and encrypt and send it to the server because it takes too much time
//can't just throw a SQLException either because some of the data PRPSQLSTT etc have already
//been sent to the server, and server is waiting for EXTDTA, server hangs for this.
netAgent_.accumulateChainBreakingReadExceptionAndThrow(
new DisconnectException(netAgent_,
new ClientMessageId(SQLState.NET_PREMATURE_EOS_DISCONNECT),
new Integer(parameterIndex)));
return;
/*netAgent_.accumulateReadException(
new SqlException(netAgent_.logWriter_,
"End of Stream prematurely reached while reading InputStream, parameter #" +
parameterIndex +
". Remaining data has been padded with 0x0."));
return;*/
} else {
pos += bytesRead;
//offset_ += bytesRead; //comment this out for data stream encryption.
leftToRead -= bytesRead;
}
} while (leftToRead > 0);
// check to make sure that the specified length wasn't too small
try {
if (in.read() != -1) {
// set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable.
netAgent_.accumulateReadException(new SqlException(
netAgent_.logWriter_,
new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL),
new Integer(parameterIndex)));
}
} catch (java.io.IOException e) {
netAgent_.accumulateReadException(new SqlException(
netAgent_.logWriter_,
new ClientMessageId(
SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION),
new Integer(parameterIndex),
e.getMessage(),
e));
}
byte[] newClearedBytes = new byte[clearedBytes.length +
lengthAndCodepoint.length];
System.arraycopy(lengthAndCodepoint, 0, newClearedBytes, 0,
lengthAndCodepoint.length);
System.arraycopy(clearedBytes, 0, newClearedBytes, lengthAndCodepoint.length, clearedBytes.length);
//it's wrong here, need to add in the real length after the codepoing 146c
byte[] encryptedBytes;
encryptedBytes = netAgent_.netConnection_.getEncryptionManager().
encryptData(newClearedBytes,
NetConfiguration.SECMEC_EUSRIDPWD,
netAgent_.netConnection_.getTargetPublicKey(),
netAgent_.netConnection_.getTargetPublicKey());
int encryptedBytesLength = encryptedBytes.length;
int sendingLength = bytes_.length - offset_;
if (encryptedBytesLength > (bytes_.length - offset_)) {
System.arraycopy(encryptedBytes, 0, bytes_, offset_, (bytes_.length - offset_));
// GemStone changes BEGIN
offset_ = DssConstants.MAX_DSS_LEN;
/* (original code)
offset_ = 32767;
*/
// GemStone changes END
try {
sendBytes(netAgent_.getOutputStream());
} catch (java.io.IOException ioe) {
netAgent_.throwCommunicationsFailure(ioe);
}
} else {
System.arraycopy(encryptedBytes, 0, bytes_, offset_, encryptedBytesLength);
offset_ = offset_ + encryptedBytes.length;
}
encryptedBytesLength = encryptedBytesLength - sendingLength;
while (encryptedBytesLength > 0) {
//dssLengthLocation_ = offset_;
offset_ = 0;
// GemStone changes BEGIN
if ((encryptedBytesLength - DSS_CONTINUATION_LEN) > 0) {
bytes_[offset_++] = (byte) (0xff);
bytes_[offset_++] = (byte) (0xff);
System.arraycopy(encryptedBytes, sendingLength,
bytes_, offset_, DSS_CONTINUATION_LEN);
encryptedBytesLength -= DSS_CONTINUATION_LEN;
sendingLength += DSS_CONTINUATION_LEN;
offset_ = DssConstants.MAX_DSS_LEN;
/* (original code)
if ((encryptedBytesLength - 32765) > 0) {
bytes_[offset_++] = (byte) (0xff);
bytes_[offset_++] = (byte) (0xff);
System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, 32765);
encryptedBytesLength -= 32765;
sendingLength += 32765;
offset_ = 32767;
*/
// GemStone changes END
try {
sendBytes(netAgent_.getOutputStream());
} catch (java.io.IOException ioe) {
netAgent_.throwCommunicationsFailure(ioe);
}
} else {
int leftlength = encryptedBytesLength + 2;
bytes_[offset_++] = (byte) ((leftlength >>> 8) & 0xff);
bytes_[offset_++] = (byte) (leftlength & 0xff);
System.arraycopy(encryptedBytes, sendingLength, bytes_, offset_, encryptedBytesLength);
offset_ += encryptedBytesLength;
dssLengthLocation_ = offset_;
encryptedBytesLength = 0;
}
}
}
// We need to reuse the agent's sql exception accumulation mechanism
// for this write exception, pad if the length is too big, and truncation if the length is too small
final private void writePlainScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
int codePoint,
int length,
java.io.InputStream in,
boolean writeNullByte,
int parameterIndex) throws DisconnectException, SqlException {
int leftToRead = length;
int extendedLengthByteCount = prepScalarStream(chained,
chainedWithSameCorrelator,
writeNullByte,
leftToRead);
int bytesToRead;
if (writeNullByte) {
bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - 1 - extendedLengthByteCount);
} else {
bytesToRead = Utils.min(leftToRead, DssConstants.MAX_DSS_LEN - 6 - 4 - extendedLengthByteCount);
}
buildLengthAndCodePointForLob(codePoint,
leftToRead,
writeNullByte,
extendedLengthByteCount);
int bytesRead = 0;
int totalBytesRead = 0;
do {
do {
try {
bytesRead = in.read(bytes_, offset_, bytesToRead);
totalBytesRead += bytesRead;
} catch (java.io.IOException e) {
padScalarStreamForError(leftToRead, bytesToRead);
// set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable.
netAgent_.accumulateReadException(new SqlException(
netAgent_.logWriter_,
new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ),
new Integer(parameterIndex),
e.getMessage(),
e));
return;
}
if (bytesRead == -1) {
padScalarStreamForError(leftToRead, bytesToRead);
// set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable.
netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.NET_PREMATURE_EOS),
new Integer(parameterIndex)));
return;
} else {
bytesToRead -= bytesRead;
offset_ += bytesRead;
leftToRead -= bytesRead;
}
} while (bytesToRead > 0);
bytesToRead = flushScalarStreamSegment(leftToRead, bytesToRead);
} while (leftToRead > 0);
// check to make sure that the specified length wasn't too small
try {
if (in.read() != -1) {
// set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable.
netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL),
new Integer(parameterIndex)));
}
} catch (java.io.IOException e) {
netAgent_.accumulateReadException(new SqlException(
netAgent_.logWriter_,
new ClientMessageId(
SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION),
new Integer(parameterIndex),
e.getMessage(),
e));
}
}
// We need to reuse the agent's sql exception accumulation mechanism
// for this write exception, pad if the length is too big, and truncation if the length is too small
final private void writePlainScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
int codePoint,
java.io.InputStream in,
boolean writeNullByte,
int parameterIndex) throws DisconnectException, SqlException {
in = new BufferedInputStream( in );
flushExistingDSS();
ensureLength( DssConstants.MAX_DSS_LEN );
buildDss(true,
chained,
chainedWithSameCorrelator,
DssConstants.GDSFMT_OBJDSS,
correlationID_,
true);
int spareInDss;
if (writeNullByte) {
spareInDss = DssConstants.MAX_DSS_LEN - 6 - 4 - 1;
} else {
spareInDss = DssConstants.MAX_DSS_LEN - 6 - 4;
}
buildLengthAndCodePointForLob(codePoint,
writeNullByte);
try{
int bytesRead = 0;
while( ( bytesRead =
in.read(bytes_, offset_, spareInDss )
) > -1 ) {
spareInDss -= bytesRead;
offset_ += bytesRead;
if( spareInDss <= 0 ){
if( ! peekStream( ( BufferedInputStream ) in ) )
break;
flushScalarStreamSegment();
bytes_[offset_++] = (byte) (0xff);
bytes_[offset_++] = (byte) (0xff);
spareInDss = DssConstants.MAX_DSS_LEN - 2;
}
}
} catch (java.io.IOException e) {
final SqlException sqlex =
new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.NET_IOEXCEPTION_ON_READ),
new Integer(parameterIndex),
e.getMessage(),
e);
netAgent_.accumulateReadException(sqlex);
return;
}
// check to make sure that the specified length wasn't too small
try {
if (in.read() != -1) {
// set with SQLSTATE 01004: The value of a string was truncated when assigned to a host variable.
final SqlException sqlex =
new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.NET_INPUTSTREAM_LENGTH_TOO_SMALL),
new Integer(parameterIndex));
netAgent_.accumulateReadException(sqlex);
}
} catch (java.io.IOException e) {
netAgent_.accumulateReadException(new SqlException(
netAgent_.logWriter_,
new ClientMessageId(
SQLState.NET_IOEXCEPTION_ON_STREAMLEN_VERIFICATION),
new Integer(parameterIndex),
e.getMessage(),
e));
}
}
// Throw DataTruncation, instead of closing connection if input size mismatches
// An implication of this, is that we need to extend the chaining model
// for writes to accomodate chained write exceptoins
final void writeScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
int codePoint,
int length,
java.io.Reader r,
boolean writeNullByte,
int parameterIndex) throws DisconnectException,
SqlException{
writeScalarStream(chained,
chainedWithSameCorrelator,
codePoint,
length * 2,
EncodedInputStream.createUTF16BEStream(r),
writeNullByte,
parameterIndex);
}
final void writeScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
int codePoint,
java.io.Reader r,
boolean writeNullByte,
int parameterIndex) throws DisconnectException,
SqlException{
writeScalarStream(chained,
chainedWithSameCorrelator,
codePoint,
EncodedInputStream.createUTF16BEStream(r),
writeNullByte,
parameterIndex);
}
// prepScalarStream does the following prep for writing stream data:
// 1. Flushes an existing DSS segment, if necessary
// 2. Determines if extended length bytes are needed
// 3. Creates a new DSS/DDM header and a null byte indicator, if applicable
protected final int prepScalarStream(boolean chained,
boolean chainedWithSameCorrelator,
boolean writeNullByte,
int leftToRead) throws DisconnectException {
int extendedLengthByteCount;
int nullIndicatorSize = 0;
if (writeNullByte) {
// leftToRead is cast to (long) on the off chance that +4+1 pushes it outside the range of int
extendedLengthByteCount = calculateExtendedLengthByteCount((long) leftToRead + 4 + 1);
nullIndicatorSize = 1;
} else {
extendedLengthByteCount = calculateExtendedLengthByteCount(leftToRead + 4);
}
// flush the existing DSS segment if this stream will not fit in the send buffer
// leftToRead is cast to (long) on the off chance that +4+1 pushes it outside the range of int
if (10 + extendedLengthByteCount + nullIndicatorSize + (long) leftToRead + offset_ > DssConstants.MAX_DSS_LEN) {
try {
if (simpleDssFinalize) {
finalizeDssLength();
} else {
finalizePreviousChainedDss(true);
}
sendBytes(netAgent_.getOutputStream());
} catch (java.io.IOException e) {
netAgent_.throwCommunicationsFailure(e);
}
}
if (netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRIDDTA ||
netAgent_.netConnection_.getSecurityMechanism() == NetConfiguration.SECMEC_EUSRPWDDTA) {
buildDss(true,
chained,
chainedWithSameCorrelator,
DssConstants.GDSFMT_ENCOBJDSS,
correlationID_,
true);
} else
// buildDss should not call ensure length.
{
buildDss(true,
chained,
chainedWithSameCorrelator,
DssConstants.GDSFMT_OBJDSS,
correlationID_,
true);
}
return extendedLengthByteCount;
}
protected final void flushExistingDSS() throws DisconnectException {
try {
if (simpleDssFinalize) {
finalizeDssLength();
} else {
finalizePreviousChainedDss(true);
}
sendBytes(netAgent_.getOutputStream());
} catch (java.io.IOException e) {
netAgent_.throwCommunicationsFailure(e);
}
}
// Writes out a scalar stream DSS segment, along with DSS continuation headers,
// if necessary.
protected final int flushScalarStreamSegment(int leftToRead,
int bytesToRead) throws DisconnectException {
int newBytesToRead = bytesToRead;
// either at end of data, end of dss segment, or both.
if (leftToRead != 0) {
// 32k segment filled and not at end of data.
// GemStone changes BEGIN
if ((Utils.min(2 + leftToRead, DssConstants.MAX_DSS_LEN)) >
(bytes_.length - offset_)) {
/* (original code)
if ((Utils.min(2 + leftToRead, 32767)) > (bytes_.length - offset_)) {
*/
// GemStone changes END
try {
sendBytes(netAgent_.getOutputStream());
} catch (java.io.IOException ioe) {
netAgent_.throwCommunicationsFailure(ioe);
}
}
dssLengthLocation_ = offset_;
bytes_[offset_++] = (byte) (0xff);
bytes_[offset_++] = (byte) (0xff);
// GemStone changes BEGIN
newBytesToRead = Utils.min(leftToRead, DSS_CONTINUATION_LEN);
/* (original code)
newBytesToRead = Utils.min(leftToRead, 32765);
*/
// GemStone changes END
}
return newBytesToRead;
}
protected final int flushScalarStreamSegment() throws DisconnectException {
try {
sendBytes(netAgent_.getOutputStream());
} catch (java.io.IOException ioe) {
netAgent_.throwCommunicationsFailure(ioe);
}
dssLengthLocation_ = offset_;
return DssConstants.MAX_DSS_LEN;
}
// the offset_ must not be updated when an error is encountered
// note valid data may be overwritten
protected final void padScalarStreamForError(int leftToRead, int bytesToRead) throws DisconnectException {
do {
do {
bytes_[offset_++] = (byte) (0x0); // use 0x0 as the padding byte
bytesToRead--;
leftToRead--;
} while (bytesToRead > 0);
bytesToRead = flushScalarStreamSegment(leftToRead, bytesToRead);
} while (leftToRead > 0);
}
private final void writeExtendedLengthBytes(int extendedLengthByteCount, long length) {
int shiftSize = (extendedLengthByteCount - 1) * 8;
for (int i = 0; i < extendedLengthByteCount; i++) {
bytes_[offset_++] = (byte) ((length >>> shiftSize) & 0xff);
shiftSize -= 8;
}
}
private final byte[] writeExtendedLengthBytesForEncryption(int extendedLengthByteCount, long length) {
int shiftSize = (extendedLengthByteCount - 1) * 8;
byte[] extendedLengthBytes = new byte[extendedLengthByteCount];
for (int i = 0; i < extendedLengthByteCount; i++) {
extendedLengthBytes[i] = (byte) ((length >>> shiftSize) & 0xff);
shiftSize -= 8;
}
return extendedLengthBytes;
}
// experimental lob section - end
// used to finialize a dss which is already in the buffer
// before another dss is built. this includes updating length
// bytes and chaining bits.
protected final void finalizePreviousChainedDss(boolean dssHasSameCorrelator) {
finalizeDssLength();
bytes_[dssLengthLocation_ + 3] |= 0x40;
if (dssHasSameCorrelator) // for blobs
{
bytes_[dssLengthLocation_ + 3] |= 0x10;
}
}
// method to determine if any data is in the request.
// this indicates there is a dss object already in the buffer.
protected final boolean doesRequestContainData() {
return offset_ != 0;
}
// signal the completion of a Dss Layer A object. The length of
// dss object will be calculated based on the difference between the
// start of the dss, saved on the beginDss call, and the current
// offset into the buffer which marks the end of the data. In the event
// the length requires the use of continuation Dss headers, one for each 32k
// chunk of data, the data will be shifted and the continuation headers
// will be inserted with the correct values as needed.
// Note: In the future, we may try to optimize this approach
// in an attempt to avoid these shifts.
protected final void finalizeDssLength() {
// calculate the total size of the dss and the number of bytes which would
// require continuation dss headers. The total length already includes the
// the 6 byte dss header located at the beginning of the dss. It does not
// include the length of any continuation headers.
int totalSize = offset_ - dssLengthLocation_;
// GemStone changes BEGIN
int bytesRequiringContDssHeader = totalSize - DssConstants.MAX_DSS_LEN;
/* (original code)
int bytesRequiringContDssHeader = totalSize - 32767;
*/
// GemStone changes END
// determine if continuation headers are needed
if (bytesRequiringContDssHeader > 0) {
// GemStone changes BEGIN
// if Dss is already finalized due to failover retries then return
if ((bytes_[dssLengthLocation_] & 0xff) != 0xff
|| (bytes_[dssLengthLocation_ + 1] & 0xff) != 0xff) {
return;
}
// GemStone changes END
// the continuation headers are needed, so calculate how many.
// after the first 32767 worth of data, a continuation header is
// needed for every 32765 bytes (32765 bytes of data + 2 bytes of
// continuation header = 32767 Dss Max Size).
// GemStone changes BEGIN
int contDssHeaderCount = bytesRequiringContDssHeader /
DSS_CONTINUATION_LEN;
if (bytesRequiringContDssHeader % DSS_CONTINUATION_LEN != 0) {
/* (original code)
int contDssHeaderCount = bytesRequiringContDssHeader / 32765;
if (bytesRequiringContDssHeader % 32765 != 0) {
*/
// GemStone changes END
contDssHeaderCount++;
}
// right now the code will shift to the right. In the future we may want
// to try something fancier to help reduce the copying (maybe keep
// space in the beginning of the buffer??).
// the offset points to the next available offset in the buffer to place
// a piece of data, so the last dataByte is at offset -1.
// various bytes will need to be shifted by different amounts
// depending on how many dss headers to insert so the amount to shift
// will be calculated and adjusted as needed. ensure there is enough room
// for all the conutinuation headers and adjust the offset to point to the
// new end of the data.
int dataByte = offset_ - 1;
int shiftOffset = contDssHeaderCount * 2;
ensureLength(offset_ + shiftOffset);
offset_ += shiftOffset;
// mark passOne to help with calculating the length of the final (first or
// rightmost) continuation header.
boolean passOne = true;
do {
// calculate chunk of data to shift
// GemStone changes BEGIN
int dataToShift = bytesRequiringContDssHeader %
DSS_CONTINUATION_LEN;
if (dataToShift == 0) {
dataToShift = DSS_CONTINUATION_LEN;
}
/* (original code)
int dataToShift = bytesRequiringContDssHeader % 32765;
if (dataToShift == 0) {
dataToShift = 32765;
}
*/
// GemStone changes END
// perform the shift
dataByte -= dataToShift;
System.arraycopy(bytes_, dataByte + 1,bytes_, dataByte + shiftOffset + 1, dataToShift);
// calculate the value the value of the 2 byte continuation dss header which
// includes the length of itself. On the first pass, if the length is 32767
// we do not want to set the continuation dss header flag.
int twoByteContDssHeader = dataToShift + 2;
if (passOne) {
passOne = false;
} else {
// GemStone changes BEGIN
if (twoByteContDssHeader == DssConstants.MAX_DSS_LEN) {
/* (original code)
if (twoByteContDssHeader == 32767) {
*/
// GemStone changes END
twoByteContDssHeader = 0xFFFF;
}
}
// insert the header's length bytes
bytes_[dataByte + shiftOffset - 1] = (byte) ((twoByteContDssHeader >>> 8) & 0xff);
bytes_[dataByte + shiftOffset] = (byte) (twoByteContDssHeader & 0xff);
// adjust the bytesRequiringContDssHeader and the amount to shift for
// data in upstream headers.
bytesRequiringContDssHeader -= dataToShift;
shiftOffset -= 2;
// shift and insert another header for more data.
} while (bytesRequiringContDssHeader > 0);
// set the continuation dss header flag on for the first header
totalSize = 0xFFFF;
}
// insert the length bytes in the 6 byte dss header.
bytes_[dssLengthLocation_] = (byte) ((totalSize >>> 8) & 0xff);
bytes_[dssLengthLocation_ + 1] = (byte) (totalSize & 0xff);
}
// mark the location of a two byte ddm length field in the buffer,
// skip the length bytes for later update, and insert a ddm codepoint
// into the buffer. The value of the codepoint is not checked.
// this length will be automatically updated when construction of
// the ddm object is complete (see updateLengthBytes method).
// Note: this mechanism handles extended length ddms.
protected final void markLengthBytes(int codePoint) {
ensureLength(offset_ + 4);
// save the location of length bytes in the mark stack.
mark();
// skip the length bytes and insert the codepoint
offset_ += 2;
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
}
// mark an offest into the buffer by placing the current offset value on
// a stack.
protected /* GemStone change: private */ final void mark() {
markStack_[top_++] = offset_;
}
// remove and return the top offset value from mark stack.
protected /* GemStone change: private */ final int popMark() {
return markStack_[--top_];
}
protected final void markForCachingPKGNAMCSN() {
mark();
}
protected final int popMarkForCachingPKGNAMCSN() {
return popMark();
}
// Called to update the last ddm length bytes marked (lengths are updated
// in the reverse order that they are marked). It is up to the caller
// to make sure length bytes were marked before calling this method.
// If the length requires ddm extended length bytes, the data will be
// shifted as needed and the extended length bytes will be automatically
// inserted.
protected final void updateLengthBytes() throws SqlException {
// remove the top length location offset from the mark stack\
// calculate the length based on the marked location and end of data.
int lengthLocation = popMark();
int length = offset_ - lengthLocation;
// determine if any extended length bytes are needed. the value returned
// from calculateExtendedLengthByteCount is the number of extended length
// bytes required. 0 indicates no exteneded length.
int extendedLengthByteCount = calculateExtendedLengthByteCount(length);
if (extendedLengthByteCount != 0) {
// ensure there is enough room in the buffer for the extended length bytes.
ensureLength(offset_ + extendedLengthByteCount);
// calculate the length to be placed in the extended length bytes.
// this length does not include the 4 byte llcp.
int extendedLength = length - 4;
// shift the data to the right by the number of extended length bytes needed.
int extendedLengthLocation = lengthLocation + 4;
System.arraycopy(bytes_,
extendedLengthLocation,
bytes_,
extendedLengthLocation + extendedLengthByteCount,
extendedLength);
// write the extended length
int shiftSize = (extendedLengthByteCount - 1) * 8;
for (int i = 0; i < extendedLengthByteCount; i++) {
bytes_[extendedLengthLocation++] = (byte) ((extendedLength >>> shiftSize) & 0xff);
shiftSize -= 8;
}
// adjust the offset to account for the shift and insert
offset_ += extendedLengthByteCount;
// the two byte length field before the codepoint contains the length
// of itself, the length of the codepoint, and the number of bytes used
// to hold the extended length. the 2 byte length field also has the first
// bit on to indicate extended length bytes were used.
length = extendedLengthByteCount + 4;
length |= 0x8000;
}
// write the 2 byte length field (2 bytes before codepoint).
bytes_[lengthLocation] = (byte) ((length >>> 8) & 0xff);
bytes_[lengthLocation + 1] = (byte) (length & 0xff);
}
// helper method to calculate the minimum number of extended length bytes needed
// for a ddm. a return value of 0 indicates no extended length needed.
protected /* GemStone change: private */ final int calculateExtendedLengthByteCount(long ddmSize) //throws SqlException
{
// according to Jim and some tests perfomred on Lob data,
// the extended length bytes are signed. Assume that
// if this is the case for Lobs, it is the case for
// all extended length scenarios.
if (ddmSize <= 0x7FFF) {
return 0;
} else if (ddmSize <= 0x7FFFFFFFL) {
return 4;
} else if (ddmSize <= 0x7FFFFFFFFFFFL) {
return 6;
} else {
return 8;
}
}
// insert the padByte into the buffer by length number of times.
final void padBytes(byte padByte, int length) {
ensureLength(offset_ + length);
for (int i = 0; i < length; i++) {
bytes_[offset_++] = padByte;
}
}
// insert an unsigned single byte value into the buffer.
final void write1Byte(int value) {
ensureLength(offset_ + 1);
bytes_[offset_++] = (byte) (value & 0xff);
}
// insert 3 unsigned bytes into the buffer. this was
// moved up from NetStatementRequest for performance
final void buildTripletHeader(int tripletLength,
int tripletType,
int tripletId) {
ensureLength(offset_ + 3);
bytes_[offset_++] = (byte) (tripletLength & 0xff);
bytes_[offset_++] = (byte) (tripletType & 0xff);
bytes_[offset_++] = (byte) (tripletId & 0xff);
}
final void writeLidAndLengths(int[][] lidAndLengthOverrides, int count, int offset) {
ensureLength(offset_ + (count * 3));
for (int i = 0; i < count; i++, offset++) {
bytes_[offset_++] = (byte) (lidAndLengthOverrides[offset][0] & 0xff);
bytes_[offset_++] = (byte) ((lidAndLengthOverrides[offset][1] >>> 8) & 0xff);
bytes_[offset_++] = (byte) (lidAndLengthOverrides[offset][1] & 0xff);
}
}
// if mdd overrides are not required, lids and lengths are copied straight into the
// buffer.
// otherwise, lookup the protocolType in the map. if an entry exists, substitute the
// protocolType with the corresponding override lid.
final void writeLidAndLengths(int[][] lidAndLengthOverrides,
int count,
int offset,
boolean mddRequired,
java.util.Hashtable map) {
if (!mddRequired) {
writeLidAndLengths(lidAndLengthOverrides, count, offset);
}
// if mdd overrides are required, lookup the protocolType in the map, and substitute
// the protocolType with the override lid.
else {
ensureLength(offset_ + (count * 3));
int protocolType, overrideLid;
Object entry;
for (int i = 0; i < count; i++, offset++) {
protocolType = lidAndLengthOverrides[offset][0];
// lookup the protocolType in the protocolType->overrideLid map
// if an entry exists, replace the protocolType with the overrideLid
// GemStone changes BEGIN
// changed to use Integer.valueOf() if possible
entry = map.get(protocolType);
/* (original code)
entry = map.get(new Integer(protocolType));
*/
// GemStone changes END
overrideLid = (entry == null) ? protocolType : ((Integer) entry).intValue();
bytes_[offset_++] = (byte) (overrideLid & 0xff);
bytes_[offset_++] = (byte) ((lidAndLengthOverrides[offset][1] >>> 8) & 0xff);
bytes_[offset_++] = (byte) (lidAndLengthOverrides[offset][1] & 0xff);
}
}
}
// perf end
// insert a big endian unsigned 2 byte value into the buffer.
final void write2Bytes(int value) {
ensureLength(offset_ + 2);
bytes_[offset_++] = (byte) ((value >>> 8) & 0xff);
bytes_[offset_++] = (byte) (value & 0xff);
}
// insert a big endian unsigned 4 byte value into the buffer.
final void write4Bytes(long value) {
ensureLength(offset_ + 4);
bytes_[offset_++] = (byte) ((value >>> 24) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 16) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 8) & 0xff);
bytes_[offset_++] = (byte) (value & 0xff);
}
// copy length number of bytes starting at offset 0 of the byte array, buf,
// into the buffer. it is up to the caller to make sure buf has at least length
// number of elements. no checking will be done by this method.
final void writeBytes(byte[] buf, int length) {
ensureLength(offset_ + length);
System.arraycopy(buf, 0, bytes_, offset_, length);
offset_ += length;
}
final void writeBytes(byte[] buf) {
ensureLength(offset_ + buf.length);
System.arraycopy(buf, 0, bytes_, offset_, buf.length);
offset_ += buf.length;
}
// insert a pair of unsigned 2 byte values into the buffer.
final void writeCodePoint4Bytes(int codePoint, int value) { // should this be writeCodePoint2Bytes
ensureLength(offset_ + 4);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
bytes_[offset_++] = (byte) ((value >>> 8) & 0xff);
bytes_[offset_++] = (byte) (value & 0xff);
}
// insert a 4 byte length/codepoint pair and a 1 byte unsigned value into the buffer.
// total of 5 bytes inserted in buffer.
protected final void writeScalar1Byte(int codePoint, int value) {
ensureLength(offset_ + 5);
bytes_[offset_++] = 0x00;
bytes_[offset_++] = 0x05;
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
bytes_[offset_++] = (byte) (value & 0xff);
}
// insert a 4 byte length/codepoint pair and a 2 byte unsigned value into the buffer.
// total of 6 bytes inserted in buffer.
final void writeScalar2Bytes(int codePoint, int value) {
ensureLength(offset_ + 6);
bytes_[offset_++] = 0x00;
bytes_[offset_++] = 0x06;
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
bytes_[offset_++] = (byte) ((value >>> 8) & 0xff);
bytes_[offset_++] = (byte) (value & 0xff);
}
// insert a 4 byte length/codepoint pair and a 4 byte unsigned value into the
// buffer. total of 8 bytes inserted in the buffer.
protected final void writeScalar4Bytes(int codePoint, long value) {
ensureLength(offset_ + 8);
bytes_[offset_++] = 0x00;
bytes_[offset_++] = 0x08;
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
bytes_[offset_++] = (byte) ((value >>> 24) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 16) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 8) & 0xff);
bytes_[offset_++] = (byte) (value & 0xff);
}
// insert a 4 byte length/codepoint pair and a 8 byte unsigned value into the
// buffer. total of 12 bytes inserted in the buffer.
final void writeScalar8Bytes(int codePoint, long value) {
ensureLength(offset_ + 12);
bytes_[offset_++] = 0x00;
bytes_[offset_++] = 0x0C;
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
bytes_[offset_++] = (byte) ((value >>> 56) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 48) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 40) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 32) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 24) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 16) & 0xff);
bytes_[offset_++] = (byte) ((value >>> 8) & 0xff);
bytes_[offset_++] = (byte) (value & 0xff);
}
// insert a 4 byte length/codepoint pair into the buffer.
// total of 4 bytes inserted in buffer.
// Note: the length value inserted in the buffer is the same as the value
// passed in as an argument (this value is NOT incremented by 4 before being
// inserted).
final void writeLengthCodePoint(int length, int codePoint) {
ensureLength(offset_ + 4);
bytes_[offset_++] = (byte) ((length >>> 8) & 0xff);
bytes_[offset_++] = (byte) (length & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
}
final byte[] writeEXTDTALengthCodePointForEncryption(int length, int codePoint) {
//how to encure length and offset later?
byte[] clearedBytes = new byte[4];
clearedBytes[0] = (byte) ((length >>> 8) & 0xff);
clearedBytes[1] = (byte) (length & 0xff);
clearedBytes[2] = (byte) ((codePoint >>> 8) & 0xff);
clearedBytes[3] = (byte) (codePoint & 0xff);
return clearedBytes;
}
// insert a 4 byte length/codepoint pair into the buffer followed
// by length number of bytes copied from array buf starting at offset 0.
// the length of this scalar must not exceed the max for the two byte length
// field. This method does not support extended length. The length
// value inserted in the buffer includes the number of bytes to copy plus
// the size of the llcp (or length + 4). It is up to the caller to make sure
// the array, buf, contains at least length number of bytes.
final void writeScalarBytes(int codePoint, byte[] buf, int length) {
ensureLength(offset_ + length + 4);
bytes_[offset_++] = (byte) (((length + 4) >>> 8) & 0xff);
bytes_[offset_++] = (byte) ((length + 4) & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
for (int i = 0; i < length; i++) {
bytes_[offset_++] = buf[i];
}
}
// insert a 4 byte length/codepoint pair into the buffer.
// total of 4 bytes inserted in buffer.
// Note: datalength will be incremented by the size of the llcp, 4,
// before being inserted.
final void writeScalarHeader(int codePoint, int dataLength) {
ensureLength(offset_ + dataLength + 4);
bytes_[offset_++] = (byte) (((dataLength + 4) >>> 8) & 0xff);
bytes_[offset_++] = (byte) ((dataLength + 4) & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
}
// insert a 4 byte length/codepoint pair plus ddm character data into
// the buffer. This method assumes that the String argument can be
// converted by the ccsid manager. This should be fine because usually
// there are restrictions on the characters which can be used for ddm
// character data. This method also assumes that the string.length() will
// be the number of bytes following the conversion.
// The two byte length field will contain the length of the character data
// and the length of the 4 byte llcp. This method does not handle
// scenarios which require extended length bytes.
final void writeScalarString(int codePoint, String string) throws SqlException {
int stringLength = string.length();
ensureLength(offset_ + stringLength + 4);
bytes_[offset_++] = (byte) (((stringLength + 4) >>> 8) & 0xff);
bytes_[offset_++] = (byte) ((stringLength + 4) & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
offset_ = ccsidManager_.convertFromUCS2(string, bytes_, offset_, netAgent_);
}
// insert a 4 byte length/codepoint pair plus ddm character data into the
// buffer. The ddm character data is padded if needed with the ccsid manager's
// space character if the length of the character data is less than paddedLength.
// Note: this method is not to be used for String truncation and the string length
// must be <= paddedLength.
// This method assumes that the String argument can be
// converted by the ccsid manager. This should be fine because usually
// there are restrictions on the characters which can be used for ddm
// character data. This method also assumes that the string.length() will
// be the number of bytes following the conversion. The two byte length field
// of the llcp will contain the length of the character data including the pad
// and the length of the llcp or 4. This method will not handle extended length
// scenarios.
final void writeScalarPaddedString(int codePoint, String string, int paddedLength) throws SqlException {
int stringLength = string.length();
ensureLength(offset_ + paddedLength + 4);
bytes_[offset_++] = (byte) (((paddedLength + 4) >>> 8) & 0xff);
bytes_[offset_++] = (byte) ((paddedLength + 4) & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
offset_ = ccsidManager_.convertFromUCS2(string, bytes_, offset_, netAgent_);
for (int i = 0; i < paddedLength - stringLength; i++) {
bytes_[offset_++] = ccsidManager_.space_;
}
}
// this method inserts ddm character data into the buffer and pad's the
// data with the ccsid manager's space character if the character data length
// is less than paddedLength.
// Not: this method is not to be used for String truncation and the string length
// must be <= paddedLength.
// This method assumes that the String argument can be
// converted by the ccsid manager. This should be fine because usually
// there are restrictions on the characters which can be used for ddm
// character data. This method also assumes that the string.length() will
// be the number of bytes following the conversion.
final void writeScalarPaddedString(String string, int paddedLength) throws SqlException {
int stringLength = string.length();
ensureLength(offset_ + paddedLength);
offset_ = ccsidManager_.convertFromUCS2(string, bytes_, offset_, netAgent_);
for (int i = 0; i < paddedLength - stringLength; i++) {
bytes_[offset_++] = ccsidManager_.space_;
}
}
// this method writes a 4 byte length/codepoint pair plus the bytes contained
// in array buff to the buffer.
// the 2 length bytes in the llcp will contain the length of the data plus
// the length of the llcp. This method does not handle scenarios which
// require extended length bytes.
final void writeScalarBytes(int codePoint, byte[] buff) {
int buffLength = buff.length;
ensureLength(offset_ + buffLength + 4);
bytes_[offset_++] = (byte) (((buffLength + 4) >>> 8) & 0xff);
bytes_[offset_++] = (byte) ((buffLength + 4) & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
System.arraycopy(buff, 0, bytes_, offset_, buffLength);
offset_ += buffLength;
}
// this method inserts a 4 byte length/codepoint pair plus length number of bytes
// from array buff starting at offset start.
// Note: no checking will be done on the values of start and length with respect
// the actual length of the byte array. The caller must provide the correct
// values so an array index out of bounds exception does not occur.
// the length will contain the length of the data plus the length of the llcp.
// This method does not handle scenarios which require extended length bytes.
final void writeScalarBytes(int codePoint, byte[] buff, int start, int length) {
ensureLength(offset_ + length + 4);
bytes_[offset_++] = (byte) (((length + 4) >>> 8) & 0xff);
bytes_[offset_++] = (byte) ((length + 4) & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
System.arraycopy(buff, start, bytes_, offset_, length);
offset_ += length;
}
// insert a 4 byte length/codepoint pair plus ddm binary data into the
// buffer. The binary data is padded if needed with the padByte
// if the data is less than paddedLength.
// Note: this method is not to be used for truncation and buff.length
// must be <= paddedLength.
// The llcp length bytes will contain the length of the data plus
// the length of the llcp or 4.
// This method does not handle scenarios which require extended length bytes.
final void writeScalarPaddedBytes(int codePoint, byte[] buff, int paddedLength, byte padByte) {
int buffLength = buff.length;
ensureLength(offset_ + paddedLength + 4);
bytes_[offset_++] = (byte) (((paddedLength + 4) >>> 8) & 0xff);
bytes_[offset_++] = (byte) ((paddedLength + 4) & 0xff);
bytes_[offset_++] = (byte) ((codePoint >>> 8) & 0xff);
bytes_[offset_++] = (byte) (codePoint & 0xff);
System.arraycopy(buff, 0, bytes_, offset_, buffLength);
offset_ += buffLength;
for (int i = 0; i < paddedLength - buffLength; i++) {
bytes_[offset_++] = padByte;
}
}
// this method inserts binary data into the buffer and pads the
// data with the padByte if the data length is less than the paddedLength.
// Not: this method is not to be used for truncation and buff.length
// must be <= paddedLength.
final void writeScalarPaddedBytes(byte[] buff, int paddedLength, byte padByte) {
int buffLength = buff.length;
ensureLength(offset_ + paddedLength);
System.arraycopy(buff, 0, bytes_, offset_, buffLength);
offset_ += buffLength;
for (int i = 0; i < paddedLength - buffLength; i++) {
bytes_[offset_++] = padByte;
}
}
// write the request to the OutputStream and flush the OutputStream.
// trace the send if PROTOCOL trace is on.
protected void flush(java.io.OutputStream socketOutputStream) throws java.io.IOException {
if (doesRequestContainData()) {
finalizeDssLength();
sendBytes(socketOutputStream);
}
}
protected void sendBytes(java.io.OutputStream socketOutputStream) throws java.io.IOException {
try {
socketOutputStream.write(bytes_, 0, offset_);
socketOutputStream.flush();
} finally {
if (netAgent_.logWriter_ != null && passwordIncluded_) {
// if password is in the buffer, need to mask it out.
maskOutPassword();
passwordIncluded_ = false;
}
if (netAgent_.loggingEnabled()) {
((NetLogWriter) netAgent_.logWriter_).traceProtocolFlow(bytes_,
0,
offset_,
NetLogWriter.TYPE_TRACE_SEND,
"Request",
"flush",
1); // tracepoint
}
clearBuffer();
}
}
final void maskOutPassword() {
try {
String maskChar = "*";
// construct a mask using the maskChar.
StringBuilder mask = new StringBuilder();
for (int i = 0; i < passwordLength_; i++) {
mask.append(maskChar);
}
// try to write mask over password.
ccsidManager_.convertFromUCS2(mask.toString(), bytes_, passwordStart_, netAgent_);
} catch (SqlException sqle) {
// failed to convert mask,
// them simply replace with 0xFF.
for (int i = 0; i < passwordLength_; i++) {
bytes_[passwordStart_ + i] = (byte) 0xFF;
}
}
}
// insert a java byte into the buffer.
final void writeByte(byte v) {
ensureLength(offset_ + 1);
bytes_[offset_++] = v;
}
// insert a java short into the buffer.
final void writeShort(short v) {
ensureLength(offset_ + 2);
com.pivotal.gemfirexd.internal.client.am.SignedBinary.shortToBigEndianBytes(bytes_, offset_, v);
offset_ += 2;
}
// insert a java int into the buffer.
void writeInt(int v) {
ensureLength(offset_ + 4);
com.pivotal.gemfirexd.internal.client.am.SignedBinary.intToBigEndianBytes(bytes_, offset_, v);
offset_ += 4;
}
// insert a java long into the buffer.
final void writeLong(long v) {
ensureLength(offset_ + 8);
com.pivotal.gemfirexd.internal.client.am.SignedBinary.longToBigEndianBytes(bytes_, offset_, v);
offset_ += 8;
}
//-- The following are the write short/int/long in bigEndian byte ordering --
// when writing Fdoca data.
protected void writeShortFdocaData(short v) {
ensureLength(offset_ + 2);
com.pivotal.gemfirexd.internal.client.am.SignedBinary.shortToBigEndianBytes(bytes_, offset_, v);
offset_ += 2;
}
// when writing Fdoca data.
protected void writeIntFdocaData(int v) {
ensureLength(offset_ + 4);
com.pivotal.gemfirexd.internal.client.am.SignedBinary.intToBigEndianBytes(bytes_, offset_, v);
offset_ += 4;
}
// when writing Fdoca data.
protected void writeLongFdocaData(long v) {
ensureLength(offset_ + 8);
com.pivotal.gemfirexd.internal.client.am.SignedBinary.longToBigEndianBytes(bytes_, offset_, v);
offset_ += 8;
}
// insert a java float into the buffer.
protected void writeFloat(float v) {
ensureLength(offset_ + 4);
com.pivotal.gemfirexd.internal.client.am.FloatingPoint.floatToIeee754Bytes(bytes_, offset_, v);
offset_ += 4;
}
// insert a java double into the buffer.
protected void writeDouble(double v) {
ensureLength(offset_ + 8);
com.pivotal.gemfirexd.internal.client.am.FloatingPoint.doubleToIeee754Bytes(bytes_, offset_, v);
offset_ += 8;
}
// insert a java.math.BigDecimal into the buffer.
final void writeBigDecimal(java.math.BigDecimal v,
int declaredPrecision,
int declaredScale,
String columnName /* GemStoneAddition */) throws SqlException {
ensureLength(offset_ + 16);
int length = com.pivotal.gemfirexd.internal.client.am.Decimal.bigDecimalToPackedDecimalBytes(bytes_, offset_, v, declaredPrecision, declaredScale,
columnName /* GemStoneAddition */);
offset_ += length;
}
final void writeDate(java.sql.Date date,
String columnName /* GemStoneAddition */) throws SqlException {
try
{
ensureLength(offset_ + 10);
// GemStone changes BEGIN
com.pivotal.gemfirexd.internal.client.am.DateTime.dateToDateBytes(
bytes_, offset_, date, getRecyclableCalendar());
/* (original code)
com.pivotal.gemfirexd.internal.client.am.DateTime.dateToDateBytes(bytes_, offset_, date);
*/
// GemStone changes END
offset_ += 10;
} catch (java.io.UnsupportedEncodingException e) {
throw new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.UNSUPPORTED_ENCODING),
"java.sql.Date", "DATE",
columnName /* GemStoneAddition */, e);
}
}
final void writeTime(java.sql.Time time,
String columnName /* GemStoneAddition */) throws SqlException {
try{
ensureLength(offset_ + 8);
// GemStone changes BEGIN
com.pivotal.gemfirexd.internal.client.am.DateTime.timeToTimeBytes(
bytes_, offset_, time, getRecyclableCalendar());
/* (original code)
com.pivotal.gemfirexd.internal.client.am.DateTime.timeToTimeBytes(bytes_, offset_, time);
*/
// GemStone changes END
offset_ += 8;
} catch(UnsupportedEncodingException e) {
throw new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.UNSUPPORTED_ENCODING),
"java.sql.Time", "TIME",
columnName /* GemStoneAddition */, e);
}
}
final void writeTimestamp(java.sql.Timestamp timestamp,
String columnName /* GemStoneAddition */) throws SqlException {
try{
ensureLength(offset_ + 26);
// GemStone changes BEGIN
com.pivotal.gemfirexd.internal.client.am.DateTime.timestampToTimestampBytes(
bytes_, offset_, timestamp, getRecyclableCalendar());
/* (original code)
com.pivotal.gemfirexd.internal.client.am.DateTime.timestampToTimestampBytes(bytes_, offset_, timestamp);
*/
// GemStone changes END
offset_ += 26;
}catch(UnsupportedEncodingException e) {
throw new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.UNSUPPORTED_ENCODING),
"java.sql.Timestamp", "TIMESTAMP",
columnName /* GemStoneAddition */, e);
}
}
// insert a java boolean into the buffer. the boolean is written
// as a signed byte having the value 0 or 1.
final void writeBoolean(boolean v) {
ensureLength(offset_ + 1);
bytes_[offset_++] = (byte) ((v ? 1 : 0) & 0xff);
}
// follows the TYPDEF rules (note: don't think ddm char data is ever length
// delimited)
// should this throw SqlException
// Will write a varchar mixed or single
// this was writeLDString
final void writeSingleorMixedCcsidLDString(String s, String encoding,
String columnName /* GemStoneAddition */) throws SqlException {
byte[] b;
try {
b = s.getBytes(encoding);
} catch (UnsupportedEncodingException e) {
throw new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.UNSUPPORTED_ENCODING),
"String", "byte",
columnName /* GemStoneAddition */, e);
}
if (b.length > 0x7FFF) {
throw new SqlException(netAgent_.logWriter_,
new ClientMessageId(SQLState.LANG_STRING_TOO_LONG),
"32767");
}
ensureLength(offset_ + b.length + 2);
writeLDBytesX(b.length, b);
}
final void writeLDBytes(byte[] bytes) {
ensureLength(offset_ + bytes.length + 2);
writeLDBytesX(bytes.length, bytes);
}
// private helper method which should only be called by a Request method.
// must call ensureLength before calling this method.
// added for code reuse and helps perf by reducing ensureLength calls.
// ldSize and bytes.length may not be the same. this is true
// when writing graphic ld strings.
private final void writeLDBytesX(int ldSize, byte[] bytes) {
writeLDBytesXSubset( ldSize, bytes.length, bytes );
}
// private helper method for writing just a subset of a byte array
private final void writeLDBytesXSubset( int ldSize, int bytesToCopy, byte[] bytes )
{
bytes_[offset_++] = (byte) ((ldSize >>> 8) & 0xff);
bytes_[offset_++] = (byte) (ldSize & 0xff);
System.arraycopy( bytes, 0, bytes_, offset_, bytesToCopy );
offset_ += bytesToCopy;
}
final void writeUDT( Object val,
String columnName /* GemStoneAddition */ ) throws SqlException
{
// should not be called if val is null
if ( val == null )
{
SanityManager.THROWASSERT( "UDT is null" );
}
byte[] buffer = null;
int length = 0;
try
{
DynamicByteArrayOutputStream dbaos = new DynamicByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( dbaos );
oos.writeObject( val );
buffer = dbaos.getByteArray();
length = dbaos.getUsed();
}
catch (Exception e)
{
throw new SqlException
(
netAgent_.logWriter_,
new ClientMessageId (SQLState.NET_MARSHALLING_UDT_ERROR),
e.getMessage(),
e
);
}
if ( length > DRDAConstants.MAX_DRDA_UDT_SIZE )
{
throw new SqlException
(
netAgent_.logWriter_,
new ClientMessageId(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE),
// GemStone changes BEGIN
val.getClass().getName(),
columnName
/* (original code)
Integer.toString( DRDAConstants.MAX_DRDA_UDT_SIZE ),
val.getClass().getName()
*/
// GemStone changes END
);
}
ensureLength( offset_ + length + 2 );
writeLDBytesXSubset( length, length, buffer );
}
// does it follows
// ccsid manager or typdef rules. should this method write ddm character
// data or fodca data right now it is coded for ddm char data only
final void writeDDMString(String s) throws SqlException {
ensureLength(offset_ + s.length());
offset_ = ccsidManager_.convertFromUCS2(s, bytes_, offset_, netAgent_);
}
private byte[] buildLengthAndCodePointForEncryptedLob(int codePoint,
int leftToRead,
boolean writeNullByte,
int extendedLengthByteCount) throws DisconnectException {
byte[] lengthAndCodepoint = new byte[4];
byte[] extendedLengthBytes = new byte[extendedLengthByteCount];
if (extendedLengthByteCount > 0) {
// method should never ensure length
lengthAndCodepoint = writeEXTDTALengthCodePointForEncryption(0x8004 + extendedLengthByteCount, codePoint);
if (writeNullByte) {
extendedLengthBytes = writeExtendedLengthBytesForEncryption(extendedLengthByteCount, leftToRead + 1);
} else {
extendedLengthBytes = writeExtendedLengthBytesForEncryption(extendedLengthByteCount, leftToRead);
}
} else {
if (writeNullByte) {
lengthAndCodepoint = writeEXTDTALengthCodePointForEncryption(leftToRead + 4 + 1, codePoint);
} else {
lengthAndCodepoint = writeEXTDTALengthCodePointForEncryption(leftToRead + 4, codePoint);
}
}
if (extendedLengthByteCount > 0) {
byte[] newLengthAndCodepoint = new byte[4 + extendedLengthBytes.length];
System.arraycopy(lengthAndCodepoint, 0, newLengthAndCodepoint, 0, lengthAndCodepoint.length);
System.arraycopy(extendedLengthBytes, 0, newLengthAndCodepoint, lengthAndCodepoint.length, extendedLengthBytes.length);
lengthAndCodepoint = newLengthAndCodepoint;
}
if (writeNullByte) {
byte[] nullByte = new byte[1 + lengthAndCodepoint.length];
System.arraycopy(lengthAndCodepoint, 0, nullByte, 0, lengthAndCodepoint.length);
nullByte[lengthAndCodepoint.length] = 0;
lengthAndCodepoint = nullByte;
}
return lengthAndCodepoint;
}
private void buildLengthAndCodePointForLob(int codePoint,
int leftToRead,
boolean writeNullByte,
int extendedLengthByteCount) throws DisconnectException {
if (extendedLengthByteCount > 0) {
// method should never ensure length
writeLengthCodePoint(0x8004 + extendedLengthByteCount, codePoint);
if (writeNullByte) {
writeExtendedLengthBytes(extendedLengthByteCount, leftToRead + 1);
} else {
writeExtendedLengthBytes(extendedLengthByteCount, leftToRead);
}
} else {
if (writeNullByte) {
writeLengthCodePoint(leftToRead + 4 + 1, codePoint);
} else {
writeLengthCodePoint(leftToRead + 4, codePoint);
}
}
// write the null byte, if necessary
if (writeNullByte) {
write1Byte(0x0);
}
}
private void buildLengthAndCodePointForLob(int codePoint,
boolean writeNullByte) throws DisconnectException {
//0x8004 is for Layer B Streaming.
//See DRDA, Version 3, Volume 3: Distributed Data Management (DDM) Architecture page 315.
writeLengthCodePoint(0x8004, codePoint);
// write the null byte, if necessary
if (writeNullByte) {
write1Byte(0x0);
}
}
public void setDssLengthLocation(int location) {
dssLengthLocation_ = location;
}
public void setCorrelationID(int id) {
correlationID_ = id;
}
private static boolean peekStream( BufferedInputStream in )
throws IOException {
in.mark( 1 );
boolean notYet = in.read() > -1;
in.reset();
return notYet;
}
// GemStone changes BEGIN
private java.util.Calendar recyclableCalendar;
private final java.util.Calendar getRecyclableCalendar() {
if (this.recyclableCalendar == null) {
this.recyclableCalendar = java.util.Calendar.getInstance();
}
return this.recyclableCalendar;
}
// GemStone changes END
}
| 41.448494
| 155
| 0.601769
|
e41028b89937a95edcb47e084f8891ae6f32f6bb
| 109
|
package com.vml.listofthings.core.errors;
public class NetworkUnavailableError extends RuntimeException {
}
| 21.8
| 63
| 0.844037
|
0372d3dadc246b667a7da2f7b70fcefe953fed5f
| 737
|
package org.datatransferproject.datatransfer.google.drive;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.datatransferproject.types.common.models.DataModel;
@JsonTypeName("org.dataportability:GoogleDriveFolderMapping")
class DriveFolderMapping extends DataModel {
private final String oldId;
private final String newId;
@JsonCreator
DriveFolderMapping(
@JsonProperty("oldId") String oldId,
@JsonProperty("newId") String newId) {
this.oldId = oldId;
this.newId = newId;
}
public String getNewId() {
return newId;
}
public String getOldId() {
return oldId;
}
}
| 23.774194
| 61
| 0.759837
|
5b48229e4ea0f05ebd7446d86f14c334e47a0101
| 13,836
|
/*
* Copyright 2017 iserge.
*
* 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.openlayers.ol.format;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsType;
import org.openlayers.ol.Feature;
import org.openlayers.ol.format.options.FormatReadOptions;
import org.openlayers.ol.format.options.FormatWriteOptions;
import org.openlayers.ol.format.options.PolylineFormatOptions;
import org.openlayers.ol.geom.Geometry;
import org.openlayers.ol.geom.GeometryLayout;
import org.openlayers.ol.proj.Projection;
/**
* Feature format for reading and writing data in the Encoded Polyline Algorithm Format.
*
* @author Serge Silaev aka iSergio <s.serge.b@gmail.com>
*/
@JsType(isNative = true, namespace = "ol.format", name = "Polyline")
public class PolylineFormat {
@JsConstructor
public PolylineFormat() {}
@JsConstructor
public PolylineFormat(PolylineFormatOptions options) {}
@JsOverlay
public static PolylineFormat create(double factor, GeometryLayout geometryLayout) {
PolylineFormatOptions options = new PolylineFormatOptions();
options.factor = factor;
options.geometryLayout = geometryLayout.toString();
return new PolylineFormat(options);
}
@JsOverlay
public static PolylineFormat create(double factor) {
PolylineFormatOptions options = new PolylineFormatOptions();
options.factor = factor;
return new PolylineFormat(options);
}
@JsOverlay
public static PolylineFormat create(GeometryLayout geometryLayout) {
PolylineFormatOptions options = new PolylineFormatOptions();
options.geometryLayout = geometryLayout.toString();
return new PolylineFormat(options);
}
/**
* Decode a list of n-dimensional points from an encoded string
* @param encoded An encoded string.
* @param stride The number of dimension of the points in the encoded string.
* @return A list of n-dimensional points.
*/
@JsMethod
public static native double[] decodeDeltas(String encoded, double stride);
/**
* Decode a list of n-dimensional points from an encoded string
* @param encoded An encoded string.
* @param stride The number of dimension of the points in the encoded string.
* @param factor The factor by which the resulting numbers will be divided. Default is 1e5.
* @return A list of n-dimensional points.
*/
@JsMethod
public static native double[] decodeDeltas(String encoded, double stride, double factor);
/**
* Decode a list of floating point numbers from an encoded string
* @param encoded An encoded string.
* @return A list of floating point numbers.
*/
@JsMethod
public static native double[] decodeFloats(String encoded);
/**
* Decode a list of floating point numbers from an encoded string
* @param encoded An encoded string.
* @param factor The factor by which the result will be divided. Default is 1e5.
* @return A list of floating point numbers.
*/
@JsMethod
public static native double[] decodeFloats(String encoded, double factor);
/**
* Encode a list of n-dimensional points and return an encoded string
*
* Attention: This function will modify the passed array!
* @param numbers A list of n-dimensional points.
* @param stride The number of dimension of the points in the list.
* @return The encoded string.
*/
@JsMethod
public static native String encodeDeltas(double[] numbers, double stride);
/**
* Encode a list of n-dimensional points and return an encoded string
*
* Attention: This function will modify the passed array!
* @param numbers A list of n-dimensional points.
* @param stride The number of dimension of the points in the list.
* @param factor The factor by which the numbers will be multiplied. The remaining decimal places will get rounded away.
* Default is 1e5.
* @return The encoded string.
*/
@JsMethod
public static native String encodeDeltas(double[] numbers, double stride, double factor);
/**
* Encode a list of floating point numbers and return an encoded string
* @param numbers A list of floating point numbers.
* @return The encoded string.
*/
@JsMethod
public static native String encodeFloats(double[] numbers);
/**
* Encode a list of floating point numbers and return an encoded string
* @param numbers A list of floating point numbers.
* @param factor The factor by which the numbers will be multiplied. The remaining decimal places will get rounded away.
* Default is 1e5.
* @return The encoded string.
*/
@JsMethod
public static native String encodeFloats(double[] numbers, double factor);
/**
* Read the feature from the Polyline source. The coordinates are assumed to be in two dimensions and in latitude, longitude order.
* @param source Source.
* @param options Read options.
* @return Feature.
*/
@JsMethod
public native Feature readFeature(String source, FormatReadOptions options);
/**
* Read the feature from the Polyline source. The coordinates are assumed to be in two dimensions and in latitude, longitude order.
* @param source Source.
* @param dataProjection Projection of the data we are reading. If not provided, the projection will be derived
* from the data (where possible) or the defaultDataProjection of the format
* is assigned (where set). If the projection can not be derived from the data and if no
* defaultDataProjection is set for a format, the features will not be reprojected.
* @param featureProjection Projection of the feature geometries created by the format reader. If not provided,
* features will be returned in the dataProjection.
* @return Feature.
*/
@JsOverlay
public Feature readFeature(String source, Projection dataProjection, Projection featureProjection) {
FormatReadOptions options = new FormatReadOptions();
options.dataProjection = dataProjection;
options.featureProjection = featureProjection;
return readFeature(source, options);
}
/**
* Read the feature from the Polyline source. The coordinates are assumed to be in two dimensions and in latitude, longitude order.
* @param source Source.
* @param dataProjection Projection of the data we are reading. If not provided, the projection will be derived
* from the data (where possible) or the defaultDataProjection of the format
* is assigned (where set). If the projection can not be derived from the data and if no
* defaultDataProjection is set for a format, the features will not be reprojected.
* @param featureProjection Projection of the feature geometries created by the format reader. If not provided,
* features will be returned in the dataProjection.
* @return Feature.
*/
@JsOverlay
public Feature readFeature(String source, String dataProjection, String featureProjection) {
FormatReadOptions options = new FormatReadOptions();
options.dataProjection = Projection.create(dataProjection);
options.featureProjection = Projection.create(featureProjection);
return readFeature(source, options);
}
/**
* Read the feature from the source. As Polyline sources contain a single feature, this will return the feature in an array.
* @param source Source.
* @param options Read options.
* @return Features.
*/
@JsMethod
public native Feature[] readFeatures(String source, FormatReadOptions options);
/**
* Read the feature from the source. As Polyline sources contain a single feature, this will return the feature in an array.
* @param source Source.
* @param dataProjection Projection of the data we are reading. If not provided, the projection will be derived
* from the data (where possible) or the defaultDataProjection of the format
* is assigned (where set). If the projection can not be derived from the data and if no
* defaultDataProjection is set for a format, the features will not be reprojected.
* @param featureProjection Projection of the feature geometries created by the format reader. If not provided,
* features will be returned in the dataProjection.
* @return Features.
*/
@JsOverlay
public Feature[] readFeatures(String source, Projection dataProjection, Projection featureProjection) {
FormatReadOptions options = new FormatReadOptions();
options.dataProjection = dataProjection;
options.featureProjection = featureProjection;
return readFeatures(source, options);
}
/**
* Read the feature from the source. As Polyline sources contain a single feature, this will return the feature in an array.
* @param source Source.
* @param dataProjection Projection of the data we are reading. If not provided, the projection will be derived
* from the data (where possible) or the defaultDataProjection of the format
* is assigned (where set). If the projection can not be derived from the data and if no
* defaultDataProjection is set for a format, the features will not be reprojected.
* @param featureProjection Projection of the feature geometries created by the format reader. If not provided,
* features will be returned in the dataProjection.
* @return Features.
*/
@JsOverlay
public Feature[] readFeatures(String source, String dataProjection, String featureProjection) {
FormatReadOptions options = new FormatReadOptions();
options.dataProjection = Projection.create(dataProjection);
options.featureProjection = Projection.create(featureProjection);
return readFeatures(source, options);
}
/**
* Read the geometry from the source.
* @param source Source.
* @param options Read options.
* @return Geometry.
*/
@JsMethod
public native Geometry readGeometry(String source, FormatReadOptions options);
/**
* Read the geometry from the source.
* @param source Source.
* @param dataProjection Projection of the data we are reading. If not provided, the projection will be derived
* from the data (where possible) or the defaultDataProjection of the format
* is assigned (where set). If the projection can not be derived from the data and if no
* defaultDataProjection is set for a format, the features will not be reprojected.
* @param featureProjection Projection of the feature geometries created by the format reader. If not provided,
* features will be returned in the dataProjection.
* @return Geometry.
*/
@JsOverlay
public Geometry readGeometry(String source, Projection dataProjection, Projection featureProjection) {
FormatReadOptions options = new FormatReadOptions();
options.dataProjection = dataProjection;
options.featureProjection = featureProjection;
return readGeometry(source, options);
}
/**
* Read the geometry from the source.
* @param source Source.
* @param dataProjection Projection of the data we are reading. If not provided, the projection will be derived
* from the data (where possible) or the defaultDataProjection of the format
* is assigned (where set). If the projection can not be derived from the data and if no
* defaultDataProjection is set for a format, the features will not be reprojected.
* @param featureProjection Projection of the feature geometries created by the format reader. If not provided,
* features will be returned in the dataProjection.
* @return Geometry.
*/
@JsOverlay
public Geometry readGeometry(String source, String dataProjection, String featureProjection) {
FormatReadOptions options = new FormatReadOptions();
options.dataProjection = Projection.create(dataProjection);
options.featureProjection = Projection.create(featureProjection);
return readGeometry(source, options);
}
/**
* Read the projection from a Polyline source.
* @param source Source.
* @return Projection.
*/
@JsMethod
public native Projection readProjection(String source);
/**
* Write a single geometry in Polyline format.
* @param geometry Geometry.
* @param options Write options.
* @return Geometry.
*/
@JsMethod
public native String writeGeometry(Geometry geometry, FormatWriteOptions options);
}
| 45.81457
| 135
| 0.68488
|
a8957279679d21e51eaca44992440dd5a2c80c2f
| 307
|
package com.infi.netty.apirouter.cfg;
import lombok.Builder;
import lombok.Data;
/**
* @author hongtao
* @version v 0.1 , 2018年1月9日 上午10:49:18
* @since JDK 1.8
*/
@Data
@Builder
public class ServerConfig {
private int port;
private int threadPoolSize;
private int bufferQueueSize;
}
| 16.157895
| 41
| 0.693811
|
3e3fe3a236feb178d83a5518b40ce59ea04b8a18
| 331
|
package calculator;
import calculator.operator.Operator;
import calculator.operator.OperatorFactory;
/**
* 计算器
* 通过字符串从工厂中获取具体的操作符对象
*/
public class Calculator {
public static Number calculate(String operator, Number... args) {
Operator op = OperatorFactory.get(operator);
return op.execute(args);
}
}
| 20.6875
| 69
| 0.716012
|
701c3f433bb8f0f892986620813e0a73bdd2849b
| 1,232
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.tuebingen.uni.sfs.lapps.core.converter.api;
import de.tuebingen.uni.sfs.lapps.exceptions.JsonValidityException;
import de.tuebingen.uni.sfs.lapps.exceptions.LifException;
import de.tuebingen.uni.sfs.lapps.exceptions.ConversionException;
import de.tuebingen.uni.sfs.lapps.exceptions.VocabularyMappingException;
import java.io.IOException;
import java.io.OutputStream;
import de.tuebingen.uni.sfs.lapps.core.lifwrapper.profiler.api.LifFormat;
import eu.clarin.weblicht.wlfxb.tc.xb.TextCorpusStored;
import java.io.File;
import java.io.InputStream;
/**
*
* @author Mohammad Fazleh Elahi
*/
public interface FormatConverter {
public File convertLifToTcf(InputStream input) throws LifException, VocabularyMappingException, ConversionException, IOException, JsonValidityException;
public TextCorpusStored convertLifToTcf(LifFormat lifFormat) throws LifException, VocabularyMappingException, ConversionException, IOException, JsonValidityException;
public void write(OutputStream os) throws ConversionException;
}
| 38.5
| 170
| 0.813312
|
0fc9fac96da946e12b8bc613cc901ed3b4331058
| 1,078
|
package io.spotnext.commerce;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import io.spotnext.commerce.facade.CartFacade;
import io.spotnext.commerce.facade.impl.DefaultCartFacade;
import io.spotnext.commerce.service.CartService;
import io.spotnext.commerce.service.impl.DefaultCartService;
/**
* The base spring configuration for this spOt plugin. Can be imported with "@Import(value = CommerceConfiguration.class)".
*/
@Configuration
@ComponentScan(basePackages = { "io.spotnext.commerce.strategy", "io.spotnext.commerce.service",
"io.spotnext.commerce.facade" })
@EnableAutoConfiguration
public class CommerceConfiguration {
@Bean(name = { "defaultCartService", "cartService" })
CartService cartService() {
return new DefaultCartService();
}
@Bean(name = { "defaultCartFacade", "cartFacade" })
CartFacade cartFacade() {
return new DefaultCartFacade();
}
}
| 33.6875
| 123
| 0.797774
|
76a7170aae245db1ec9dfed7fb1b52475339c566
| 5,995
|
package st.southsea.blog.module;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import st.southsea.blog.base.module.BaseModule;
import st.southsea.blog.bean.Article;
import st.southsea.blog.service.ArticleService;
import st.southsea.blog.service.FriendService;
import st.southsea.blog.service.LabelService;
import st.southsea.blog.service.UserService;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: South
* @Date: 2019-05-22 09:24
*/
@IocBean
@At("")
@Filters()
public class BrowseModule extends BaseModule {
@Inject
private UserService userService;
@Inject
private FriendService friendService;
@Inject
private ArticleService articleService;
@Inject
private LabelService labelService;
public Map<String, Object> init(HttpSession session) {
Map<String, Object> map = new HashMap<>();
List<Article> articleList = articleService.query();
if (session.getAttribute("user") != (null)) {
if (userService.fetch((String) session.getAttribute("user")) != null) {
map.put("user", userService.fetch((String) session.getAttribute("user")));
}
}
map.put("friends", friendService.query());
map.put("host", userService.getHost());
map.put("articleCount", articleList.size());
map.put("labelCount", labelService.count());
map.put("totalPages", (articleList.size() / 10) + 1);
int trafficVolume = 0;
for (Article article : articleList) {
trafficVolume += article.getBrowseVolume();
}
map.put("trafficVolume", trafficVolume);
return map;
}
// 首页查询
@At(value = {"/", "/index"})
@Ok("beetl:/index.html")
public Map<String, Object> index(HttpSession session) {
return indexPage(1, session);
}
// 首页分页查询
@At("/?")
@Ok("beetl:/index.html")
public Map<String, Object> indexPage(int page, HttpSession session) {
Map<String, Object> map = init(session);
Pager pager = new Pager(page, 10);
List<Article> articleList = articleService.query(new Article(), pager);
map.put("articleList", articleList);
map.put("page", page);
return map;
}
// 搜索查询
@At("/search")
@Ok("beetl:/index.html")
@POST
public Map<String, Object> searchArticlePage(Article article, int page, HttpSession session) {
Map<String, Object> map = init(session);
Pager pager = new Pager(page, 10);
List<Article> articleList = articleService.queryFormSearch(article, pager);
map.put("articleList", articleList);
map.put("page", page);
map.put("totalPages", (articleService.queryFormSearch(article, null).size() / 10) + 1);
return map;
}
// 分类页面
@At("/label")
@Ok("beetl:/label.html")
public Map<String, Object> label(HttpSession session) {
Map<String, Object> map = init(session);
map.put("labelList", labelService.query());
return map;
}
// 分类分页查询
@At("/label/*")
@Ok("beetl:/labels.html")
@GET
public Map<String, Object> labelPage(int labelId, int page, HttpSession session) {
Map<String, Object> map = init(session);
Article article = new Article();
article.setLabelId(labelId);
if (page == 0) {
page = 1;
}
Pager pager = new Pager(page, 10);
List<Article> articleList = articleService.query(article, pager);
map.put("articleList", articleList);
map.put("page", page);
map.remove("totalPages");
map.put("totalPages", (articleService.query(article, null).size() / 10) + 1);
map.put("label", labelService.fetch(labelId));
return map;
}
// 归档查询
@At("/archives")
@Ok("beetl:/archives.html")
public Map<String, Object> archives(HttpSession session) {
return archivesPage(1, session);
}
// 归档分页查询
@At("/archives/?")
@Ok("beetl:/archives.html")
public Map<String, Object> archivesPage(int page, HttpSession session) {
Map<String, Object> map = init(session);
Pager pager = new Pager(page, 10);
List<Article> articleList = articleService.query(new Article(), pager);
map.put("page", page);
map.put("articleList", articleList);
return map;
}
// 文章查看
@At("/article/?")
@Ok("beetl:/article.html")
public Object article(long articleId, HttpSession session) {
Article originalArticle = articleService.fetchLinks(articleId);
if (session.getAttribute(String.valueOf(articleId)) == null) {
originalArticle.setBrowseVolume(originalArticle.getBrowseVolume() + 1);
session.setAttribute(String.valueOf(articleId), 1);
session.setMaxInactiveInterval(60 * 60 * 24);
}
articleService.update(originalArticle);
Map<String, Object> map = init(session);
map.put("article", originalArticle);
List<Article> articleList = articleService.query();
int index = 0;
for (Article article : articleList) {
if (article.getArticleId() == articleId) {
if (index == 0) {
map.put("beforeArticle", null);
map.put("afterArticle", articleList.get(index + 1));
} else if (index == articleList.size() - 1) {
map.put("afterArticle", null);
map.put("beforeArticle", articleList.get(index - 1));
} else {
map.put("beforeArticle", articleList.get(index - 1));
map.put("afterArticle", articleList.get(index + 1));
}
} else {
index++;
}
}
return map;
}
}
| 32.759563
| 98
| 0.602502
|
29760ba325043deaff42bb7d3351bca243698386
| 7,617
|
// COPYRIGHT_BEGIN
//
// The MIT License (MIT)
//
// Copyright (c) 2000-2020 Wizzer Works
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// COPYRIGHT_END
// Declare package.
package com.wizzer.mle.studio.framework.attribute;
// Import standard Java packages.
import java.io.PrintStream;
/**
* This class implements a <code>String</code> attribute.
*
* @author Mark S. Millard
*/
public class StringAttribute extends Attribute
{
/**
* A constructor that initializes the <code>StringAttribute</code>.
*
* @param name The name of the attribute.
* @param value The value of the attribute.
* @param characters The number of characters that are valid as part of the <code>StringAttribute</code>
* value.
* @param isReadOnly A flag indicating whether the attribute should be read-only or not.
*/
public StringAttribute(String name, String value, int characters, boolean isReadOnly)
{
this.setName(name);
this.setValue(value);
this.setReadOnly(isReadOnly);
this.setBits(characters * 16);
}
/**
* Format the <code>StringAttribute</code> as a <code>String</code>.
*
* @return A <code>String<code> representing this <code>StringAttribute</code> is returned.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#toString()
*/
public String toString()
{
return (String) m_value;
}
/**
* Get the <code>StringAttribute</code> value as a <code>String</code>.
*
* @return A <code>String<code> representing the value of the <code>StringAttribute</code> is returned.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#getStringValue()
*/
public String getStringValue()
{
return (String) m_value;
}
/**
* Get the <code>StringAttribute</code> type.
*
* @return By default, <b>TYPE_STRING</b> is always returned.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#getType()
*/
public String getType()
{
return Attribute.TYPE_STRING;
}
/**
* Get the value of the <code>StringAttribute</code>.
*
* @return A <code>String</code> is returned.
*/
public String getValue()
{
return (String) m_value;
}
/**
* Get the value of the <code>StringAttribute</code> as a bit string.
*
* @return A <code>String</code> is returned.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#getBitString()
*/
public String getBitString()
{
String result = "";
String val = (String) m_value;
for (int i = 0; i < val.length(); i++)
{
char c = val.charAt(i);
String charString = Integer.toString(c, 2);
charString = StringAttribute.Pad(charString, true, "0", 16);
//System.out.println ("Creating a bit string for: " + getName() + " " + charString);
result = result + charString;
}
if (m_bits < result.length())
{
//System.out.println("Error: Number is too long: " + result);
}
result = this.Pad(result, false, "0");
//System.out.println ("String getBitString(): " + getName() + " " + result);
return result;
}
/**
* Load the value of the <code>StringAttribute</code> from a bit string.
*
* @param buffer The bit string to load from.
* @param offset An offset into the specified bit string indicating where to start
* loading from.
*
* @return A new offset is calculated and returned.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#loadFromBitString(java.lang.String, int)
*/
public int loadFromBitString(String buffer, int offset)
{
this.setValue("");
//System.out.println ("Trying this string: " + getName());
long charCount = this.getBits() / 16;
for (int i = offset; i < offset + this.getBits(); i += 16)
{
String bitString = buffer.substring(i, i + 16);
char c = (char) Integer.parseInt(bitString, 2);
if (c == 0) continue;
//System.out.println ("Char: " + c);
this.setValue(((String) m_value) + c);
}
//System.out.println ("Loaded String: " + getName() + " " + bits + " [" + offset + ", " + getBits() + "] " + toString());
return offset + this.getBits();
}
/**
* Dump the contents of the <b>StringAttribute</b> to the specified print stream.
* <p>
* The contents of any child attributes will also be dumped.
* </p>
*
* @param ps The <code>PrintStream</code> to dump to.
* @param indent A <code>String</code> specifying an indentation format.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#dump(PrintStream, java.lang.String)
*/
public void dump(PrintStream ps, String indent)
{
ps.println(indent + " " + this.getName() + " (String) " + this.getValue() + " " + this.getBits() + " " + this.getBitString());
for (int i = 0; i < this.getChildCount(); i++)
{
Attribute a = this.getChild(i);
a.dump(ps, indent + "|---");
}
}
/**
* Test to see if the specified object is different from this <code>StringAttribute</code>.
*
* @param obj The <code>Object</code> to test against.
*
* @return <b>true</b> will be returned if the specified <code>Object</code> is different
* from this <code>StringAttribute</code>. If they are not different, then <b>false</b> will be
* returned.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#isDifferent(Object)
*/
public boolean isDifferent (Object v)
{
return this.getValue() == null || this.getValue().compareTo((String) v) != 0;
}
/**
* Get a copy of the contents of this <code>StringAttribute</code>.
*
* @return A shallow copy of the <code>StringAttribute</code> is returned.
* The children of the <code>StringAttribute</code> are <b>not</b> copied.
*/
public Attribute copy()
{
StringAttribute attr = new StringAttribute(getName(),getValue(),getBits() / 16,getReadOnly());
return attr;
}
/**
* Validate the value of the <code>StringAttribute</code>.
*
* @return <b>true</b> will be returned if the value of the attribute is valid.
* Otherwise, b>false</b> will be returned if the value is invalid.
*
* @see com.wizzer.mle.studio.framework.attribute.Attribute#validate()
*/
public boolean validate()
{
// XXX - Do something more useful here.
return true;
}
}
| 33.555066
| 137
| 0.63437
|
2cdfe0ffa952f87f61358fe30287f571d8345a9c
| 253
|
package com.bnc.sbjb;
public class HelloWorld {
private final String name;
public HelloWorld(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Hello %s", name);
}
}
| 15.8125
| 47
| 0.608696
|
eac7162db3ad464e3e81f3281bc523dfde27d2cc
| 733
|
package net.lightapi.portal;
import org.junit.jupiter.api.Test;
import org.wildfly.common.Assert;
public class HybridQueryClientTest {
@Test
public void testStringFormat() {
String expect = "{\"host\":\"lightapi.net\",\"service\":\"market\",\"action\":\"getAuthCode\",\"version\":\"0.1.0\",\"data\":{\"host\":\"networknt.com\",\"offset\":0,\"limit\":25}}";
String host = "networknt.com";
int offset = 0;
int limit = 25;
final String s = String.format("{\"host\":\"lightapi.net\",\"service\":\"market\",\"action\":\"getAuthCode\",\"version\":\"0.1.0\",\"data\":{\"host\":\"%s\",\"offset\":%s,\"limit\":%s}}", host, offset, limit);
Assert.assertTrue(expect.equals(s));
}
}
| 43.117647
| 217
| 0.58663
|
94ed0429ba74a241f8265e479fccb912a08fc3c0
| 340
|
package com.kloia.eventapis.view;
import java.util.List;
import java.util.Optional;
@SuppressWarnings("checkstyle:InterfaceTypeParameterName")
public interface SnapshotRepository<T, ID> {
<S extends T> List<S> saveAll(Iterable<S> entities);
<S extends T> S save(S entity);
void flush();
Optional<T> findById(ID id);
}
| 20
| 58
| 0.720588
|
e7e38709c380b46c933537393bafd650b8aff8fe
| 3,202
|
package com.aliyun.oss.crypto;
import java.nio.ByteBuffer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.crypto.CryptoCipher;
public abstract class CryptoScheme {
// Enable bouncy castle provider
static {
CryptoRuntime.enableBouncyCastle();
}
public static final int BLOCK_SIZE = 16;
public static final CryptoScheme AES_CTR = new AesCtr();
public abstract String getKeyGeneratorAlgorithm();
public abstract int getKeyLengthInBits();
public abstract String getContentChiperAlgorithm();
public abstract int getContentChiperIVLength();
public abstract byte[] adjustIV(byte[] iv, long dataStartPos);
/**
* This is a factory method to create CryptoCipher.
*/
public CryptoCipher newCryptoCipher(Cipher cipher, SecretKey cek, int cipherMode) {
return new CryptoCipher(cipher, this, cek, cipherMode);
}
public CryptoCipher createCryptoCipher(SecretKey cek, byte[] iv, int cipherMode, Provider provider) {
try {
Cipher cipher = null;
if (provider != null) {
cipher = Cipher.getInstance(getContentChiperAlgorithm(), provider);
} else {
cipher = Cipher.getInstance(getContentChiperAlgorithm());
}
cipher.init(cipherMode, cek, new IvParameterSpec(iv));
return newCryptoCipher(cipher, cek, cipherMode);
} catch (Exception e) {
throw new ClientException("Unable to build cipher: " + e.getMessage(), e);
}
}
/**
* Increment the rightmost 64 bits of a 16-byte counter by the specified delta.
* Both the specified delta and the resultant value must stay within the
* capacity of 64 bits. (Package private for testing purposes.)
*
* @param counter
* a 16-byte counter.
* @param blockDelta
* the number of blocks (16-byte) to increment
*/
public static byte[] incrementBlocks(byte[] counter, long blockDelta) {
if (blockDelta == 0)
return counter;
if (counter == null || counter.length != 16)
throw new IllegalArgumentException();
ByteBuffer bb = ByteBuffer.allocate(8);
for (int i = 12; i <= 15; i++)
bb.put(i - 8, counter[i]);
long val = bb.getLong() + blockDelta; // increment by delta
bb.rewind();
byte[] result = bb.putLong(val).array();
for (int i = 8; i <= 15; i++)
counter[i] = result[i - 8];
return counter;
}
public static CryptoScheme fromCEKAlgo(String cekAlgo) {
if (AES_CTR.getContentChiperAlgorithm().equals(cekAlgo)) {
return AES_CTR;
}
throw new UnsupportedOperationException("Unsupported content encryption scheme: " + cekAlgo);
}
}
| 34.06383
| 105
| 0.656152
|
af4a1c649c963698aca4ac90df824b1013a8962d
| 4,580
|
/*
* Copyright 2021 S. Webber
*
* 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.projog.core.predicate.builtin.compound;
import static org.projog.core.term.TermUtils.castToNumeric;
import java.util.Objects;
import org.projog.core.predicate.AbstractPredicateFactory;
import org.projog.core.predicate.Predicate;
import org.projog.core.predicate.PredicateFactory;
import org.projog.core.predicate.PreprocessablePredicateFactory;
import org.projog.core.predicate.builtin.list.PartialApplicationUtils;
import org.projog.core.term.Term;
/* TEST
%?- limit(3, repeat)
%YES
%YES
%YES
%FAIL limit(-1, true)
%FAIL limit(0, true)
%TRUE limit(1, true)
%TRUE limit(2, true)
%FAIL limit(-1, fail)
%FAIL limit(0, fail)
%FAIL limit(1, fail)
%FAIL limit(2, fail)
%TRUE assert(p(a)), assert(p(b)), assert(p(c))
%FAIL limit(-1, p(X))
%FAIL limit(0, p(X))
%?- limit(1, p(X))
% X=a
%?- limit(2, p(X))
% X=a
% X=b
%?- limit(3, p(X))
% X=a
% X=b
% X=c
%?- limit(4, p(X))
% X=a
% X=b
% X=c
%?- X=a, limit(3, p(X))
% X=a
%?- X=b, limit(3, p(X))
% X=b
%?- X=c, limit(3, p(X))
% X=c
%FAIL X=d, limit(3, p(X))
%FAIL X=fail, limit(3, X)
%?- X=true, limit(3, X)
% X=true
%?- X=repeat, limit(3, X)
% X=repeat
% X=repeat
% X=repeat
%?- limit(a, true)
%ERROR Expected Numeric but got: ATOM with value: a
%?- limit(X, true)
%ERROR Expected Numeric but got: VARIABLE with value: X
%?- limit(3, X)
%ERROR Expected an atom or a predicate but got a VARIABLE with value: X
%?- limit(3, 999)
%ERROR Expected an atom or a predicate but got a INTEGER with value: 999
%FAIL limit(3, unknown_predicate)
p(a,1).
p(a,2).
p(a,3).
p(a,4).
p(a,5).
p(b,1).
p(b,2).
p(b,3).
p(c,1).
p(c,3).
p(d(1),1).
p(d(2),2).
p(d(3),2).
p(d(4),2).
p(d(5),5).
%?- limit(3, p(a,X))
% X=1
% X=2
% X=3
%?- limit(6, p(X,2))
% X=a
% X=b
% X=d(2)
% X=d(3)
% X=d(4)
%?- limit(7, p(d(X),X))
% X=1
% X=2
% X=5
*/
/**
* <code>limit(N, X)</code> - calls the goal represented by a term a maximum number of times.
* <p>
* Evaluates the goal represented by <code>X</code> for a maximum of <code>N</code> attempts.
*/
public final class Limit extends AbstractPredicateFactory implements PreprocessablePredicateFactory
{
@Override
public Predicate getPredicate(Term maxAttempts, Term goal) {
PredicateFactory pf = getPredicates().getPredicateFactory(goal);
return getLimitPredicate(pf, maxAttempts, goal);
}
private static Predicate getLimitPredicate(PredicateFactory pf, Term maxAttempts, Term goal) {
Predicate p = pf.getPredicate(goal.getArgs());
long n = castToNumeric(maxAttempts).getLong();
return new LimitPredicate(p, n);
}
@Override
public PredicateFactory preprocess(Term term) {
Term goal = term.getArgument(1);
if (PartialApplicationUtils.isAtomOrStructure(goal)) {
return new OptimisedLimit(getPredicates().getPreprocessedPredicateFactory(goal));
} else {
return this;
}
}
private static final class OptimisedLimit implements PredicateFactory {
private final PredicateFactory pf;
OptimisedLimit(PredicateFactory pf) {
this.pf = Objects.requireNonNull(pf);
}
@Override
public Predicate getPredicate(Term[] args) {
return getLimitPredicate(pf, args[0], args[1]);
}
@Override
public boolean isRetryable() {
return true;
}
}
private static final class LimitPredicate implements Predicate {
private final Predicate predicate;
private final long limit;
private long ctr;
private LimitPredicate(Predicate predicate, long limit) {
this.predicate = predicate;
this.limit = limit;
}
@Override
public boolean evaluate() {
if (couldReevaluationSucceed()) {
ctr++;
return predicate.evaluate();
} else {
return false;
}
}
@Override
public boolean couldReevaluationSucceed() {
return ctr < limit && (ctr == 0 || predicate.couldReevaluationSucceed());
}
}
}
| 22.341463
| 99
| 0.650873
|
cfc85f9ec90b895b0f5d4a1fad213604945c948b
| 818
|
package com.shine.common;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.shine.common.constant.XmlErrorInfo;
/**
* Created with IntelliJ IDEA.
*
* @author Berry_Cooper.
* @date 2019-06-23 00:16
* fileName:XmlResponse
* Use:Get请求 错误响应,多用于读取文件
*/
@JacksonXmlRootElement(localName = "ERROR")
public class XmlResponse {
@JacksonXmlProperty(localName = "INFO")
public XmlErrorInfo xmlErrorInfo;
public XmlResponse(XmlErrorInfo xmlErrorInfo) {
this.xmlErrorInfo = xmlErrorInfo;
}
public XmlErrorInfo getXmlErrorInfo() {
return xmlErrorInfo;
}
public void setXmlErrorInfo(XmlErrorInfo xmlErrorInfo) {
this.xmlErrorInfo = xmlErrorInfo;
}
}
| 24.787879
| 77
| 0.740831
|
de5caa7cfffbc75e5db67aa72dee24764fae7271
| 595
|
package com.spaceprogram.simplejpa;
/**
* This attribute will be used to define multi-value attributes.
*
* Probably should be defined as a Set property on the class, but stored as a multi-value attribute.
*
* Then queries could be applied on the attribute, wouldn't need multiple queries.
*
* eg: select o from MyObject o where o.multiValProperty = 'keyword'
*
* see: http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1231&categoryID=152
*
* User: treeder
* Date: Feb 19, 2008
* Time: 7:05:43 PM
*/
public @interface MultiValueProperty {
}
| 29.75
| 101
| 0.710924
|
0c43b3637c77296bb9e4afdbc1e7fe69b3c3a52d
| 411
|
package com.interview.systemdesign.cabbookingsystem;
public class Kyc {
private String govtId;
private String idType;
public String getGovtId() {
return govtId;
}
public void setGovtId(String govtId) {
this.govtId = govtId;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
}
| 19.571429
| 52
| 0.63017
|
da3abebe6a2a80dc39dec989cda4dbe64fddec1f
| 64
|
package modulardiversity.item;
public class ItemNumberChip {
}
| 12.8
| 30
| 0.8125
|
4841c4e7c7815af0d94f42b6d039801daa8ac81e
| 1,553
|
/*
* Copyright (c) [2021] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
class ThreadTest_24 {
/* Test for interrupt() -- Interrupt the current thread
* If this thread is blocked in an invocation
* of the wait(), wait(long), or wait(long, int) methods of the Object class, or
* of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class,
* then its interrupt status will be cleared and it will receive an InterruptedException.
*/
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
interrupt();
System.out.println("in the new thread, isInterrupted() returns -- " + isInterrupted());
}
};
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("unexpected InterruptedException while sleeping");
}
System.out.println("isInterrupted() finally returns -- " + t.isInterrupted());
System.out.println("PASS");
}
}
| 38.825
| 107
| 0.639408
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.