blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
ed6402f29c698c337957fbcda9a1acf3227689fc
37a4fc5b0e2853e5d6e17c71731061d16333d024
/oo/composicao/desafio/Compra.java
f1f5a0fd8666ca094bada0cd751751e02a9f5466
[]
no_license
Espinace/CursoJava
38196a42c68c4ef08b57a7b350626d1aedbf61a9
b80f049d83ec36dc6dfa6aff5be346bb721cc0ca
refs/heads/main
2023-07-24T19:41:29.385842
2021-09-02T02:55:40
2021-09-02T02:55:40
302,435,318
1
0
null
null
null
null
UTF-8
Java
false
false
557
java
package oo.composicao.desafio; import java.util.ArrayList; public class Compra { final ArrayList<Item> itens = new ArrayList<Item>(); void adicionarItem(Produto p, int qtde) { this.itens.add(new Item(p, qtde)); } void adicionarItem(String nome, double preco, int qtde) { var produto = new Produto(nome, preco); this.itens.add(new Item(produto, qtde)); } double obterValorTotal() { double total = 0; for(Item item: itens) { total += item.quantidade * item.produto.preco; } return total; } }
[ "noreply@github.com" ]
Espinace.noreply@github.com
9f35d168ac40fdd93e665824adf056283ad74d72
5e3f8c4df165df7f4ec7f4f9f87d2c7e8364edf6
/social-multiplication/src/main/java/microservices/book/socialmultiplication/event/MultiplicationSolvedEvent.java
778e010b13e10ca955f28b9ed92cc5afe7f88670
[]
no_license
0stein/springboot-microservice-example
140b00b91d77ae8b309c43ab4fbbf6d8d531c005
7bab86064a7fab82905076b25ef364b60363c867
refs/heads/master
2022-12-31T13:25:35.781105
2020-10-24T15:16:34
2020-10-24T15:16:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
671
java
package microservices.book.socialmultiplication.event; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; import java.io.Serializable; /** * 시스템에서 {@link microservices.book.socialmultiplication.domain.Multiplication} * 문제가 해결됐다는 사실을 모델링한 이벤트. * 곱셈에 대한 컨텍스트 정보를 제공한다. */ @RequiredArgsConstructor @Getter @ToString @EqualsAndHashCode public class MultiplicationSolvedEvent implements Serializable { private final Long multiplicationResultAttemptId; private final Long userId; private final boolean correct; }
[ "aad336645@gmail.com" ]
aad336645@gmail.com
c12bb21db928db80db8e55a301485db524800da3
80daebee78251e16782eb29371e19aeddc4e8044
/interface4.java
c2c7949a2034779ac34bbd4b6c29e8b395884dd5
[]
no_license
piyushkumar786/Core_java
fc26443b23f8c8d58a962262e931e92ffd262236
13bcc434e4b18addff872aa81c551678ae27c443
refs/heads/master
2020-06-24T05:39:17.486857
2019-07-25T16:38:11
2019-07-25T16:38:11
198,865,692
0
0
null
null
null
null
UTF-8
Java
false
false
1,274
java
//1.how to implement interface it1//abstract class { void m1();//public abstract method } interface it2 extends it1//inheritence between interface using extend keyword { void m2(); } interface it3 extends it2 { void m3(); } class test implements it1 { //this called called m1() } class test implements it2 { //this class called m1(),m2() } class test implemants it3 { //this class implements m1(),m2(),m3() } //2. interface it1//abstract class { void m1();//public abstract method } interface it2 extends it1//inheritence between interface using extend keyword { void m2(); } interface it3 extends it2,it1//it can possible access at time two interface { void m3(); } class test implements it3 { //this called called m1(),m2(),m3() } //class extends class //interface extends interface //class implements interface //class a extends b--valid //class a extends a,b--invalid //class a implements it1----valid //class a,b implements it1,it2---valid //class a extends a---invlaid //interface it1 extends it2---valid //interface it1 extends it1,it2---valid //interface it1 extends a----invalid //interface it1 extends it1---invalid //(extend keyword must be first keyword) //class a extends b implements it1,it2 ----valid //class a implements it1,it2 extends b---invalid
[ "noreply@github.com" ]
piyushkumar786.noreply@github.com
e8ce736bb1cdc0ef1847d9bcaa235fe792f83ec9
a4a2f08face8d49aadc16b713177ba4f793faedc
/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamTask.java
6ba946793b32e8cfd52ac10ef2332f841e15accc
[ "BSD-3-Clause", "MIT", "OFL-1.1", "ISC", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wyfsxs/blink
046d64afe81a72d4d662872c007251d94eb68161
aef25890f815d3fce61acb3d1afeef4276ce64bc
refs/heads/master
2021-05-16T19:05:23.036540
2020-03-27T03:42:35
2020-03-27T03:42:35
250,431,969
0
1
Apache-2.0
2020-03-27T03:48:25
2020-03-27T03:34:26
Java
UTF-8
Java
false
false
44,601
java
/* * 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.flink.streaming.runtime.tasks; import org.apache.flink.annotation.Internal; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.TaskInfo; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.TaskManagerOptions; import org.apache.flink.core.fs.CloseableRegistry; import org.apache.flink.core.fs.FileSystemSafetyNet; import org.apache.flink.runtime.accumulators.AccumulatorRegistry; import org.apache.flink.runtime.checkpoint.CheckpointMetaData; import org.apache.flink.runtime.checkpoint.CheckpointMetrics; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.checkpoint.TaskStateSnapshot; import org.apache.flink.runtime.execution.CancelTaskException; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.io.network.api.CancelCheckpointMarker; import org.apache.flink.runtime.io.network.api.writer.ResultPartitionWriter; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.state.CheckpointStorage; import org.apache.flink.runtime.state.CheckpointStreamFactory; import org.apache.flink.runtime.state.StateBackend; import org.apache.flink.runtime.state.StateBackendLoader; import org.apache.flink.runtime.state.TaskStateManager; import org.apache.flink.runtime.taskmanager.DispatcherThreadFactory; import org.apache.flink.runtime.util.OperatorSubtaskDescriptionText; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.graph.StreamConfig; import org.apache.flink.streaming.api.graph.StreamEdge; import org.apache.flink.streaming.api.operators.OperatorSnapshotFinalizer; import org.apache.flink.streaming.api.operators.OperatorSnapshotFutures; import org.apache.flink.streaming.api.operators.StreamOperator; import org.apache.flink.streaming.api.operators.StreamTaskStateInitializer; import org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl; import org.apache.flink.streaming.runtime.io.RecordWriterOutput; import org.apache.flink.streaming.runtime.io.StreamRecordWriter; import org.apache.flink.streaming.runtime.partitioner.ConfigurableStreamPartitioner; import org.apache.flink.streaming.runtime.partitioner.StreamPartitioner; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.streaming.runtime.streamstatus.StreamStatusMaintainer; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.util.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.Closeable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicReference; /** * Base class for all streaming tasks. A task is the unit of local processing that is deployed * and executed by the TaskManagers. Each task runs one or more {@link StreamOperator}s which form * the Task's operator chain. Operators that are chained together execute synchronously in the * same thread and hence on the same stream partition. A common case for these chains * are successive map/flatmap/filter tasks. * * <p>The task chain contains one "head" operator and multiple chained operators. * The StreamTask is specialized for the type of the head operator: one-input and two-input tasks, * as well as for sources, iteration heads and iteration tails. * * <p>The Task class deals with the setup of the streams read by the head operator, and the streams * produced by the operators at the ends of the operator chain. Note that the chain may fork and * thus have multiple ends. * * <p>The life cycle of the task is set up as follows: * <pre>{@code * -- setInitialState -> provides state of all operators in the chain * * -- invoke() * | * +----> Create basic utils (config, etc) and load the chain of operators * +----> operators.setup() * +----> task specific init() * +----> initialize-operator-states() * +----> open-operators() * +----> run() * +----> close-operators() * +----> dispose-operators() * +----> common cleanup * +----> task specific cleanup() * }</pre> * * <p>The {@code StreamTask} has a lock object called {@code lock}. All calls to methods on a * {@code StreamOperator} must be synchronized on this lock object to ensure that no methods * are called concurrently. * * @param <OUT> * @param <OP> */ @Internal public abstract class StreamTask<OUT, OP extends StreamOperator<OUT>> extends AbstractInvokable implements AsyncExceptionHandler { /** The thread group that holds all trigger timer threads. */ public static final ThreadGroup TRIGGER_THREAD_GROUP = new ThreadGroup("Triggers"); /** The logger used by the StreamTask and its subclasses. */ private static final Logger LOG = LoggerFactory.getLogger(StreamTask.class); // ------------------------------------------------------------------------ /** * All interaction with the {@code StreamOperator} must be synchronized on this lock object to * ensure that we don't have concurrent method calls that void consistent checkpoints. */ private final Object lock = new Object(); /** The configuration of the head operator. */ protected final StreamConfig configuration; /** The chain of operators executed by this task. */ protected OperatorChain operatorChain; /** The configuration of this streaming task. */ protected final StreamTaskConfigSnapshot streamTaskConfig; /** Our state backend. We use this to create checkpoint streams and a keyed state backend. */ protected StateBackend stateBackend; /** The external storage where checkpoint data is persisted. */ private CheckpointStorage checkpointStorage; /** * The internal {@link ProcessingTimeService} used to define the current * processing time (default = {@code System.currentTimeMillis()}) and * register timers for tasks to be executed in the future. */ protected ProcessingTimeService timerService; /** The map of user-defined accumulators of this task. */ private AccumulatorRegistry accumulatorRegistry; /** The currently active background materialization threads. */ private final CloseableRegistry cancelables = new CloseableRegistry(); /** * Flag to mark the task "in operation", in which case check needs to be initialized to true, * so that early cancel() before invoke() behaves correctly. */ private volatile boolean isRunning; /** Flag to mark this task as canceled. */ private volatile boolean canceled; /** Thread pool for async snapshot workers. */ private ExecutorService asyncOperationsThreadPool; /** Handler for exceptions during checkpointing in the stream task. Used in synchronous part of the checkpoint. */ private CheckpointExceptionHandler synchronousCheckpointExceptionHandler; /** Wrapper for synchronousCheckpointExceptionHandler to deal with rethrown exceptions. Used in the async part. */ private AsyncCheckpointExceptionHandler asynchronousCheckpointExceptionHandler; private final List<StreamRecordWriter<StreamRecord<?>>> streamRecordWriters; // ------------------------------------------------------------------------ /** * Constructor for initialization, possibly with initial state (recovery / savepoint / etc). * * @param env The task environment for this task. */ protected StreamTask(Environment env) { this(env, null); } /** * Constructor for initialization, possibly with initial state (recovery / savepoint / etc). * * <p>This constructor accepts a special {@link ProcessingTimeService}. By default (and if * null is passes for the time provider) a {@link SystemProcessingTimeService DefaultTimerService} * will be used. * * @param environment The task environment for this task. * @param timeProvider Optionally, a specific time provider to use. */ protected StreamTask( Environment environment, @Nullable ProcessingTimeService timeProvider) { super(environment); this.timerService = timeProvider; this.streamTaskConfig = StreamTaskConfigCache.deserializeFrom( new StreamTaskConfig(super.getTaskConfiguration()), this.getUserCodeClassLoader()); this.streamRecordWriters = createStreamRecordWriters(streamTaskConfig, environment); List<StreamConfig> chainedNodeConfigs = streamTaskConfig.getChainedHeadNodeConfigs(); this.configuration = chainedNodeConfigs.size() == 0 ? new StreamConfig(new Configuration()) : chainedNodeConfigs.get(0); } // ------------------------------------------------------------------------ // Life cycle methods for specific implementations // ------------------------------------------------------------------------ protected abstract void init() throws Exception; protected abstract void run() throws Exception; protected abstract void cleanup() throws Exception; protected abstract void cancelTask() throws Exception; // ------------------------------------------------------------------------ // Core work methods of the Stream Task // ------------------------------------------------------------------------ /** * Allows the user to specify his own {@link ProcessingTimeService TimerServiceProvider}. * By default a {@link SystemProcessingTimeService DefaultTimerService} is going to be provided. * Changing it can be useful for testing processing time functionality, such as * {@link org.apache.flink.streaming.api.windowing.assigners.WindowAssigner WindowAssigners} * and {@link org.apache.flink.streaming.api.windowing.triggers.Trigger Triggers}. * */ @VisibleForTesting public void setProcessingTimeService(ProcessingTimeService timeProvider) { if (timeProvider == null) { throw new RuntimeException("The timeProvider cannot be set to null."); } timerService = timeProvider; } public StreamTaskStateInitializer createStreamTaskStateInitializer() { return new StreamTaskStateInitializerImpl( getEnvironment(), stateBackend, timerService); } @Override public final void invoke() throws Exception { boolean disposed = false; try { // -------- Initialize --------- LOG.debug("Initializing {}.", getName()); asyncOperationsThreadPool = Executors.newCachedThreadPool(); CheckpointExceptionHandlerFactory cpExceptionHandlerFactory = createCheckpointExceptionHandlerFactory(); synchronousCheckpointExceptionHandler = cpExceptionHandlerFactory.createCheckpointExceptionHandler( getExecutionConfig().isFailTaskOnCheckpointError(), getEnvironment()); asynchronousCheckpointExceptionHandler = new AsyncCheckpointExceptionHandler(this); stateBackend = createStateBackend(); checkpointStorage = stateBackend.createCheckpointStorage(getEnvironment().getJobID()); accumulatorRegistry = getEnvironment().getAccumulatorRegistry(); // if the clock is not already set, then assign a default TimeServiceProvider if (timerService == null) { ThreadFactory timerThreadFactory = new DispatcherThreadFactory(TRIGGER_THREAD_GROUP, "Time Trigger for " + getName()); timerService = new SystemProcessingTimeService(this, getCheckpointLock(), timerThreadFactory); } operatorChain = new OperatorChain(this, streamRecordWriters); // task specific initialization init(); // save the work of reloading state, etc, if the task is already canceled if (canceled) { throw new CancelTaskException(); } // -------- Invoke -------- LOG.debug("Invoking {}", getName()); // we need to make sure that any triggers scheduled in open() cannot be // executed before all operators are opened synchronized (lock) { // both the following operations are protected by the lock // so that we avoid race conditions in the case that initializeState() // registers a timer, that fires before the open() is called. initializeState(); openAllOperators(); } // final check to exit early before starting to run if (canceled) { throw new CancelTaskException(); } // let the task do its work isRunning = true; run(); // if this left the run() method cleanly despite the fact that this was canceled, // make sure the "clean shutdown" is not attempted if (canceled) { throw new CancelTaskException(); } LOG.debug("Finished task {}", getName()); // make sure no further checkpoint and notification actions happen. // we make sure that no other thread is currently in the locked scope before // we close the operators by trying to acquire the checkpoint scope lock // we also need to make sure that no triggers fire concurrently with the close logic // at the same time, this makes sure that during any "regular" exit where still synchronized (lock) { // this is part of the main logic, so if this fails, the task is considered failed closeAllOperators(); // make sure no new timers can come timerService.quiesce(); // only set the StreamTask to not running after all operators have been closed! // See FLINK-7430 isRunning = false; } // make sure all timers finish timerService.awaitPendingAfterQuiesce(); LOG.debug("Closed operators for task {}", getName()); // make sure all buffered data is flushed operatorChain.flushOutputs(); // make an attempt to dispose the operators such that failures in the dispose call // still let the computation fail tryDisposeAllOperators(); disposed = true; } catch (Throwable t) { LOG.error("Could not execute the task " + getName() + ", aborting the execution", t); throw t; } finally { // clean up everything we initialized isRunning = false; // stop all timers and threads tryShutdownTimerService(); // stop all asynchronous checkpoint threads try { cancelables.close(); shutdownAsyncThreads(); } catch (Throwable t) { // catch and log the exception to not replace the original exception LOG.error("Could not shut down async checkpoint threads", t); } // we must! perform this cleanup try { cleanup(); } catch (Throwable t) { // catch and log the exception to not replace the original exception LOG.error("Error during cleanup of stream task", t); } // if the operators were not disposed before, do a hard dispose if (!disposed) { disposeAllOperators(); } // release the output resources. this method should never fail. if (operatorChain != null) { // beware: without synchronization, #performCheckpoint() may run in // parallel and this call is not thread-safe synchronized (lock) { operatorChain.releaseOutputs(); } } } } @Override public final void cancel() throws Exception { isRunning = false; canceled = true; // the "cancel task" call must come first, but the cancelables must be // closed no matter what try { cancelTask(); } finally { cancelables.close(); } } public final boolean isRunning() { return isRunning; } public final boolean isCanceled() { return canceled; } /** * Execute {@link StreamOperator#open()} of each operator in the chain of this * {@link StreamTask}. Opening happens from <b>tail to head</b> operator in the chain, contrary * to {@link StreamOperator#close()} which happens <b>head to tail</b> * (see {@link #closeAllOperators()}. */ private void openAllOperators() throws Exception { final Iterator<StreamOperator<?>> it = operatorChain.getAllOperatorsTopologySorted().descendingIterator(); while (it.hasNext()) { final StreamOperator<?> operator = it.next(); if (operator != null) { operator.open(); } } } /** * Execute {@link StreamOperator#close()} of each operator in the chain of this * {@link StreamTask}. Closing happens from <b>head to tail</b> operator in the chain, * contrary to {@link StreamOperator#open()} which happens <b>tail to head</b> * (see {@link #openAllOperators()}. */ private void closeAllOperators() throws Exception { // We need to close them first to last, since upstream operators in the chain might emit // elements in their close methods. for (StreamOperator<?> operator : operatorChain.getAllOperatorsTopologySorted()) { if (operator != null) { operator.close(); } } } /** * Execute {@link StreamOperator#dispose()} of each operator in the chain of this * {@link StreamTask}. Disposing happens from <b>tail to head</b> operator in the chain. */ private void tryDisposeAllOperators() throws Exception { final Iterator<StreamOperator<?>> it = operatorChain.getAllOperatorsTopologySorted().descendingIterator(); while (it.hasNext()) { final StreamOperator<?> operator = it.next(); if (operator != null) { operator.dispose(); } } } private void shutdownAsyncThreads() throws Exception { if (!asyncOperationsThreadPool.isShutdown()) { asyncOperationsThreadPool.shutdownNow(); } } /** * Execute @link StreamOperator#dispose()} of each operator in the chain of this * {@link StreamTask}. Disposing happens from <b>tail to head</b> operator in the chain. * * <p>The difference with the {@link #tryDisposeAllOperators()} is that in case of an * exception, this method catches it and logs the message. */ private void disposeAllOperators() { if (operatorChain != null) { final Iterator<StreamOperator<?>> it = operatorChain.getAllOperatorsTopologySorted().descendingIterator(); while (it.hasNext()) { final StreamOperator<?> operator = it.next(); try { if (operator != null) { operator.dispose(); } } catch (Throwable t) { LOG.error("Error during disposal of stream operator.", t); } } } } /** * The finalize method shuts down the timer. This is a fail-safe shutdown, in case the original * shutdown method was never called. * * <p>This should not be relied upon! It will cause shutdown to happen much later than if manual * shutdown is attempted, and cause threads to linger for longer than needed. */ @Override protected void finalize() throws Throwable { super.finalize(); if (timerService != null) { if (!timerService.isTerminated()) { LOG.info("Timer service is shutting down."); timerService.shutdownService(); } } cancelables.close(); } boolean isSerializingTimestamps() { TimeCharacteristic tc = streamTaskConfig.getTimeCharacteristic(); return tc == TimeCharacteristic.EventTime | tc == TimeCharacteristic.IngestionTime; } // ------------------------------------------------------------------------ // Access to properties and utilities // ------------------------------------------------------------------------ /** * Gets the name of the task, in the form "taskname (2/5)". * @return The name of the task. */ public String getName() { return getEnvironment().getTaskInfo().getTaskNameWithSubtasks(); } /** * Gets the lock object on which all operations that involve data and state mutation have to lock. * @return The checkpoint lock object. */ public Object getCheckpointLock() { return lock; } public CheckpointStorage getCheckpointStorage() { return checkpointStorage; } public StreamConfig getConfiguration() { return configuration; } public AccumulatorRegistry getAccumulatorRegistry() { return accumulatorRegistry; } public StreamTaskConfigSnapshot getStreamTaskConfig() { return streamTaskConfig; } public StreamStatusMaintainer getStreamStatusMaintainer() { return operatorChain; } RecordWriterOutput<?>[] getStreamOutputs() { return operatorChain.getStreamOutputs(); } // ------------------------------------------------------------------------ // Checkpoint and Restore // ------------------------------------------------------------------------ @Override public boolean triggerCheckpoint(CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) throws Exception { try { // No alignment if we inject a checkpoint CheckpointMetrics checkpointMetrics = new CheckpointMetrics() .setBytesBufferedInAlignment(0L) .setAlignmentDurationNanos(0L); return performCheckpoint(checkpointMetaData, checkpointOptions, checkpointMetrics); } catch (Exception e) { // propagate exceptions only if the task is still in "running" state if (isRunning) { throw new Exception("Could not perform checkpoint " + checkpointMetaData.getCheckpointId() + " for operator " + getName() + '.', e); } else { LOG.debug("Could not perform checkpoint {} for operator {} while the " + "invokable was not in state running.", checkpointMetaData.getCheckpointId(), getName(), e); return false; } } } @Override public void triggerCheckpointOnBarrier( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointMetrics checkpointMetrics) throws Exception { try { performCheckpoint(checkpointMetaData, checkpointOptions, checkpointMetrics); } catch (CancelTaskException e) { LOG.info("Operator {} was cancelled while performing checkpoint {}.", getName(), checkpointMetaData.getCheckpointId()); throw e; } catch (Exception e) { throw new Exception("Could not perform checkpoint " + checkpointMetaData.getCheckpointId() + " for operator " + getName() + '.', e); } } @Override public void abortCheckpointOnBarrier(long checkpointId, Throwable cause) throws Exception { LOG.debug("Aborting checkpoint via cancel-barrier {} for task {}", checkpointId, getName()); // notify the coordinator that we decline this checkpoint getEnvironment().declineCheckpoint(checkpointId, cause); // notify all downstream operators that they should not wait for a barrier from us synchronized (lock) { operatorChain.broadcastCheckpointCancelMarker(checkpointId); } } private boolean performCheckpoint( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointMetrics checkpointMetrics) throws Exception { LOG.debug("Starting checkpoint ({}) {} on task {}", checkpointMetaData.getCheckpointId(), checkpointOptions.getCheckpointType(), getName()); synchronized (lock) { if (isRunning) { // we can do a checkpoint // Prepare the checkpoint, allow operators to do some pre-barrier work. // The pre-barrier work should be nothing or minimal in the common case. operatorChain.prepareSnapshotPreBarrier(checkpointMetaData.getCheckpointId()); // Since both state checkpointing and downstream barrier emission occurs in this // lock scope, they are an atomic operation regardless of the order in which they occur. // Given this, we immediately emit the checkpoint barriers, so the downstream operators // can start their checkpoint work as soon as possible operatorChain.broadcastCheckpointBarrier( checkpointMetaData.getCheckpointId(), checkpointMetaData.getTimestamp(), checkpointOptions); checkpointState(checkpointMetaData, checkpointOptions, checkpointMetrics); return true; } else { // we cannot perform our checkpoint - let the downstream operators know that they // should not wait for any input from this operator // we cannot broadcast the cancellation markers on the 'operator chain', because it may not // yet be created final CancelCheckpointMarker message = new CancelCheckpointMarker(checkpointMetaData.getCheckpointId()); Exception exception = null; for (StreamRecordWriter<StreamRecord<?>> streamRecordWriter : streamRecordWriters) { try { streamRecordWriter.broadcastEvent(message); } catch (Exception e) { exception = ExceptionUtils.firstOrSuppressed( new Exception("Could not send cancel checkpoint marker to downstream tasks.", e), exception); } } if (exception != null) { throw exception; } return false; } } } public ExecutorService getAsyncOperationsThreadPool() { return asyncOperationsThreadPool; } @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { synchronized (lock) { if (isRunning) { LOG.debug("Notification of complete checkpoint for task {}", getName()); final Iterator<StreamOperator<?>> it = operatorChain.getAllOperatorsTopologySorted().descendingIterator(); while (it.hasNext()) { final StreamOperator<?> operator = it.next(); if (operator != null) { operator.notifyCheckpointComplete(checkpointId); } } } else { LOG.debug("Ignoring notification of complete checkpoint for not-running task {}", getName()); } } } private void tryShutdownTimerService() { if (timerService != null && !timerService.isTerminated()) { try { final long timeoutMs = getEnvironment().getTaskManagerInfo().getConfiguration(). getLong(TaskManagerOptions.TASK_CANCELLATION_TIMEOUT_TIMERS); if (!timerService.shutdownServiceUninterruptible(timeoutMs)) { LOG.warn("Timer service shutdown exceeded time limit of {} ms while waiting for pending " + "timers. Will continue with shutdown procedure.", timeoutMs); } } catch (Throwable t) { // catch and log the exception to not replace the original exception LOG.error("Could not shut down timer service", t); } } } private void checkpointState( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointMetrics checkpointMetrics) throws Exception { CheckpointStreamFactory storage = checkpointStorage.resolveCheckpointStorageLocation( checkpointMetaData.getCheckpointId(), checkpointOptions.getTargetLocation()); CheckpointingOperation checkpointingOperation = new CheckpointingOperation( this, checkpointMetaData, checkpointOptions, storage, checkpointMetrics); checkpointingOperation.executeCheckpointing(); } private void initializeState() throws Exception { final Iterator<StreamOperator<?>> it = operatorChain.getAllOperatorsTopologySorted().descendingIterator(); while (it.hasNext()) { final StreamOperator<?> operator = it.next(); if (null != operator) { operator.initializeState(); } } } // ------------------------------------------------------------------------ // State backend // ------------------------------------------------------------------------ private StateBackend createStateBackend() throws Exception { final StateBackend fromApplication = streamTaskConfig.getStateBackend(); return StateBackendLoader.fromApplicationOrConfigOrDefault( fromApplication, getEnvironment().getTaskManagerInfo().getConfiguration(), getUserCodeClassLoader(), LOG); } protected CheckpointExceptionHandlerFactory createCheckpointExceptionHandlerFactory() { return new CheckpointExceptionHandlerFactory(); } private String createOperatorIdentifier(StreamOperator<?> operator) { TaskInfo taskInfo = getEnvironment().getTaskInfo(); return new OperatorSubtaskDescriptionText( operator.getOperatorID(), operator.getClass().getSimpleName(), taskInfo.getIndexOfThisSubtask(), taskInfo.getNumberOfParallelSubtasks()).toString(); } /** * Returns the {@link ProcessingTimeService} responsible for telling the current * processing time and registering timers. */ public ProcessingTimeService getProcessingTimeService() { if (timerService == null) { throw new IllegalStateException("The timer service has not been initialized."); } return timerService; } /** * Handles an exception thrown by another thread (e.g. a TriggerTask), * other than the one executing the main task by failing the task entirely. * * <p>In more detail, it marks task execution failed for an external reason * (a reason other than the task code itself throwing an exception). If the task * is already in a terminal state (such as FINISHED, CANCELED, FAILED), or if the * task is already canceling this does nothing. Otherwise it sets the state to * FAILED, and, if the invokable code is running, starts an asynchronous thread * that aborts that code. * * <p>This method never blocks. */ @Override public void handleAsyncException(String message, Throwable exception) { if (isRunning) { // only fail if the task is still running getEnvironment().failExternally(exception); } } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ @Override public String toString() { return getName(); } // ------------------------------------------------------------------------ /** * This runnable executes the asynchronous parts of all involved backend snapshots for the subtask. */ @VisibleForTesting protected static final class AsyncCheckpointRunnable implements Runnable, Closeable { private final StreamTask<?, ?> owner; private final Map<OperatorID, OperatorSnapshotFutures> operatorSnapshotsInProgress; private final CheckpointMetaData checkpointMetaData; private final CheckpointMetrics checkpointMetrics; private final long asyncStartNanos; private final AtomicReference<CheckpointingOperation.AsyncCheckpointState> asyncCheckpointState = new AtomicReference<>( CheckpointingOperation.AsyncCheckpointState.RUNNING); AsyncCheckpointRunnable( StreamTask<?, ?> owner, Map<OperatorID, OperatorSnapshotFutures> operatorSnapshotsInProgress, CheckpointMetaData checkpointMetaData, CheckpointMetrics checkpointMetrics, long asyncStartNanos) { this.owner = Preconditions.checkNotNull(owner); this.operatorSnapshotsInProgress = Preconditions.checkNotNull(operatorSnapshotsInProgress); this.checkpointMetaData = Preconditions.checkNotNull(checkpointMetaData); this.checkpointMetrics = Preconditions.checkNotNull(checkpointMetrics); this.asyncStartNanos = asyncStartNanos; } @Override public void run() { FileSystemSafetyNet.initializeSafetyNetForThread(); try { TaskStateSnapshot jobManagerTaskOperatorSubtaskStates = new TaskStateSnapshot(operatorSnapshotsInProgress.size()); TaskStateSnapshot localTaskOperatorSubtaskStates = new TaskStateSnapshot(operatorSnapshotsInProgress.size()); for (Map.Entry<OperatorID, OperatorSnapshotFutures> entry : operatorSnapshotsInProgress.entrySet()) { OperatorID operatorID = entry.getKey(); OperatorSnapshotFutures snapshotInProgress = entry.getValue(); // finalize the async part of all by executing all snapshot runnables OperatorSnapshotFinalizer finalizedSnapshots = new OperatorSnapshotFinalizer(snapshotInProgress); jobManagerTaskOperatorSubtaskStates.putSubtaskStateByOperatorID( operatorID, finalizedSnapshots.getJobManagerOwnedState()); localTaskOperatorSubtaskStates.putSubtaskStateByOperatorID( operatorID, finalizedSnapshots.getTaskLocalState()); } final long asyncEndNanos = System.nanoTime(); final long asyncDurationMillis = (asyncEndNanos - asyncStartNanos) / 1_000_000L; checkpointMetrics.setAsyncDurationMillis(asyncDurationMillis); if (asyncCheckpointState.compareAndSet(CheckpointingOperation.AsyncCheckpointState.RUNNING, CheckpointingOperation.AsyncCheckpointState.COMPLETED)) { reportCompletedSnapshotStates( jobManagerTaskOperatorSubtaskStates, localTaskOperatorSubtaskStates, asyncDurationMillis); } else { LOG.debug("{} - asynchronous part of checkpoint {} could not be completed because it was closed before.", owner.getName(), checkpointMetaData.getCheckpointId()); } } catch (Exception e) { handleExecutionException(e); } finally { owner.cancelables.unregisterCloseable(this); FileSystemSafetyNet.closeSafetyNetAndGuardedResourcesForThread(); } } private void reportCompletedSnapshotStates( TaskStateSnapshot acknowledgedTaskStateSnapshot, TaskStateSnapshot localTaskStateSnapshot, long asyncDurationMillis) { TaskStateManager taskStateManager = owner.getEnvironment().getTaskStateManager(); boolean hasAckState = acknowledgedTaskStateSnapshot.hasState(); boolean hasLocalState = localTaskStateSnapshot.hasState(); Preconditions.checkState(hasAckState || !hasLocalState, "Found cached state but no corresponding primary state is reported to the job " + "manager. This indicates a problem."); // we signal stateless tasks by reporting null, so that there are no attempts to assign empty state // to stateless tasks on restore. This enables simple job modifications that only concern // stateless without the need to assign them uids to match their (always empty) states. taskStateManager.reportTaskStateSnapshots( checkpointMetaData, checkpointMetrics, hasAckState ? acknowledgedTaskStateSnapshot : null, hasLocalState ? localTaskStateSnapshot : null); LOG.debug("{} - finished asynchronous part of checkpoint {}. Asynchronous duration: {} ms", owner.getName(), checkpointMetaData.getCheckpointId(), asyncDurationMillis); LOG.trace("{} - reported the following states in snapshot for checkpoint {}: {}.", owner.getName(), checkpointMetaData.getCheckpointId(), acknowledgedTaskStateSnapshot); } private void handleExecutionException(Exception e) { boolean didCleanup = false; CheckpointingOperation.AsyncCheckpointState currentState = asyncCheckpointState.get(); while (CheckpointingOperation.AsyncCheckpointState.DISCARDED != currentState) { if (asyncCheckpointState.compareAndSet( currentState, CheckpointingOperation.AsyncCheckpointState.DISCARDED)) { didCleanup = true; try { cleanup(); } catch (Exception cleanupException) { e.addSuppressed(cleanupException); } Exception checkpointException = new Exception( "Could not materialize checkpoint " + checkpointMetaData.getCheckpointId() + " for operator " + owner.getName() + '.', e); // We only report the exception for the original cause of fail and cleanup. // Otherwise this followup exception could race the original exception in failing the task. owner.asynchronousCheckpointExceptionHandler.tryHandleCheckpointException( checkpointMetaData, checkpointException); currentState = CheckpointingOperation.AsyncCheckpointState.DISCARDED; } else { currentState = asyncCheckpointState.get(); } } if (!didCleanup) { LOG.trace("Caught followup exception from a failed checkpoint thread. This can be ignored.", e); } } @Override public void close() { if (asyncCheckpointState.compareAndSet( CheckpointingOperation.AsyncCheckpointState.RUNNING, CheckpointingOperation.AsyncCheckpointState.DISCARDED)) { try { cleanup(); } catch (Exception cleanupException) { LOG.warn("Could not properly clean up the async checkpoint runnable.", cleanupException); } } else { logFailedCleanupAttempt(); } } private void cleanup() throws Exception { LOG.debug( "Cleanup AsyncCheckpointRunnable for checkpoint {} of {}.", checkpointMetaData.getCheckpointId(), owner.getName()); Exception exception = null; // clean up ongoing operator snapshot results and non partitioned state handles for (OperatorSnapshotFutures operatorSnapshotResult : operatorSnapshotsInProgress.values()) { if (operatorSnapshotResult != null) { try { operatorSnapshotResult.cancel(); } catch (Exception cancelException) { exception = ExceptionUtils.firstOrSuppressed(cancelException, exception); } } } if (null != exception) { throw exception; } } private void logFailedCleanupAttempt() { LOG.debug("{} - asynchronous checkpointing operation for checkpoint {} has " + "already been completed. Thus, the state handles are not cleaned up.", owner.getName(), checkpointMetaData.getCheckpointId()); } } public CloseableRegistry getCancelables() { return cancelables; } // ------------------------------------------------------------------------ private static final class CheckpointingOperation { private final StreamTask<?, ?> owner; private final CheckpointMetaData checkpointMetaData; private final CheckpointOptions checkpointOptions; private final CheckpointMetrics checkpointMetrics; private final CheckpointStreamFactory storageLocation; private final StreamOperator<?>[] allOperators; private long startSyncPartNano; private long startAsyncPartNano; // ------------------------ private final Map<OperatorID, OperatorSnapshotFutures> operatorSnapshotsInProgress; public CheckpointingOperation( StreamTask<?, ?> owner, CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointStreamFactory checkpointStorageLocation, CheckpointMetrics checkpointMetrics) { this.owner = Preconditions.checkNotNull(owner); this.checkpointMetaData = Preconditions.checkNotNull(checkpointMetaData); this.checkpointOptions = Preconditions.checkNotNull(checkpointOptions); this.checkpointMetrics = Preconditions.checkNotNull(checkpointMetrics); this.storageLocation = Preconditions.checkNotNull(checkpointStorageLocation); final List<StreamOperator<?>> operators = new ArrayList<>(owner.operatorChain.getAllOperatorsTopologySorted()); Collections.reverse(operators); this.allOperators = operators.toArray(new StreamOperator[0]); this.operatorSnapshotsInProgress = new HashMap<>(allOperators.length); } public void executeCheckpointing() throws Exception { startSyncPartNano = System.nanoTime(); try { for (StreamOperator<?> op : allOperators) { checkpointStreamOperator(op); } if (LOG.isDebugEnabled()) { LOG.debug("Finished synchronous checkpoints for checkpoint {} on task {}", checkpointMetaData.getCheckpointId(), owner.getName()); } startAsyncPartNano = System.nanoTime(); checkpointMetrics.setSyncDurationMillis((startAsyncPartNano - startSyncPartNano) / 1_000_000); // we are transferring ownership over snapshotInProgressList for cleanup to the thread, active on submit AsyncCheckpointRunnable asyncCheckpointRunnable = new AsyncCheckpointRunnable( owner, operatorSnapshotsInProgress, checkpointMetaData, checkpointMetrics, startAsyncPartNano); owner.cancelables.registerCloseable(asyncCheckpointRunnable); owner.asyncOperationsThreadPool.submit(asyncCheckpointRunnable); if (LOG.isDebugEnabled()) { LOG.debug("{} - finished synchronous part of checkpoint {}." + "Alignment duration: {} ms, snapshot duration {} ms", owner.getName(), checkpointMetaData.getCheckpointId(), checkpointMetrics.getAlignmentDurationNanos() / 1_000_000, checkpointMetrics.getSyncDurationMillis()); } } catch (Exception ex) { // Cleanup to release resources for (OperatorSnapshotFutures operatorSnapshotResult : operatorSnapshotsInProgress.values()) { if (null != operatorSnapshotResult) { try { operatorSnapshotResult.cancel(); } catch (Exception e) { LOG.warn("Could not properly cancel an operator snapshot result.", e); } } } if (LOG.isDebugEnabled()) { LOG.debug("{} - did NOT finish synchronous part of checkpoint {}." + "Alignment duration: {} ms, snapshot duration {} ms", owner.getName(), checkpointMetaData.getCheckpointId(), checkpointMetrics.getAlignmentDurationNanos() / 1_000_000, checkpointMetrics.getSyncDurationMillis()); } owner.synchronousCheckpointExceptionHandler.tryHandleCheckpointException(checkpointMetaData, ex); } } @SuppressWarnings("deprecation") private void checkpointStreamOperator(StreamOperator<?> op) throws Exception { if (null != op) { OperatorSnapshotFutures snapshotInProgress = op.snapshotState( checkpointMetaData.getCheckpointId(), checkpointMetaData.getTimestamp(), checkpointOptions, storageLocation); operatorSnapshotsInProgress.put(op.getOperatorID(), snapshotInProgress); } } private enum AsyncCheckpointState { RUNNING, DISCARDED, COMPLETED } } /** * Wrapper for synchronous {@link CheckpointExceptionHandler}. This implementation catches unhandled, rethrown * exceptions and reports them through {@link #handleAsyncException(String, Throwable)}. As this implementation * always handles the exception in some way, it never rethrows. */ static final class AsyncCheckpointExceptionHandler implements CheckpointExceptionHandler { /** Owning stream task to which we report async exceptions. */ final StreamTask<?, ?> owner; /** Synchronous exception handler to which we delegate. */ final CheckpointExceptionHandler synchronousCheckpointExceptionHandler; AsyncCheckpointExceptionHandler(StreamTask<?, ?> owner) { this.owner = Preconditions.checkNotNull(owner); this.synchronousCheckpointExceptionHandler = Preconditions.checkNotNull(owner.synchronousCheckpointExceptionHandler); } @Override public void tryHandleCheckpointException(CheckpointMetaData checkpointMetaData, Exception exception) { try { synchronousCheckpointExceptionHandler.tryHandleCheckpointException(checkpointMetaData, exception); } catch (Exception unhandled) { AsynchronousException asyncException = new AsynchronousException(unhandled); owner.handleAsyncException("Failure in asynchronous checkpoint materialization", asyncException); } } } @VisibleForTesting public static List<StreamRecordWriter<StreamRecord<?>>> createStreamRecordWriters( StreamTaskConfigSnapshot config, Environment environment) { List<StreamRecordWriter<StreamRecord<?>>> streamRecordWriters = new ArrayList<>(); List<StreamEdge> outEdges = config.getOutStreamEdgesOfChain(); Map<Integer, StreamConfig> chainedConfigs = config.getChainedNodeConfigs(); for (int i = 0; i < outEdges.size(); i++) { StreamEdge edge = outEdges.get(i); streamRecordWriters.add( createStreamRecordWriter( edge, i, environment, environment.getTaskInfo().getTaskName(), chainedConfigs.get(edge.getSourceId()).getBufferTimeout())); } return streamRecordWriters; } private static StreamRecordWriter<StreamRecord<?>> createStreamRecordWriter( StreamEdge edge, int outputIndex, Environment environment, String taskName, long bufferTimeout) { @SuppressWarnings("unchecked") StreamPartitioner<?> outputPartitioner = edge.getPartitioner(); LOG.debug("Using partitioner {} for output {} of task {}", outputPartitioner, outputIndex, taskName); ResultPartitionWriter bufferWriter = environment.getWriter(outputIndex); // we initialize the partitioner here with the number of key groups (aka max. parallelism) if (outputPartitioner instanceof ConfigurableStreamPartitioner) { int numKeyGroups = bufferWriter.getNumTargetKeyGroups(); if (0 < numKeyGroups) { ((ConfigurableStreamPartitioner) outputPartitioner).configure(numKeyGroups); } } StreamRecordWriter<StreamRecord<?>> output = new StreamRecordWriter(bufferWriter, outputPartitioner, bufferTimeout, taskName); output.setMetricGroup( environment.getMetricGroup().getIOMetricGroup(), environment.getExecutionConfig().isTracingMetricsEnabled(), environment.getExecutionConfig().getTracingMetricsInterval()); return output; } }
[ "yafei.wang@transwarp.io" ]
yafei.wang@transwarp.io
e64e0ac5118663eeeab9b7934edd0276ef6a3ce6
2c741bc8ebde05c9089e5ce4033eec9e3bc45a08
/src/main/java/org/apache/ibatis/type/MappedJdbcTypes.java
8ddcedf3eb5a1019c8e449e579cd2b925065b5e0
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
JohnZhongg/mybatis-3
76aa29b0cbf8002309785e09b126f4e704d7b33d
48a7593ed3764d3e1ff00997901c92afc99250de
refs/heads/master
2020-03-25T23:15:10.751766
2020-01-19T06:52:21
2020-01-19T06:52:21
144,267,511
1
0
null
2018-08-10T09:38:20
2018-08-10T09:38:20
null
UTF-8
Java
false
false
1,138
java
/** * Copyright 2009-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 * * 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.ibatis.type; import java.lang.annotation.*; /** * 匹配的 JDBC Type 类型的注解 * * @author Eduardo Macarron */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) // 注册到类 public @interface MappedJdbcTypes { /** * @return 匹配的 JDBC Type 类型的注解 */ JdbcType[] value(); /** * @return 是否包含 {@link java.sql.JDBCType#NULL} */ boolean includeNullJdbcType() default false; }
[ "707845008@qq.com" ]
707845008@qq.com
33296c72344675a6c0088ddead53048a3f736844
f504c056b19a9f026526381795d8cbda1ba97ea5
/Project1/ImageRecognition/src/main/java/com/cclearning/imgclass/data/Sqs.java
f68872ea22f3e321ba2b1235800045c115ef8211
[]
no_license
chenyangcn15/AWS
df5219c7b659c18db73d37ca396634ba8b0fd8d1
0961e818420a2deb35137abf21c3f8b9aae41ce7
refs/heads/master
2022-07-02T20:58:22.689311
2020-03-07T09:12:22
2020-03-07T09:12:22
245,601,108
0
0
null
2020-10-13T20:09:00
2020-03-07T09:10:08
Java
UTF-8
Java
false
false
4,860
java
package com.cclearning.imgclass.data; import java.util.List; import java.util.Map; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityRequest; import com.amazonaws.services.sqs.model.CreateQueueResult; import com.amazonaws.services.sqs.model.DeleteQueueRequest; import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; import com.cclearning.imgclass.Config; import com.cclearning.imgclass.utils.Utils; public class Sqs { private final String mQueueName; private AmazonSQS mAmazonSQS; private Message currentMsg; public Sqs(String name) { this.mQueueName = name; this.currentMsg = null; create(); setup(); } private AmazonSQS createAmazonSQS() { if(mAmazonSQS == null) { mAmazonSQS = AmazonSQSClientBuilder.standard().withRegion(Config.REGIONS).build(); } return mAmazonSQS; } private void create() { final AmazonSQS sqs = createAmazonSQS(); CreateQueueResult result = sqs.createQueue(mQueueName); log("create a queue, result: " + result.toString()); } private void setup() { final AmazonSQS sqs = createAmazonSQS(); String queueUrl = sqs.getQueueUrl(mQueueName).getQueueUrl(); SetQueueAttributesRequest request = new SetQueueAttributesRequest(); request.setQueueUrl(queueUrl); // Set the message visibility timeout to 15s. request.addAttributesEntry("VisibilityTimeout", "15"); sqs.setQueueAttributes(request); } public void destory() { final AmazonSQS sqs = createAmazonSQS(); String queueUrl = sqs.getQueueUrl(mQueueName).getQueueUrl(); DeleteQueueRequest request = new DeleteQueueRequest(queueUrl); sqs.deleteQueue(request); log("Delete the queue: " + mQueueName); } public void sendMsg(String msg) { final AmazonSQS sqs = createAmazonSQS(); String queueUrl = sqs.getQueueUrl(mQueueName).getQueueUrl(); SendMessageRequest send_msg_request = new SendMessageRequest() .withQueueUrl(queueUrl) .withMessageBody(msg) .withDelaySeconds(0); sqs.sendMessage(send_msg_request); log("sent a message."); } /** * Receive one message each time * @return */ public String receiveMsg() { final AmazonSQS sqs = createAmazonSQS(); String queueUrl = sqs.getQueueUrl(mQueueName).getQueueUrl(); // for more configuration ReceiveMessageRequest request = new ReceiveMessageRequest(); request.setMaxNumberOfMessages(1); request.setQueueUrl(queueUrl); List<Message> messages = sqs.receiveMessage(request).getMessages(); if(messages.size() > 0) { Message msg = messages.get(0); currentMsg = msg; return msg.getBody(); } return null; } public String receiveMsg(int visibilityTimeout) { final AmazonSQS sqs = createAmazonSQS(); String queueUrl = sqs.getQueueUrl(mQueueName).getQueueUrl(); // for more configuration ReceiveMessageRequest request = new ReceiveMessageRequest(); request.setMaxNumberOfMessages(1); request.setQueueUrl(queueUrl); List<Message> messages = sqs.receiveMessage(request).getMessages(); if(messages.size() > 0) { Message msg = messages.get(0); currentMsg = msg; if(visibilityTimeout > 0) { // change visibility timeout ChangeMessageVisibilityRequest cmvr = new ChangeMessageVisibilityRequest(queueUrl, msg.getReceiptHandle(), visibilityTimeout); sqs.changeMessageVisibility(cmvr); } return msg.getBody(); } return null; } public boolean deleteMsg() { final AmazonSQS sqs = createAmazonSQS(); String queueUrl = sqs.getQueueUrl(mQueueName).getQueueUrl(); if (currentMsg != null) { sqs.deleteMessage(queueUrl, currentMsg.getReceiptHandle()); currentMsg = null; return true; }else { return false; } } public int getQueueLength() { final AmazonSQS sqs = createAmazonSQS(); String queueUrl = sqs.getQueueUrl(mQueueName).getQueueUrl(); GetQueueAttributesRequest sqsr = new GetQueueAttributesRequest(queueUrl).withAttributeNames("ApproximateNumberOfMessages", "ApproximateNumberOfMessagesNotVisible"); Map<String, String> results = sqs.getQueueAttributes(sqsr).getAttributes(); String visibleMsgCount = results.get("ApproximateNumberOfMessages"); String invisibleMsgCount = results.get("ApproximateNumberOfMessagesNotVisible"); int count = 1; try { count = Integer.parseInt(visibleMsgCount) + Integer.parseInt(invisibleMsgCount); }catch(Exception e) { e.printStackTrace(); } if(Config.DEBUG) { Utils.log("The sqs length: " + count); } return count; } private void log(String msg) { Utils.log(msg); } }
[ "noreply@github.com" ]
chenyangcn15.noreply@github.com
287fa62595fd51b673beaebf614decfcb4647f8a
4c10fe6b48920d25de6d28926c076347329486a1
/main.java
00a2d7632fc23a6a46441bb2dfdace5d4cd61ef4
[ "Apache-2.0" ]
permissive
DrSultanQasem/ELM-JAVA
627f6fa893b0fd53b2c2cef80847b347ed52d30a
c663752b8ee080baeddb1d703cdfa8faeca43c09
refs/heads/master
2020-04-02T06:51:44.143219
2015-05-25T14:50:43
2015-05-25T14:50:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
809
java
import no.uib.cipr.matrix.NotConvergedException; public class main { /** * @param args * @throws NotConvergedException */ public static void main(String[] args) throws NotConvergedException { // TODO Auto-generated method stub elm ds = new elm(0, 20, "sig"); ds.train("sinc_train"); ds.test("sinc_test"); /*elm ds = new elm(1, 20, "sig"); ds.train("diabetes_train"); ds.test("diabetes_test"); */ /* elm ds = new elm(1, 20, "sig"); ds.train("segment_train"); ds.test("segment_test"); */ System.out.println("TrainingTime:"+ds.getTrainingTime()); System.out.println("TrainingAcc:"+ds.getTrainingAccuracy()); System.out.println("TestingTime:"+ds.getTestingTime()); System.out.println("TestAcc:"+ds.getTestingAccuracy()); } }
[ "lmj@lmjdeMacBook-Air.local" ]
lmj@lmjdeMacBook-Air.local
f4422e65bdfe27a5a78ad60748ccaf2e3700f775
0a6b259d062d6c570305e3cf2fc3a7ccd94b8660
/strStr/Solution.java
77ed8c88109eaa912570f0bc178bed2cd0db3e0e
[]
no_license
Viggiecc/Algorithm
399efe8540a088624a009843f52c21d83894e152
dcf12dee3f99848bef0f7bf400e24969f44354e9
refs/heads/master
2021-01-11T04:54:51.538692
2018-08-24T05:42:03
2018-08-24T05:42:03
71,432,934
0
0
null
null
null
null
UTF-8
Java
false
false
941
java
import java.lang.*; import java.io.*; import java.util.*; public class Solution { public static int strStr (String source, String target) { int sourceLen = source.length(); int targetLen = target.length(); if(source == null || target == null || targetLen > sourceLen) { return -1; } int i; int j; for (i = 0; i < sourceLen - targetLen +1; i++) { for (j = 0; j < targetLen; j++) { if (source.charAt(i + j) != target.charAt(j)) { break; } } if (j == targetLen) return i; } return -1; } public static void main (String[] args) { Scanner input = new Scanner(System.in); System.out.println("String source: "); String source = input.nextLine(); System.out.println("String target: "); String target = input.nextLine(); // Solution solution = new Solution(); // System.out.println(solution.strStr(source, target)); System.out.println("The index is: " + strStr(source, target)); } }
[ "wezhang@shutterfly.com" ]
wezhang@shutterfly.com
4edcefc3ab77b636b9baea0310bbc35d7d131c31
7cd06f53f014edb2b73bf1e9c0d82b72c6b632ff
/ThucTap/app/src/main/java/com/uiapp/thuctap/mvp/main/garden/garden/injection/GardenModule.java
0a3c97472a773c9caf418b4aaee8b58b4162effb
[]
no_license
nhungnguyen123/ThucTapAndroid
cda2f0a67da238cd8c1fba61f6fc4f0ed0014ba8
e0169c899cecb4d2aa4279f9d0572abc301564ea
refs/heads/master
2021-01-13T03:33:49.442398
2016-12-25T06:19:03
2016-12-25T06:19:03
77,313,373
0
1
null
null
null
null
UTF-8
Java
false
false
823
java
package com.uiapp.thuctap.mvp.main.garden.garden.injection; import com.uiapp.thuctap.injection.PerFragment; import com.uiapp.thuctap.interactor.api.ApiManager; import com.uiapp.thuctap.interactor.prefer.PreferManager; import com.uiapp.thuctap.mvp.main.garden.garden.presenter.GardenPresenter; import com.uiapp.thuctap.mvp.main.garden.garden.view.IGardenView; import dagger.Module; import dagger.Provides; /** * Created by hongnhung on 7/24/16. */ @PerFragment @Module public class GardenModule { private IGardenView iGardenView; public GardenModule(IGardenView iGardenView) { this.iGardenView = iGardenView; } @Provides GardenPresenter provideGardenPresenter(ApiManager apiManager, PreferManager preferManager) { return new GardenPresenter(apiManager, preferManager); } }
[ "nhungnth19951903@gmail.com" ]
nhungnth19951903@gmail.com
19c89e1a56ec871d5adda9df36742cd489763872
98552b649ba259feab203c19bca48b348c9a629d
/src/main/java/com/xiu/fastTech/volatiletest/VolatileTest.java
8b4e8b2bbcce8710868e839fa155449791416666
[]
no_license
williamzhang11/fastTech
fea4b67d1672cf01c5cd3f3d51fa415638fc9ebf
2f95e808636d25191ba1b8811e14b3707794666e
refs/heads/master
2021-06-30T03:53:13.210326
2019-12-14T07:30:21
2019-12-14T07:30:21
171,101,194
1
0
null
2020-10-13T12:01:40
2019-02-17T08:58:46
Java
UTF-8
Java
false
false
555
java
package com.xiu.fastTech.volatiletest; public class VolatileTest { private static int count=0; public static void main(String[] args) { for(int i =0;i<100;i++) { new Thread(new VolatileThread()).start(); } } static class VolatileThread implements Runnable{ public VolatileThread() { } public void run() { for(int i =0;i<1000;i++) { synchronized (VolatileThread.class) { System.out.println(Thread.currentThread().getName()+"=" + (++count)); } } } } }
[ "1107517306@qq.com" ]
1107517306@qq.com
d277f80ab836a24171b4b5b2f925bdb70c30fbcb
ccf17b57f1f0b6ae48ed3475d3399c6180c11433
/src/main/java/com/base/modules/demo/web/TBzExpertExcelDemoController.java
b879fea602de99387fe5ece247fcb753b97a0a7c
[]
no_license
wangjiangqz/myProject
6adf47629bbe6ea16543f34b5e45b6098a044d22
b9d8587975e6bacfba4df1e81f0e2ddd1d7bd243
refs/heads/master
2022-12-22T05:20:07.339302
2019-10-26T12:04:20
2019-10-26T12:04:20
177,296,049
0
0
null
2022-12-16T02:08:35
2019-03-23T14:03:40
JavaScript
UTF-8
Java
false
false
6,335
java
/** * Copyright &copy; 2019-2019 <a href="#">版权</a> All rights reserved. */ package com.base.modules.demo.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.base.common.config.Global; import com.base.common.persistence.Page; import com.base.common.utils.StringUtils; import com.base.common.web.BaseController; import com.base.modules.demo.entity.TBzExpertExcelDemo; import com.base.modules.demo.service.TBzExpertExcelDemoService; /** * Excel演示Controller * @author handf * @version 2016-08-26 */ @Controller @RequestMapping(value = "${adminPath}/demo/tBzExpertExcelDemo") public class TBzExpertExcelDemoController extends BaseController { @Autowired private TBzExpertExcelDemoService tBzExpertExcelDemoService; @ModelAttribute public TBzExpertExcelDemo get(@RequestParam(required=false) String id) { TBzExpertExcelDemo entity = null; if (StringUtils.isNotBlank(id)){ entity = tBzExpertExcelDemoService.get(id); } if (entity == null){ entity = new TBzExpertExcelDemo(); } return entity; } @RequestMapping(value = {"list", ""}) public String list(TBzExpertExcelDemo tBzExpertExcelDemo, HttpServletRequest request, HttpServletResponse response, Model model) { Page<TBzExpertExcelDemo> page = tBzExpertExcelDemoService.findPage(new Page<TBzExpertExcelDemo>(request, response), tBzExpertExcelDemo); model.addAttribute("page", page); return "modules/demo/tBzExpertExcelDemoList"; } @RequestMapping(value = "form") public String form(TBzExpertExcelDemo tBzExpertExcelDemo, Model model) { model.addAttribute("tBzExpertExcelDemo", tBzExpertExcelDemo); return "modules/demo/tBzExpertExcelDemoForm"; } @RequestMapping(value = "save") public String save(TBzExpertExcelDemo tBzExpertExcelDemo, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, tBzExpertExcelDemo)){ return form(tBzExpertExcelDemo, model); } tBzExpertExcelDemoService.save(tBzExpertExcelDemo); addMessage(redirectAttributes, "保存Excel演示成功"); return "redirect:"+Global.getAdminPath()+"/demo/tBzExpertExcelDemo/?repage"; } @RequestMapping(value = "delete") public String delete(TBzExpertExcelDemo tBzExpertExcelDemo, RedirectAttributes redirectAttributes) { tBzExpertExcelDemoService.delete(tBzExpertExcelDemo); addMessage(redirectAttributes, "删除Excel演示成功"); return "redirect:"+Global.getAdminPath()+"/demo/tBzExpertExcelDemo/?repage"; } /** * excel保存导入 * @param tBzExpertExcelDemo * @param request * @param multipartHttpServletRequest * @return */ @RequestMapping(value = "excelSave", method = RequestMethod.POST) @ResponseBody public JSONObject excelSave(TBzExpertExcelDemo tBzExpertExcelDemo, HttpServletRequest request, MultipartHttpServletRequest multipartHttpServletRequest) { MultipartFile multipartFile = multipartHttpServletRequest.getFile("fileUpload");// 获得上传的附件 JSONObject json = tBzExpertExcelDemoService.excelSave(multipartFile, request); return json; } /** * 导出模拟信息表 * @param tBzExpertExcelDemo * @param request * @param response * @param model */ @RequestMapping(value = "exportExcel") public void exportExcel(TBzExpertExcelDemo tBzExpertExcelDemo, HttpServletRequest request, HttpServletResponse response, Model model){ List<TBzExpertExcelDemo> tBzExpertExcelDemos = tBzExpertExcelDemoService.findList(tBzExpertExcelDemo); String fileName = "导出模拟信息表.xls"; try{ HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("导出模拟信息表"); HSSFRow row = sheet.createRow((int) 0); HSSFCellStyle style = wb.createCellStyle(); // 设置表头样式 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中 String[] excelHeader = { "序号", "列一", "列二", "列三"}; // excel表头 for (int i = 0; i < excelHeader.length; i++){ HSSFCell cell = row.createCell(i); cell.setCellValue(excelHeader[i]); cell.setCellStyle(style); sheet.setColumnWidth(i, 4000); } if(tBzExpertExcelDemos != null && tBzExpertExcelDemos.size() > 0){ for (int i = 0; i < tBzExpertExcelDemos.size(); i++){ TBzExpertExcelDemo expertExcelDemo = tBzExpertExcelDemos.get(i); row = sheet.createRow(i + 1); row.createCell(0).setCellValue(i + 1); row.createCell(1).setCellValue(expertExcelDemo.getColumnOne()); row.createCell(2).setCellValue(expertExcelDemo.getColumnTwo()); row.createCell(3).setCellValue(expertExcelDemo.getColumnThree()); } } response.reset(); response.setContentType("application/octet-stream; charset=utf-8"); fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); wb.write(response.getOutputStream()); }catch (Exception e){ e.printStackTrace(); } } }
[ "544979753@qq.com" ]
544979753@qq.com
bb861cb24bd47ce3b91cf64e11f2d6e1fbd978af
664fa5517e312c6711925ad8c43bf7916ef3b08c
/src/main/java/com/ugfind/serviceImpl/RecruitinfoServiceImpl.java
232176d0faf5f7267c3460983ffb710b3d70492f
[]
no_license
mao377542770/o2o
f5673994bae6f5c5dd75e59159c5d3cf9f8f77b3
cdcfddf153e55a9a9a7719d82de0f448451d2b63
refs/heads/master
2021-01-11T10:57:19.701183
2017-02-17T12:07:27
2017-02-17T12:07:27
72,843,897
0
0
null
null
null
null
UTF-8
Java
false
false
1,461
java
package com.ugfind.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ugfind.dao.RecruitinfoMapper; import com.ugfind.model.NewsPageConfig; import com.ugfind.model.Recruitinfo; import com.ugfind.service.RecruitinfoService; @Service public class RecruitinfoServiceImpl implements RecruitinfoService { @Autowired private RecruitinfoMapper recruitInfoDao; @Override public int deleteByPrimaryKey(Integer id) { return recruitInfoDao.deleteByPrimaryKey(id); } @Override public int insertSelective(Recruitinfo record) { return recruitInfoDao.insertSelective(record); } @Override public Recruitinfo selectByPrimaryKey(Integer id) { return recruitInfoDao.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(Recruitinfo record) { return recruitInfoDao.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(Recruitinfo record) { // TODO Auto-generated method stub return 0; } @Override public int getRecruitInfoCount(NewsPageConfig newsPage) { return recruitInfoDao.getRecruitInfoCount(newsPage); } @Override public List<Recruitinfo> getRecruitInfoBypage(NewsPageConfig newsPage) { return recruitInfoDao.getRecruitInfoBypage(newsPage); } @Override public int updateRecruitInfoViewCount(Integer id) { return recruitInfoDao.updateRecruitInfoViewCount(id); } }
[ "377542770@qq.com" ]
377542770@qq.com
46b1060ff388daced4cc50f8ecc7a9361aceef3d
8bb9cd855366217336d399fdb945c0835d80a2ee
/searchview/src/main/java/com/jerey/searchview/SearchViewUtils.java
a367e2e8a084efab96b1c1b0c90aa86d904b0c08
[ "Apache-2.0" ]
permissive
deviche/KeepGank
dd03b20dffa705b3d085d0b13d1a972241a38c03
776b35819f1e713514420d0ba0f5efedd95a2025
refs/heads/master
2020-03-27T08:34:33.013281
2018-03-25T06:30:58
2018-03-25T06:30:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,708
java
package com.jerey.searchview; import android.animation.Animator; import android.content.Context; import android.os.Build; import android.support.v7.widget.CardView; import android.view.View; import android.view.ViewAnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; public class SearchViewUtils { public static int dip2px(Context context, float dp) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dp * scale + 0.5); } public static void autoOpenOrClose(final Context context, final CardView search, final EditText editText) { //隐藏 if (search.getVisibility() == View.VISIBLE) { close(context, search, editText); } else { open(context, search, editText); } } public static void open(final Context context, final CardView search, final EditText editText) { if (search.getVisibility() == View.INVISIBLE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { final Animator animator = ViewAnimationUtils.createCircularReveal(search, search.getWidth() - dip2px(context, 23), dip2px(context, 23), 0, (float) Math.hypot(search.getWidth(), search.getHeight())); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { ((InputMethodManager) context.getSystemService(Context .INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager .SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); KeyboardUtils.showSoftInput(editText, context); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); search.setVisibility(View.VISIBLE); if (search.getVisibility() == View.VISIBLE) { animator.setDuration(300); animator.start(); search.setEnabled(true); } } else { search.setVisibility(View.VISIBLE); search.setEnabled(true); KeyboardUtils.showSoftInput(editText, context); } } public static void close(final Context context, final CardView search, final EditText editText) { if (search.getVisibility() == View.VISIBLE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { final Animator animatorHide = ViewAnimationUtils.createCircularReveal(search, search.getWidth() - dip2px(context, 23), dip2px(context, 23), //确定元的半径(算长宽的斜边长,这样半径不会太短也不会很长效果比较舒服) (float) Math.hypot(search.getWidth(), search.getHeight()), 0); animatorHide.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { search.setVisibility(View.INVISIBLE); ((InputMethodManager) context.getSystemService(Context .INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(search .getWindowToken(), 0); KeyboardUtils.hideSoftInput(editText, context); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); animatorHide.setDuration(300); animatorHide.start(); } else { search.setVisibility(View.INVISIBLE); KeyboardUtils.hideSoftInput(editText, context); } editText.setText(""); search.setEnabled(false); } }
[ "610315802@qq.com" ]
610315802@qq.com
10917443c5f994ab4246ea0bb039f65c74345dae
0bf70b85b5a3f0fb51c6c3c45c2d8a7c4fa79a87
/net.solarnetwork.node/src/net/solarnetwork/node/runtime/JobServiceRegistrationListener.java
cfa842a91963717fab94fe899416bf9207f2ac9a
[]
no_license
Spudmn/solarnetwork-node
7a1839b41a1cd2d4e996caa8cb1d82baac3fcfeb
8701e756d91a92f76234c4b7a6e026528625b148
refs/heads/master
2021-01-15T11:03:11.181320
2014-11-06T20:21:13
2014-11-06T20:21:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,712
java
/* =================================================================== * JobServiceRegistrationListener.java * * Created Dec 2, 2009 10:29:15 AM * * Copyright 2007-2009 SolarNetwork.net Dev Team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * =================================================================== * $Id$ * =================================================================== */ package net.solarnetwork.node.runtime; import java.io.IOException; import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.TreeMap; import net.solarnetwork.node.job.TriggerAndJobDetail; import net.solarnetwork.node.settings.SettingSpecifierProvider; import net.solarnetwork.node.util.BaseServiceListener; import net.solarnetwork.node.util.RegisteredService; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ConfigurationEvent; import org.osgi.service.cm.ConfigurationListener; import org.quartz.CronTrigger; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; /** * An OSGi service registration listener for jobs, so they can be automatically * registered/unregistered with the job scheduler. * * <p> * This class is designed to be registered as a listener for * {@link TriggerAndJobDetail} beans registered as services. As * {@link TriggerAndJobDetail} services are discovered, they will be scheduled * to run in the configured {@link Scheduler}. As those services are removed, * they will be un-scheduled. In this way bundles can export jobs to be run by * the "core" {@code Scheduler} provided by this bundle. * </p> * * <p> * This class will also register {@link JobSettingSpecifierProvider} for every * unique bundle symbolic name. This allows the settings UI to expose the * registered jobs as configurable components. * </p> * * <p> * For example, this might be configured via OSGi Blueprint like this: * </p> * * <pre> * &lt;reference-list id="triggers" interface="net.solarnetwork.node.job.TriggerAndJobDetail"> * &lt;reference-listener bind-method="onBind" unbind-method="onUnbind"> * &lt;bean class="net.solarnetwork.node.runtime.JobServiceRegistrationListener"> * &lt;property name="scheduler" ref="scheduler"/> * &lt;property name="bundleContext" ref="bundleContext"/> * &lt;/bean> * &lt;/reference-listener> * &lt;/reference-list> * </pre> * * <p> * The configurable properties of this class are: * </p> * * <dl class="class-properties"> * <dt>scheduler</dt> * <dd>The Quartz {@link Scheduler} for scheduling and un-scheduling jobs with * as {@link TriggerAndJobDetail} services are registered and un-registered.</dd> * </dl> * * @author matt * @version 1.1 * @see ManagedJobServiceRegistrationListener for alternative using * settings-based jobs */ public class JobServiceRegistrationListener extends BaseServiceListener<TriggerAndJobDetail, RegisteredService<TriggerAndJobDetail>> implements ConfigurationListener { private Scheduler scheduler; private ServiceRegistration<ConfigurationListener> configurationListenerRef; private final Map<String, JobSettingSpecifierProvider> providerMap = new TreeMap<String, JobSettingSpecifierProvider>(); private String pidForSymbolicName(String name) { return name + ".JOBS"; } /** * Callback when a trigger has been registered. * * @param trigJob * the trigger and job * @param properties * the service properties */ public void onBind(TriggerAndJobDetail trigJob, Map<String, ?> properties) { if ( log.isDebugEnabled() ) { log.debug("Bind called on [" + trigJob + "] with props " + properties); } JobDetail job = trigJob.getJobDetail(); Trigger trigger = trigJob.getTrigger(); final String pid = pidForSymbolicName((String) properties.get("Bundle-SymbolicName")); String cronExpression = null; String settingKey = null; JobSettingSpecifierProvider provider = null; synchronized ( providerMap ) { if ( pid != null ) { provider = providerMap.get(pid); if ( provider == null ) { provider = new JobSettingSpecifierProvider(pid, trigJob.getMessageSource()); providerMap.put(pid, provider); } if ( configurationListenerRef == null ) { configurationListenerRef = getBundleContext().registerService( ConfigurationListener.class, this, null); } // check for ConfigurationAdmin cron setting for this trigger, // and // use that if available settingKey = JobUtils.triggerKey(trigger); if ( trigger instanceof CronTrigger ) { cronExpression = ((CronTrigger) trigger).getCronExpression(); ConfigurationAdmin ca = (ConfigurationAdmin) getBundleContext().getService( getBundleContext().getServiceReference(ConfigurationAdmin.class.getName())); if ( ca != null ) { try { Configuration conf = ca.getConfiguration(pid, null); if ( conf != null ) { @SuppressWarnings("unchecked") Dictionary<String, ?> props = conf.getProperties(); if ( props != null ) { String newCronExpression = (String) props.get(settingKey); if ( newCronExpression != null ) { cronExpression = newCronExpression; } } } } catch ( IOException e ) { log.warn("Unable to get configuration for {}", pid, e); } } } } } try { if ( cronExpression != null && settingKey != null ) { JobUtils.scheduleCronJob(scheduler, (CronTrigger) trigJob.getTrigger(), trigJob.getJobDetail(), cronExpression, null); if ( provider != null ) { provider.addSpecifier(trigJob); RegisteredService<TriggerAndJobDetail> rs = new RegisteredService<TriggerAndJobDetail>( trigJob, properties); Hashtable<String, Object> serviceProps = new Hashtable<String, Object>(); serviceProps.put("settingPid", provider.getSettingUID()); addRegisteredService(rs, provider, new String[] { SettingSpecifierProvider.class.getName() }, serviceProps); } } else { scheduler.scheduleJob(job, trigger); } } catch ( SchedulerException e ) { log.error("Error scheduling trigger {} for job {}", new Object[] { trigger.getName(), trigger.getJobName(), e }); } } /** * Callback when a trigger has been un-registered. * * @param trigJob * the trigger and job * @param properties * the service properties */ public void onUnbind(TriggerAndJobDetail trigJob, Map<String, ?> properties) { if ( trigJob == null ) { // gemini blueprint calls this when availability="optional" and there are no services return; } try { scheduler.deleteJob(trigJob.getJobDetail().getName(), trigJob.getJobDetail().getGroup()); } catch ( SchedulerException e ) { log.error("Unable to un-schedule job " + trigJob); throw new RuntimeException(e); } removeRegisteredService(trigJob, properties); final String pid = pidForSymbolicName((String) properties.get("Bundle-SymbolicName")); JobSettingSpecifierProvider provider = null; synchronized ( providerMap ) { provider = providerMap.get(pid); if ( provider != null ) { provider.removeSpecifier(trigJob); } } } @Override public void configurationEvent(ConfigurationEvent event) { if ( event.getType() == ConfigurationEvent.CM_UPDATED ) { JobSettingSpecifierProvider provider = null; synchronized ( providerMap ) { provider = providerMap.get(event.getPid()); } if ( provider != null ) { @SuppressWarnings("unchecked") ServiceReference<ConfigurationAdmin> caRef = event.getReference(); ConfigurationAdmin ca = getBundleContext().getService(caRef); try { Configuration config = ca.getConfiguration(event.getPid(), null); @SuppressWarnings("unchecked") Dictionary<String, ?> props = config.getProperties(); log.debug("CA PID {} updated props: {}", event.getPid(), props); Enumeration<String> keys = props.keys(); while ( keys.hasMoreElements() ) { String key = keys.nextElement(); List<RegisteredService<TriggerAndJobDetail>> tjList = getRegisteredServices(); synchronized ( tjList ) { for ( RegisteredService<TriggerAndJobDetail> rs : tjList ) { TriggerAndJobDetail tj = rs.getConfig(); if ( key.equals(JobUtils.triggerKey(tj.getTrigger())) ) { JobUtils.scheduleCronJob(scheduler, (CronTrigger) tj.getTrigger(), tj.getJobDetail(), (String) props.get(key), null); } } } } } catch ( IOException e ) { log.warn("Exception processing configuration update event", e); } } } } public Scheduler getScheduler() { return scheduler; } public void setScheduler(Scheduler scheduler) { this.scheduler = scheduler; } }
[ "git+matt@msqr.us" ]
git+matt@msqr.us
bfc8aaca8a34393e7d02fce1ef8c958d3de04350
a6891be0bbf8f1843b919873f446a290fc53fdb5
/src/IntelM2M/algo/NewKmCluster.java
1f82ba6a48ee759b3f8ba3d81ed0a2af197f8d38
[]
no_license
lynnRobotics/Engine_demo
cd342266369eb834ec684961c0e7b542fd50558f
6c81a1254dab45390cc62dceb2b4e1d6eb00a2db
refs/heads/master
2016-09-06T10:40:33.934112
2015-05-05T14:06:54
2015-05-05T14:10:39
29,174,739
0
0
null
null
null
null
BIG5
Java
false
false
2,844
java
package IntelM2M.algo; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import weka.clusterers.SimpleKMeans; import weka.core.Instances; import weka.filters.Filter; import weka.filters.unsupervised.attribute.AddCluster; import IntelM2M.datastructure.EnvStructure; import IntelM2M.datastructure.RelationTable; /*Mao Yuan Weng 2012/01*/ public class NewKmCluster { public Map<String, ArrayList<clusterNode>> clusterArray = new LinkedHashMap<String, ArrayList<clusterNode>>();; // cluster result class clusterNode { clusterNode() { centroid = new ArrayList<String>(); clusterMember = new ArrayList<String>(); } ArrayList<String> centroid; ArrayList<String> clusterMember; double diff; } public ArrayList<clusterNode> runClustering(int clusterNumber) { //PrintFunction out=new PrintFunction(); try { File f = new File("./_weka_training_data/cluster.arff"); Instances train = new Instances(new BufferedReader(new FileReader(f))); AddCluster ac = new AddCluster(); SimpleKMeans skm = new SimpleKMeans(); skm.setNumClusters(clusterNumber); // 設定用 K-Means 要分成 n 群 ac.setClusterer(skm); ac.setInputFormat(train); // 指定輸入資料 Instances CI = Filter.useFilter(train, ac); // 執行分群演算法 Instances clusterCenter = skm.getClusterCentroids(); ArrayList<clusterNode> arr = new ArrayList<clusterNode>(); for(int i = 0; i < clusterCenter.numInstances(); i++) //no. of centers { clusterNode cNode = new clusterNode(); arr.add(cNode); int len = clusterCenter.instance(i).numAttributes(); /*number of attribute(dimension+ans)*/ /*record centroid for cluster i*/ for(int j = 0; j < len-1; j++) //len-1: the class { String tmp=clusterCenter.instance(i).toString(j); arr.get(i).centroid.add(tmp); } } /*record member for cluster i*/ for(int i=0; i<CI.numInstances(); i++) { int index = (int)CI.instance(i).value(CI.instance(i).numAttributes()-1); String actName= CI.instance(i).toString( (CI.instance(i).attribute(CI.instance(i).numAttributes()-2))); arr.get(index).clusterMember.add(actName); } return arr; } catch(Exception e) {e.printStackTrace();} return null; } }
[ "lynn.robotics@gmail.com" ]
lynn.robotics@gmail.com
8e121be91856dc1a72816af467d15a1e8347a19f
890237edf24875da7b89a9358798327616ecef52
/src/main/java/frame/StudentsFrame.java
3c1f5d5563978a9a72bd362c2d0bba2644cdbcb1
[]
no_license
Orion10110/Student
73e4ad1d901c5e72f72fd5dca3fb0c9a10483951
2069ced2d165326a010ba4eb01448668cb053e72
refs/heads/master
2021-01-24T08:42:16.115468
2016-09-29T16:11:53
2016-09-29T16:11:53
69,061,991
0
0
null
null
null
null
UTF-8
Java
false
false
15,590
java
package frame; import java.sql.SQLException; import java.util.Collection; import java.util.Vector; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import logic.Group; import logic.ManagementSystem; import logic.Student; public class StudentsFrame extends JFrame implements ActionListener, ListSelectionListener, ChangeListener{ // Введем сразу имена для кнопок - потом будем их использовать в обработчиках private static final String MOVE_GR = "moveGroup"; private static final String CLEAR_GR = "clearGroup"; private static final String INSERT_ST = "insertStudent"; private static final String UPDATE_ST = "updateStudent"; private static final String DELETE_ST = "deleteStudent"; private static final String ALL_STUDENTS = "allStudent"; private ManagementSystem ms = null; private JList grpList; private JTable stdList; private JSpinner spYear; public StudentsFrame() throws Exception { // Устанавливаем layout для всей клиентской части формы getContentPane().setLayout(new BorderLayout()); // Создаем строку меню JMenuBar menuBar = new JMenuBar(); // Создаем выпадающее меню JMenu menu = new JMenu("Отчеты"); // Создаем пункт в выпадающем меню JMenuItem menuItem = new JMenuItem("Все студенты"); menuItem.setName(ALL_STUDENTS); menuItem.addActionListener(this); // Вставляем пункт меню в выпадающее меню menu.add(menuItem); // Вставляем выпадающее меню в строку меню menuBar.add(menu); // Устанавливаем меню для формы setJMenuBar(menuBar); // Создаем верхнюю панель, где будет поле для ввода года JPanel top = new JPanel(); // Устанавливаем для нее layout top.setLayout(new FlowLayout(FlowLayout.LEFT)); // Вставляем пояснительную надпись top.add(new JLabel("Год обучения:")); // Делаем спин-поле // 1. Задаем модель поведения - только цифры // 2. Вставляем в панель SpinnerModel sm = new SpinnerNumberModel(2006, 1900, 2100, 1); spYear = new JSpinner(sm); spYear.addChangeListener(this); top.add(spYear); // Создаем нижнюю панель и задаем ей layout JPanel bot = new JPanel(); bot.setLayout(new BorderLayout()); // Создаем левую панель для вывода списка групп // Она у нас GroupPanel left = new GroupPanel(); // Задаем layout и задаем "бордюр" вокруг панели left.setLayout(new BorderLayout()); left.setBorder(new BevelBorder(BevelBorder.LOWERED)); // Получаем коннект к базе и создаем объект ManagementSystem ms = ManagementSystem.getInstance(); // Получаем список групп Vector<Group> gr = new Vector<Group>(ms.getGroups()); // Создаем надпись left.add(new JLabel("Группы:"), BorderLayout.NORTH); // Создаем визуальный список и вставляем его в скроллируемую // панель, которую в свою очередь уже кладем на панель left grpList = new JList(gr); grpList.addListSelectionListener(this); grpList.setSelectedIndex(0); left.add(new JScrollPane(grpList), BorderLayout.CENTER); // Создаем кнопки для групп JButton btnMvGr = new JButton("Переместить"); btnMvGr.setName(MOVE_GR); JButton btnClGr = new JButton("Очистить"); btnClGr.setName(CLEAR_GR); btnMvGr.addActionListener(this); btnClGr.addActionListener(this); // Создаем панель, на которую положим наши кнопки и кладем ее вниз JPanel pnlBtnGr = new JPanel(); pnlBtnGr.setLayout(new GridLayout(1, 2)); pnlBtnGr.add(btnMvGr); pnlBtnGr.add(btnClGr); left.add(pnlBtnGr, BorderLayout.SOUTH); // Создаем правую панель для вывода списка студентов JPanel right = new JPanel(); // Задаем layout и задаем "бордюр" вокруг панели right.setLayout(new BorderLayout()); right.setBorder(new BevelBorder(BevelBorder.LOWERED)); // Создаем надпись right.add(new JLabel("Студенты:"), BorderLayout.NORTH); // Создаем таблицу и вставляем ее в скроллируемую // панель, которую в свою очередь уже кладем на панель right // Наша таблица пока ничего не умеет - просто положим ее как заготовку // Сделаем в ней 4 колонки - Фамилия, Имя, Отчество, Дата рождения stdList = new JTable(1, 4); right.add(new JScrollPane(stdList), BorderLayout.CENTER); // Создаем кнопки для студентов JButton btnAddSt = new JButton("Добавить"); btnAddSt.setName(INSERT_ST); btnAddSt.addActionListener(this); JButton btnUpdSt = new JButton("Исправить"); btnUpdSt.setName(UPDATE_ST); btnUpdSt.addActionListener(this); JButton btnDelSt = new JButton("Удалить"); btnDelSt.setName(DELETE_ST); btnDelSt.addActionListener(this); // Создаем панель, на которую положим наши кнопки и кладем ее вниз JPanel pnlBtnSt = new JPanel(); pnlBtnSt.setLayout(new GridLayout(1, 3)); pnlBtnSt.add(btnAddSt); pnlBtnSt.add(btnUpdSt); pnlBtnSt.add(btnDelSt); right.add(pnlBtnSt, BorderLayout.SOUTH); // Вставляем панели со списками групп и студентов в нижнюю панель bot.add(left, BorderLayout.WEST); bot.add(right, BorderLayout.CENTER); // Вставляем верхнюю и нижнюю панели в форму getContentPane().add(top, BorderLayout.NORTH); getContentPane().add(bot, BorderLayout.CENTER); // Сразу выделяем первую группу grpList.setSelectedIndex(0); // Задаем границы формы setBounds(100, 100, 700, 500); } public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof Component) { Component c = (Component) e.getSource(); if (c.getName().equals(MOVE_GR)) { moveGroup(); } if (c.getName().equals(CLEAR_GR)) { clearGroup(); } if (c.getName().equals(ALL_STUDENTS)) { showAllStudents(); } if (c.getName().equals(INSERT_ST)) { insertStudent(); } if (c.getName().equals(UPDATE_ST)) { updateStudent(); } if (c.getName().equals(DELETE_ST)) { deleteStudent(); } } } // Метод для обеспечения интерфейса ListSelectionListener public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { reloadStudents(); } } // Метод для обеспечения интерфейса ChangeListener public void stateChanged(ChangeEvent e) { reloadStudents(); } // метод для обновления списка студентов для определенной группы private void reloadStudents() { Thread t = new Thread() { // Переопределяем в нем метод run public void run() { if (stdList != null) { // Получаем выделенную группу Group g = (Group) grpList.getSelectedValue(); // Получаем число из спинера int y = ((SpinnerNumberModel) spYear.getModel()).getNumber().intValue(); try { // Получаем список студентов Collection<Student> s = ms.getStudentsFromGroup(g, y); // И устанавливаем модель для таблицы с новыми данными stdList.setModel(new StudentTableModel(new Vector<Student>(s))); } catch (SQLException e) { JOptionPane.showMessageDialog(StudentsFrame.this, e.getMessage()); } } // Вводим искусственную задержку на 3 секунды try { Thread.sleep(3000); } catch (Exception e) { } } // Окончание нашего метода run }; // Окончание определения анонимного класса // И теперь мы запускаем наш поток t.start(); } // метод для переноса группы private void moveGroup() { JOptionPane.showMessageDialog(this, "moveGroup"); } // метод для очистки группы private void clearGroup() { Thread t = new Thread() { public void run() { // Проверяем - выделена ли группа if (grpList.getSelectedValue() != null) { if (JOptionPane.showConfirmDialog(StudentsFrame.this, "Вы хотите удалить студентов из группы?", "Удаление студентов", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { // Получаем выделенную группу Group g = (Group) grpList.getSelectedValue(); // Получаем число из спинера int y = ((SpinnerNumberModel) spYear.getModel()).getNumber().intValue(); try { // Удалили студентов из группы ms.removeStudentsFromGroup(g, y); // перегрузили список студентов reloadStudents(); } catch (SQLException e) { JOptionPane.showMessageDialog(StudentsFrame.this, e.getMessage()); } } } } }; t.start(); } // метод для добавления студента private void insertStudent() { JOptionPane.showMessageDialog(this, "insertStudent"); } // метод для редактирования студента private void updateStudent() { JOptionPane.showMessageDialog(this, "updateStudent"); } // метод для удаления студента private void deleteStudent() { Thread t = new Thread() { public void run() { if (stdList != null) { StudentTableModel stm = (StudentTableModel) stdList.getModel(); // Проверяем - выделен ли хоть какой-нибудь студент if (stdList.getSelectedRow() >= 0) { if (JOptionPane.showConfirmDialog(StudentsFrame.this, "Вы хотите удалить студента?", "Удаление студента", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { // Вот где нам пригодился метод getStudent(int rowIndex) Student s = stm.getStudent(stdList.getSelectedRow()); try { ms.deleteStudent(s); reloadStudents(); } catch (SQLException e) { JOptionPane.showMessageDialog(StudentsFrame.this, e.getMessage()); } } } // Если студент не выделен - сообщаем пользователю, что это необходимо else { JOptionPane.showMessageDialog(StudentsFrame.this, "Необходимо выделить студента в списке"); } } } }; t.start(); } // метод для показа всех студентов private void showAllStudents() { JOptionPane.showMessageDialog(this, "showAllStudents"); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { // Мы сразу отменим продолжение работы, если не сможем получить // коннект к базе данных StudentsFrame sf = new StudentsFrame(); sf.setDefaultCloseOperation(EXIT_ON_CLOSE); sf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } }); } } // Наш внутренний класс - переопределенная панель. class GroupPanel extends JPanel { public Dimension getPreferredSize() { return new Dimension(250, 0); } }
[ "pojasoriona@gmail.com" ]
pojasoriona@gmail.com
c060fe4426ca052bdd3982ccd22d634d4f794910
e3ea6022ff733fbde7e4bbcbc110716104a6c2f4
/LoginExample/src/java/com/loginexample/dao/impl/UserDAOImpl.java
331e4119cb50f4cc647461eaa9f7a45483703fe3
[]
no_license
bibekshakya/githubtest
e905e4240fec8a5f4b8215b845a7ff9f59607892
da3beab7b538eb201bca5311b1d058d8ee7f30a0
refs/heads/master
2021-01-24T16:02:08.302139
2015-06-04T13:54:40
2015-06-04T13:54:40
36,920,366
0
0
null
2015-06-05T08:06:04
2015-06-05T08:06:02
Java
UTF-8
Java
false
false
1,062
java
/* * 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 com.loginexample.dao.impl; import com.loginexample.dao.UserDAO; import com.loginexample.entity.User; import java.util.ArrayList; import java.util.List; /** * * @author forsell */ public class UserDAOImpl implements UserDAO { @Override public List<User> getAll() { List<User> userList=new ArrayList<User>(); userList.add(new User(1, "admin", "admin")); userList.add(new User(2,"dixanta","admin")); userList.add(new User(3,"dix","admin")); return userList; } @Override public User authenticate(String username, String password) { User u=null; for(User user:getAll()){ if(user.getUserName().equalsIgnoreCase(username) && user.getPassword().equalsIgnoreCase(password)){ u=user; break; } } return u; } }
[ "dixanta@gmail.com" ]
dixanta@gmail.com
4fedb9570e6144fd191689e650031abd33812f6a
c900886d205af05242301e28467a7f243e96e697
/arquillian-tutorial/src/test/java/jug/cdi/one/qualifiers/QualifierTest.java
d884c116ed309590400a1294043a52c1ce355b20
[]
no_license
enriquezrene/cdi
c595d4de56c849c97ddc0c4c793e7155e511e6a7
b969ac503b6ac44e445ffa776bf449002e39563b
refs/heads/master
2021-01-19T07:03:22.941342
2014-12-17T22:48:01
2014-12-17T22:48:01
28,158,400
1
1
null
null
null
null
UTF-8
Java
false
false
1,158
java
package jug.cdi.one.qualifiers; import javax.inject.Inject; import jug.cdi.one.HelloService; import junit.framework.Assert; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class QualifierTest { @Inject @English private HelloService helloServiceIngles; @Inject @French private HelloService helloServiceFrances; @Test public void shouldGreetInEnglish() throws Exception { Assert.assertEquals("Hello world", helloServiceIngles.hello()); } @Test public void shouldGreetInFrench() throws Exception { Assert.assertEquals("Bonjour tout le monde!", helloServiceFrances.hello()); } @Deployment public static JavaArchive createDeployment() { return ShrinkWrap.create(JavaArchive.class, "test.jar") .addClass(HelloService.class) .addPackage(English.class.getPackage()) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } }
[ "enriquezrene.ap@gmail.com" ]
enriquezrene.ap@gmail.com
fb8007859fe8fc904c189aada99a269c5a5a4961
e863022689b9394925f0b281e350b655e7f3f2c8
/src/main/java/com/bill/materiel/service/SysUserService.java
6aca394fa5fe6615497ab69cf7959baeee926f4e
[]
no_license
jiekou0000/materiel
ac22d184553d5f2bce877a8c09172b5cd2758157
9b7ccee9d87e54f125712431a7537765c93ca694
refs/heads/master
2020-04-11T01:46:39.814446
2018-12-18T09:53:11
2018-12-18T09:53:11
161,426,038
1
0
null
null
null
null
UTF-8
Java
false
false
2,003
java
package com.bill.materiel.service; import com.bill.materiel.consts.WebConstant; import com.bill.materiel.dao.UserInfoRepository; import com.bill.materiel.domain.UserInfo; import com.bill.materiel.dto.sysuser.RegisterReq; import com.bill.materiel.utils.message.Message; import com.bill.materiel.utils.message.MessageType; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import javax.validation.Valid; import java.util.Date; /** * SysUserService * * @author Bill * @date 2018/12/14 0014 */ @Service public class SysUserService { @Autowired private UserInfoRepository userInfoRepository; /** * 注册 */ public Message doRegister(@Valid RegisterReq req) { UserInfo exist = userInfoRepository.findByLoginName(req.getLoginName()); if (exist != null) { return new Message(MessageType.ERROR, "登录名已存在"); } UserInfo userInfo = UserInfo.builder() .phoneNum(req.getPhoneNum()) .password(new BCryptPasswordEncoder().encode(req.getPassword())) .loginName(req.getLoginName()) .createTime(new Date()) .build(); userInfoRepository.save(userInfo); return new Message(MessageType.SUCCESS); } /** * 登陆 */ public Message doLogin() { if (StringUtils.isEmpty(WebConstant.LOGIN_REDIRECT_URI)) { return new Message(MessageType.SUCCESS, (Object) "/index"); } else { String[] str = WebConstant.LOGIN_REDIRECT_URI.split("/"); if (!StringUtils.equals("user", str[1])) { WebConstant.LOGIN_REDIRECT_URI = "/tpl" + WebConstant.LOGIN_REDIRECT_URI; } return new Message(MessageType.SUCCESS, (Object) WebConstant.LOGIN_REDIRECT_URI); } } }
[ "bill@hxonline.tv" ]
bill@hxonline.tv
b9332d78bff9a344f718093ad503ae2676a47ce3
1f19aec2ecfd756934898cf0ad2758ee18d9eca2
/u-1/u-11/u-11-111/u-11-111-1111/u-11-111-1111-f5519.java
a49f273540db74d3f7b01eb633cd490ab509f1af
[]
no_license
apertureatf/perftest
f6c6e69efad59265197f43af5072aa7af8393a34
584257a0c1ada22e5486052c11395858a87b20d5
refs/heads/master
2020-06-07T17:52:51.172890
2019-06-21T18:53:01
2019-06-21T18:53:01
193,039,805
0
0
null
null
null
null
UTF-8
Java
false
false
106
java
mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117 4170898073685
[ "jenkins@khan.paloaltonetworks.local" ]
jenkins@khan.paloaltonetworks.local
5471a175dbe7a653f36f5e595bd5408f1753f98e
18aaeb1f2c1c72c98ed3b2f285bd04c7ba1a7648
/app/src/main/java/com/yuas/pecker/model/imodel/ILoginModel.java
d9dad768f5874436ef232dd2bb5c26650b667c62
[]
no_license
TravelerLq/pecker
27d9ca961caa9c8bb1d62848ff492c05fc83a8e9
24c1ef82d9ddc6fa177a5e2e4e53650836ce7a54
refs/heads/master
2020-04-27T11:36:04.554229
2019-03-25T03:12:18
2019-03-25T03:12:18
174,301,130
0
0
null
null
null
null
UTF-8
Java
false
false
201
java
package com.yuas.pecker.model.imodel; import com.yuas.pecker.bean.UserResponseBean; public interface ILoginModel { void login(String name, String psw, INetCallback<UserResponseBean> callback); }
[ "2318241264@qq.com" ]
2318241264@qq.com
75f7f3e6d114682bd83fb180aa5845d039573c93
14b946b7d5d1a7cb50f7b35eb9808d51f9ab8acc
/src/main/java/com/mpather47/git/repository/person/impl/PersonRepositoryImpl.java
81e7a5e556f62c03dc238758504846ba0af219a6
[]
no_license
Mbuyi5/Hospital-Management-System
7a3f06503e059bfc18a9f15c2587d2a38b3b4125
694dcbc9dfb4f2a1a16876bfe88ccce3c6db9ab6
refs/heads/master
2023-01-06T16:35:48.794379
2020-11-09T08:38:01
2020-11-09T08:38:01
277,210,577
0
0
null
2020-09-06T13:47:34
2020-07-05T01:20:38
Java
UTF-8
Java
false
false
1,498
java
package com.mpather47.git.repository.person.impl; import com.mpather47.git.entity.person.Person; import com.mpather47.git.repository.person.PersonRepository; import java.util.HashSet; import java.util.Set; public class PersonRepositoryImpl implements PersonRepository { private static PersonRepository repository=null; private Set<Person> personDB; private PersonRepositoryImpl() {this.personDB = new HashSet<>();} public static PersonRepository getRepository(){ if(repository==null) repository = new PersonRepositoryImpl(); return repository; } @Override public Set<Person> getAll() { return this.personDB; } @Override public Person create(Person person) { this.personDB.add(person); return person; } @Override public Person read(String id) { Person person = this.personDB.stream().filter(r -> r.getPersonId().trim().equalsIgnoreCase(id)) .findAny().orElse(null); return person; } @Override public Person update(Person person) { boolean deletePerson = delete(person.getPersonId()); if(deletePerson){ this.personDB.add(person); return person; } return null; } @Override public boolean delete(String id) { Person person = read(id); if(person != null){ this.personDB.remove(person); return true; } return false; } }
[ "mpather47@gmail.com" ]
mpather47@gmail.com
843e8b58b5f609285edea48609dd59d00cf59a89
1f4032004aad1e8163433ad9ebd3aacda48ee234
/src/viz/painters/array/index/ArrayIsFieldIndexPainter.java
298c0e874ea813c5d0f675517fdf03f2cf4200ca
[]
no_license
johnwu96822/proviz
abef2c2cca200461fe66d7a604e32dfdffe945ac
cba24cea11c64fb0303682f7be855e514cf5007b
refs/heads/master
2021-01-01T19:11:08.698069
2013-09-01T07:31:23
2013-09-01T07:31:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
658
java
package viz.painters.array.index; import viz.ProViz; import viz.painters.Painter; import viz.painters.java.array.IndexPainter; import viz.runtime.IVizVariable; import viz.views.VizCanvas; /** * This index variable is a local variable, and the target array is a field. * @author JW * */ public abstract class ArrayIsFieldIndexPainter extends IndexPainter { public ArrayIsFieldIndexPainter(IVizVariable vvar, VizCanvas canvas) { super(vvar, canvas); } @Override public Painter getArrayPainter() { return ProViz.getVPM().getPainter(this.getInstanceVariable(getArrayName())); } public abstract String getArrayName(); }
[ "johnwu96822@gmail.com" ]
johnwu96822@gmail.com
16b59d9cba4ccff10347418b6898191a325a1d0c
ab3ff6af186492bbd727daaf4de7f55e44c3c796
/app/src/androidTest/java/com/algonquincollege/lach0192/hilo/ExampleInstrumentedTest.java
71777fe54c9bcdedffad1f60660acd86e912dd7c
[]
no_license
lach0192/HiLo
3d317700ce9a8cf43ca36d1a1237fe0d990cea0e
9552c80830cfb7a9ae42a4da1cd88e7948801cbc
refs/heads/master
2021-07-14T02:04:27.707959
2017-10-03T14:19:50
2017-10-03T14:19:50
105,480,021
0
0
null
null
null
null
UTF-8
Java
false
false
772
java
package com.algonquincollege.lach0192.hilo; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.algonquincollege.lach0192.hilo", appContext.getPackageName()); } }
[ "lach0192@algonquinlive.com" ]
lach0192@algonquinlive.com
1db37d5706d502ee53c8a5a897e629f697fab02a
a272ab3bdd64b571c478e3188907fc925d184337
/squidCore/src/main/java/org/cirdles/squid/squidReports/squidReportTables/SquidReportTable.java
2eee9d30a5950aa767056f1da402f8d50ab5e40d
[ "Apache-2.0" ]
permissive
halleydt/Squid
df5392b4a52d8ad94ad8cb95bc93c5e89f3518cf
cc84e5a50ce1aea1c466b6b4f69070f9b20bc3d5
refs/heads/master
2020-08-05T18:39:55.859808
2019-09-03T15:52:18
2019-09-03T15:52:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
23,461
java
/* * Copyright 2019 James F. Bowring and CIRDLES.org. * * 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.cirdles.squid.squidReports.squidReportTables; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.cirdles.squid.shrimp.ShrimpFraction; import org.cirdles.squid.shrimp.SquidRatiosModel; import static org.cirdles.squid.squidReports.squidReportCategories.SquidReportCategory.createReportCategory; import org.cirdles.squid.squidReports.squidReportCategories.SquidReportCategoryInterface; import org.cirdles.squid.squidReports.squidReportColumns.SquidReportColumn; import org.cirdles.squid.tasks.TaskInterface; import org.cirdles.squid.tasks.expressions.Expression; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.COM206PB_PCT; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.COM206PB_PCT_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.COM208PB_PCT; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.COM208PB_PCT_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.CONCEN_206PB; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.CONCEN_208PB; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.ERR_CORREL; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.ERR_CORREL_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR206_238AGE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR206_238AGE_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR206_238CALIB_CONST; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR207_206AGE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR207_206AGE_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR208_232AGE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR208_232AGE_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR208_232CALIB_CONST; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4CORR; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB4COR_DISCORDANCE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB7COR206_238AGE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB7COR206_238AGE_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB7COR206_238CALIB_CONST; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB7COR208_232AGE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB7COR208_232AGE_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB7COR208_232CALIB_CONST; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB7CORR; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB8COR206_238AGE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB8COR206_238AGE_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB8COR206_238CALIB_CONST; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB8COR207_206AGE; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB8COR207_206AGE_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.PB8CORR; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R204PB_206PB; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R206PB_238U; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R206PB_238U_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R207PB_206PB; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R207PB_206PB_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R207PB_235U; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R207PB_235U_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R208PB206PB; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R208PB206PB_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R208PB_232TH; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.R238U_206PB; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.TOTAL_206_238_RM; import static org.cirdles.squid.tasks.expressions.builtinExpressions.BuiltInExpressionsDataDictionary.TOTAL_208_232_RM; import org.cirdles.squid.tasks.expressions.constants.ConstantNode; import org.cirdles.squid.tasks.expressions.expressionTrees.ExpressionTreeBuilderInterface; import org.cirdles.squid.tasks.expressions.expressionTrees.ExpressionTreeInterface; import org.cirdles.squid.tasks.expressions.operations.Value; /** * * @author James F. Bowring, CIRDLES.org, and Earth-Time.org */ public class SquidReportTable implements Serializable, SquidReportTableInterface { // private static final long serialVersionUID = 5227409808812622714L; public final static int HEADER_ROW_COUNT = 7; public final static int DEFAULT_COUNT_OF_SIGNIFICANT_DIGITS = 15; // Fields private String reportTableName; private LinkedList<SquidReportCategoryInterface> reportCategories; private SquidReportTable() { } private SquidReportTable(String reportTableName, LinkedList<SquidReportCategoryInterface> reportCategories) { this.reportTableName = reportTableName; this.reportCategories = reportCategories; } public static SquidReportTable createDefaultSquidReportTableRefMat(TaskInterface task) { String reportTableName = "Default Squid3 Report Table for Reference Materials"; LinkedList<SquidReportCategoryInterface> reportCategories = createDefaultReportCategoriesRefMat(task); return new SquidReportTable(reportTableName, reportCategories); } public static SquidReportTable createDefaultSquidReportTableUnknown(TaskInterface task) { String reportTableName = "Default Squid3 Report Table for Unknowns"; LinkedList<SquidReportCategoryInterface> reportCategories = createDefaultReportCategoriesUnknown(task); return new SquidReportTable(reportTableName, reportCategories); } public static LinkedList<SquidReportCategoryInterface> createDefaultReportCategoriesRefMat(TaskInterface task) { LinkedList<SquidReportCategoryInterface> reportCategoriesRefMat = new LinkedList<>(); SquidReportCategoryInterface spotFundamentals = createDefaultSpotFundamentalsCategory(); reportCategoriesRefMat.add(spotFundamentals); SquidReportCategoryInterface countsPerSecond = createDefaultCountsPerSecondCategory(task); reportCategoriesRefMat.add(countsPerSecond); SquidReportCategoryInterface rawNuclideRatios = createDefaultRawNuclideRatiosCategory(task); reportCategoriesRefMat.add(rawNuclideRatios); SquidReportCategoryInterface corrIndependentBuiltIn = createReportCategory("Correction-Independent Built-In"); // TODO // reportCategoriesRefMat.add(corrIndependentBuiltIn); SquidReportCategoryInterface pb204Corr_RM = createReportCategory("204Pb Corrected"); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR206_238CALIB_CONST)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR206_238AGE_RM, "Ma")); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR208_232CALIB_CONST)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR208_232AGE_RM)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + TOTAL_206_238_RM)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + TOTAL_208_232_RM)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + COM206PB_PCT)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + COM208PB_PCT)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R208PB206PB)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR207_206AGE_RM, "Ma")); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R207PB_206PB_RM)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R207PB_235U_RM)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R206PB_238U_RM)); pb204Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + ERR_CORREL_RM)); reportCategoriesRefMat.add(pb204Corr_RM); SquidReportCategoryInterface pb207Corr_RM = createReportCategory("207Pb Corrected"); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7COR206_238CALIB_CONST)); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7COR206_238AGE_RM, "Ma")); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7COR208_232CALIB_CONST)); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7COR208_232AGE_RM, "Ma")); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + TOTAL_206_238_RM)); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + TOTAL_208_232_RM)); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + COM206PB_PCT_RM)); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + COM208PB_PCT_RM)); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + R208PB206PB_RM)); pb207Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + R206PB_238U_RM)); reportCategoriesRefMat.add(pb207Corr_RM); SquidReportCategoryInterface pb208Corr_RM = createReportCategory("208Pb Corrected"); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8COR206_238CALIB_CONST)); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8COR206_238AGE_RM, "Ma")); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + TOTAL_206_238_RM)); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + COM206PB_PCT_RM)); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8COR207_206AGE_RM, "Ma")); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R207PB_206PB_RM)); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R207PB_235U_RM)); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R206PB_238U_RM)); pb208Corr_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + ERR_CORREL_RM)); reportCategoriesRefMat.add(pb208Corr_RM); // SquidReportCategoryInterface custom_RM = createReportCategory("Custom Expressions Ref Mat"); // List<Expression> customExpressionsRM = task.getCustomTaskExpressions(); // for (Expression exp : customExpressionsRM) { // ExpressionTreeInterface expTree = exp.getExpressionTree(); // if ((!expTree.isSquidSwitchSCSummaryCalculation()) // && (expTree.isSquidSwitchSTReferenceMaterialCalculation())) { // custom_RM.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(expTree.getName())); // } // } // reportCategoriesRefMat.add(custom_RM); return reportCategoriesRefMat; } public static LinkedList<SquidReportCategoryInterface> createDefaultReportCategoriesUnknown(TaskInterface task) { LinkedList<SquidReportCategoryInterface> reportCategoriesUnknown = new LinkedList<>(); SquidReportCategoryInterface spotFundamentals = createDefaultSpotFundamentalsCategory(); reportCategoriesUnknown.add(spotFundamentals); SquidReportCategoryInterface countsPerSecond = createDefaultCountsPerSecondCategory(task); reportCategoriesUnknown.add(countsPerSecond); SquidReportCategoryInterface rawNuclideRatios = createDefaultRawNuclideRatiosCategory(task); reportCategoriesUnknown.add(rawNuclideRatios); SquidReportCategoryInterface corrIndependentData = createReportCategory("Correction-Independent Data"); // TODO // reportCategoriesUnknown.add(corrIndependentData); SquidReportCategoryInterface pb204Corr = createReportCategory("204Pb Corrected"); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + COM206PB_PCT)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + COM208PB_PCT)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R208PB206PB)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + CONCEN_206PB)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + CONCEN_208PB)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR206_238AGE, "Ma")); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR207_206AGE, "Ma")); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR208_232AGE, "Ma")); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4COR_DISCORDANCE)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R208PB_232TH)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R238U_206PB)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R207PB_206PB)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R207PB_235U)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + R206PB_238U)); pb204Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB4CORR + ERR_CORREL)); reportCategoriesUnknown.add(pb204Corr); SquidReportCategoryInterface pb207Corr = createReportCategory("207Pb Corrected"); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + R204PB_206PB)); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + COM206PB_PCT)); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + COM208PB_PCT)); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + R208PB206PB)); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + CONCEN_206PB)); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + CONCEN_208PB)); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7COR206_238AGE, "Ma")); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7COR208_232AGE, "Ma")); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + R206PB_238U)); pb207Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB7CORR + R208PB_232TH)); reportCategoriesUnknown.add(pb207Corr); SquidReportCategoryInterface pb208Corr = createReportCategory("208Pb Corrected"); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R204PB_206PB)); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + COM206PB_PCT)); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + CONCEN_206PB)); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8COR206_238AGE, "Ma")); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8COR207_206AGE, "Ma")); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R238U_206PB)); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R207PB_206PB)); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R207PB_235U)); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + R206PB_238U)); pb208Corr.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(PB8CORR + ERR_CORREL)); reportCategoriesUnknown.add(pb208Corr); SquidReportCategoryInterface custom = createReportCategory("Custom Expressions"); List<Expression> customExpressions = task.getCustomTaskExpressions(); for (Expression exp : customExpressions) { ExpressionTreeInterface expTree = exp.getExpressionTree(); if ((!expTree.isSquidSwitchSCSummaryCalculation()) && !(expTree instanceof ConstantNode) && !(((ExpressionTreeBuilderInterface) expTree).getOperation() instanceof Value) && (expTree.isSquidSwitchSAUnknownCalculation())) { custom.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(expTree.getName())); } } reportCategoriesUnknown.add(custom); return reportCategoriesUnknown; } private static SquidReportCategoryInterface createDefaultSpotFundamentalsCategory() { SquidReportCategoryInterface spotFundamentals = createReportCategory("Spot Fundamentals"); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("DateTimeMilliseconds")); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("Hours", 5)); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("StageX", 5)); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("StageY", 5)); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("StageZ", 5)); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("Qt1Y", 5)); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("Qt1Z", 5)); spotFundamentals.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn("PrimaryBeam", 5)); return spotFundamentals; } private static SquidReportCategoryInterface createDefaultCountsPerSecondCategory(TaskInterface task) { SquidReportCategoryInterface countsPerSecond = createReportCategory("CPS"); // special case of generation String[] isotopeLabels = new String[task.getSquidSpeciesModelList().size()]; for (int i = 0; i < isotopeLabels.length; i++) { isotopeLabels[i] = task.getMapOfIndexToMassStationDetails().get(i).getIsotopeLabel(); countsPerSecond.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(isotopeLabels[i])); } return countsPerSecond; } private static SquidReportCategoryInterface createDefaultRawNuclideRatiosCategory(TaskInterface task) { SquidReportCategoryInterface rawNuclideRatios = createReportCategory("Raw Nuclide Ratios"); // special case of generation Iterator<SquidRatiosModel> squidRatiosIterator = ((ShrimpFraction) task.getUnknownSpots().get(0)).getIsotopicRatiosII().iterator(); while (squidRatiosIterator.hasNext()) { SquidRatiosModel entry = squidRatiosIterator.next(); if (entry.isActive()) { String displayNameNoSpaces = entry.getDisplayNameNoSpaces().substring(0, Math.min(20, entry.getDisplayNameNoSpaces().length())); rawNuclideRatios.getCategoryColumns().add(SquidReportColumn.createSquidReportColumn(displayNameNoSpaces)); } } return rawNuclideRatios; } /** * @return the reportTableName */ @Override public String getReportTableName() { return reportTableName; } /** * @param reportTableName the reportTableName to set */ @Override public void setReportTableName(String reportTableName) { this.reportTableName = reportTableName; } /** * @return the reportCategories */ @Override public LinkedList<SquidReportCategoryInterface> getReportCategories() { return reportCategories; } /** * @param reportCategories the reportCategories to set */ @Override public void setReportCategories(LinkedList<SquidReportCategoryInterface> reportCategories) { this.reportCategories = reportCategories; } }
[ "noreply@github.com" ]
halleydt.noreply@github.com
ef7eb53e464c865896b93994ed62607114f77b52
e702c6111ecc17133bc875c129fab3ea082c1a47
/z_javaTest/src/test_lambda/TestLambdaInterface.java
744b766cf87cabc4b8dd65728527cba6a05beefc
[]
no_license
mingginew88/githubTest
012e65fbf6a948d093f8934f6fbc2009557b35ea
18448e21fa92e5bb1eb52d6e24285dee87516a18
refs/heads/master
2020-03-17T00:29:13.381558
2018-06-05T07:02:19
2018-06-05T07:02:19
133,118,473
0
0
null
null
null
null
UTF-8
Java
false
false
213
java
package test_lambda; public interface TestLambdaInterface { public void test(); } interface TestLambdaInterface2{ public void test(int a); } interface TestLambdaInterface3{ public int test(int a, int b); }
[ "39209657+mingginew88@users.noreply.github.com" ]
39209657+mingginew88@users.noreply.github.com
54a0fb113a65329b023ba8938ca3365da6aa48d9
8e11d2659b0f9cd053d86e2fb399d73e41e6cc06
/src/khazar/SJF.java
9a0e8f3951383eed125ca2f0205aa73d737ca386
[]
no_license
ziyamammadov/sjf-scheduling
e72a0536184110f11c37b320ac99c9611b4c7eb7
cd86369fcd1ec341b79dc9dbbd3eabe37dfa238a
refs/heads/master
2022-05-28T12:44:31.017779
2020-05-05T09:08:18
2020-05-05T09:10:58
261,407,708
0
0
null
null
null
null
UTF-8
Java
false
false
2,718
java
package khazar; public class SJF { static void findWaitingTime(Process[] proc, int n, int[] wt) { int[] rt = new int[n]; for (int i = 0; i < n; i++) rt[i] = proc[i].getBurstTime(); int complete = 0, t = 0, min = Integer.MAX_VALUE; int shortest = 0, finish_time; boolean check = false; while (complete != n) { for (int j = 0; j < n; j++) { if ((proc[j].getArrivalTime() <= t) && (rt[j] < min) && rt[j] > 0) { min = rt[j]; shortest = j; check = true; } } if (!check) { t++; continue; } rt[shortest]--; min = rt[shortest]; if (min == 0) min = Integer.MAX_VALUE; if (rt[shortest] == 0) { complete++; check = false; finish_time = t + 1; wt[shortest] = finish_time - proc[shortest].getBurstTime() - proc[shortest].getArrivalTime(); if (wt[shortest] < 0) wt[shortest] = 0; } t++; } } static void findTurnAroundTime(Process[] proc, int n, int[] wt, int[] tat) { for (int i = 0; i < n; i++) tat[i] = proc[i].getBurstTime() + wt[i]; } static void findAvgTime(Process[] proc, int n) { int[] wt = new int[n]; int[] tat = new int[n]; int total_wt = 0, total_tat = 0; findWaitingTime(proc, n, wt); findTurnAroundTime(proc, n, wt, tat); printHeader(); for (int i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; System.out.println(pad(String.valueOf(proc[i].getProcessId()), 15) + pad(String.valueOf(proc[i].getBurstTime()), 15) + pad(String.valueOf(wt[i]), 15) + pad(String.valueOf(tat[i]), 18)); } System.out.println("Average waiting time = " + (float) total_wt / (float) n); System.out.println("Average turn around time = " + (float) total_tat / (float) n); } static String pad(String str, int n) { return String.format("| " + "%-" + n + "s" + "|", str); } static void printHeader() { String s = "=========================================================================================="; System.out.println(s + "+"); System.out.println(pad("PROCESSES", 15) + pad("BURST TIME", 15) + pad("WAITING TIME", 15) + pad("TURN AROUND TIME", 18)); System.out.println(s + "|"); } }
[ "mmmdovziya900@gmail.com" ]
mmmdovziya900@gmail.com
09fbd13f6e5e517c23f97b7f2acbd97f62d6326b
8932f94e093dd391e064b41f2c6818d707d331f4
/src/main/java/com/addthis/hermes/internal/Manager.java
fb43573b19da6a99e425c32ce5408e645b6e2ccc
[ "Apache-2.0" ]
permissive
shanling2004/hermes
b4bffca46a83ca1ad9ec9be96acadb5f988facdf
c6998c4eadb2324fb183f4d5f64e63111a18e8a4
refs/heads/master
2021-01-22T12:45:21.164138
2015-06-15T19:45:49
2015-06-15T19:45:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,933
java
/* * 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.addthis.hermes.internal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import com.addthis.hermes.configuration.Transformer; import com.addthis.hermes.data.NavigationTiming; import com.addthis.hermes.data.ResourceTiming; public class Manager { private final Transformer transformer; private final Map<Long, MeasurementTree> data; public Manager(Transformer transformer) { this.transformer = transformer; this.data = new HashMap<>(); } public void addNavigationTiming(long timestamp, NavigationTiming navigationTiming) { MeasurementTree measurements = data.get(timestamp); if (measurements == null) { measurements = new MeasurementTree(); data.put(timestamp, measurements); } measurements.setNavigation(navigationTiming); } public void addMeasurement(long timestamp, ResourceTiming measurement) { String name = measurement.getName(); Pattern[] ignorePatterns = transformer.getIgnorePatterns(); Pattern[] searchPatterns = transformer.getSearchPatterns(); String[] replaceStrings = transformer.getReplacementStrings(); for (Pattern ignorePattern : ignorePatterns) { if (ignorePattern.matcher(name).find()) { return; } } for (int i = 0; i < searchPatterns.length; i++) { name = searchPatterns[i].matcher(name).replaceFirst(replaceStrings[i]); } ResourceTiming modified = new ResourceTiming.Builder(measurement).setName(name).build(); String[] categories = transformer.generateCategories(modified); MeasurementTree measurements = data.get(timestamp); if (measurements == null) { measurements = new MeasurementTree(); data.put(timestamp, measurements); } measurements.addMeasurement(modified, categories); } /** * Returns a reference to the current measurements. * * @return reference to the current measurements. */ public Map<Long, MeasurementTree> getMeasurements() { // TODO: Is it worth implementing deep copy for this feature? return data; } @Override public String toString() { return Arrays.toString(data.entrySet().toArray()); } }
[ "spiegel@addthis.com" ]
spiegel@addthis.com
b9a2c376c88db5ec90355088514b871aaf814c34
b1f6a65b8a132196bd87818fd7183c6c32e56149
/customerApp/app/src/main/java/com/example/kcwoo326/customerapp/activity/RegisterActivity.java
4f5c9cebaf035b808dd2b37bb2be0b93e078ef1f
[]
no_license
dhkim93/Pos_project
8abe03c0f372573b27b01cc99db6807b5fb9d720
a008452d76790ab06fd275f9370b1597ce31ff08
refs/heads/master
2020-04-12T06:42:18.272674
2016-10-28T10:03:33
2016-10-28T10:03:33
65,466,544
0
1
null
null
null
null
UTF-8
Java
false
false
7,091
java
package com.example.kcwoo326.customerapp.activity; /** * Created by KimJinWoo on 2016-09-27. */ import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.example.kcwoo326.customerapp.R; import com.example.kcwoo326.customerapp.app.AppConfig; import com.example.kcwoo326.customerapp.app.AppController; import com.example.kcwoo326.customerapp.helper.SQLiteHandler; import com.example.kcwoo326.customerapp.helper.SessionManager; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class RegisterActivity extends Activity { private static final String TAG = RegisterActivity.class.getSimpleName(); private Button btnRegister; private Button btnLinkToLogin; private EditText inputFullName; private EditText inputUserId; private EditText inputPassword; private ProgressDialog pDialog; private SessionManager session; private SQLiteHandler db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); inputFullName = (EditText) findViewById(R.id.name); inputUserId = (EditText) findViewById(R.id.user_id); inputPassword = (EditText) findViewById(R.id.password); btnRegister = (Button) findViewById(R.id.btnRegister); btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); // Progress dialog pDialog = new ProgressDialog(this); pDialog.setCancelable(false); // Session manager session = new SessionManager(getApplicationContext()); // SQLite database handler db = new SQLiteHandler(getApplicationContext()); // Check if user is already logged in or not if (session.isLoggedIn()) { // User is already logged in. Take him to main activity Intent intent = new Intent(RegisterActivity.this, MainActivity.class); startActivity(intent); finish(); } // Register Button Click event btnRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputFullName.getText().toString().trim(); String user_id = inputUserId.getText().toString().trim(); String password = inputPassword.getText().toString().trim(); if (!name.isEmpty() && !user_id.isEmpty() && !password.isEmpty()) { registerUser(name, user_id, password); } else { Toast.makeText(getApplicationContext(), "Please enter your details!", Toast.LENGTH_LONG) .show(); } } }); // Link to Login Screen btnLinkToLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); finish(); } }); } /** * Function to store user in MySQL database will post params(tag, name, * email, password) to register url * */ private void registerUser(final String name, final String user_id, final String password) { // Tag used to cancel the request String tag_string_req = "req_register"; pDialog.setMessage("Registering ..."); showDialog(); StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Register Response: " + response.toString()); hideDialog(); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { // User successfully stored in MySQL // Now store the user in sqlite String uid = jObj.getString("uid"); JSONObject user = jObj.getJSONObject("user"); String name = user.getString("name"); String user_id = user.getString("user_id"); String created_at = user.getString("created_at"); // Inserting row in users table db.addUser(name, user_id, uid, created_at); Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show(); // Launch login activity Intent intent = new Intent( RegisterActivity.this, LoginActivity.class); startActivity(intent); finish(); } else { // Error occurred in registration. Get the error // message String errorMsg = jObj.getString("error_msg"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Registration Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { // Posting params to register url Map<String, String> params = new HashMap<String, String>(); params.put("name", name); params.put("user_id", user_id); params.put("password", password); return params; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }
[ "dhkim930@naver.com" ]
dhkim930@naver.com
9b06e27cc4748ec37188b1ad3c665702cf1ce518
186372e2bb690197c8e2f8a2f526112c9ab17500
/jeevOMLibs/src/main/java/com/schoolteacher/mylibrary/model/State.java
9fced8ce947e785d838737ba1daf60100530e7c7
[]
no_license
shah00070/techer
a57f76e9f4be212caf8350e0330a860b55e83ccb
c26143fde45a1f0f0eed6a7c1abe1b3fba16202a
refs/heads/master
2021-01-19T11:42:29.707386
2016-06-03T08:46:39
2016-06-03T08:46:39
61,519,634
1
0
null
null
null
null
UTF-8
Java
false
false
409
java
package com.schoolteacher.mylibrary.model; import java.io.Serializable; public class State implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int Id; private String Name; public int getId() { return Id; } public void setId(int id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } }
[ "shah.h@jeevom.com" ]
shah.h@jeevom.com
04a9374132d8e7b34804b6bed5a058255495cb58
54f19212b0acf99981a1f68211121de212bfa570
/src/java/Inventario/Devoluciones.java
41ae9ae94fd785f0f2a2edd07fc98367e2f7a8d4
[]
no_license
amerikillo/SAARurales
df7d73183d952181b006120ea162f4d2467d2d27
b9fe8a641c42c5ac4a056da47060aa3f7038a725
refs/heads/master
2021-01-01T05:59:46.953015
2014-10-29T22:43:19
2014-10-29T22:43:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,444
java
/* * 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 Inventario; import ISEM.NuevoISEM; import conn.ConectionDB; import java.io.IOException; import java.io.PrintWriter; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Calendar; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import servlets.Facturacion; /** * * @author Americo */ public class Devoluciones extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ConectionDB con = new ConectionDB(); //ConectionDB_SQLServer consql = new ConectionDB_SQLServer(); Facturacion fact = new Facturacion(); NuevoISEM objSql = new NuevoISEM(); java.text.DateFormat df2 = new java.text.SimpleDateFormat("dd/MM/yyyy"); java.text.DateFormat df3 = new java.text.SimpleDateFormat("yyyy-MM-dd"); java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession sesion = request.getSession(true); try { try { if (request.getParameter("accion").equals("devolucion")) { con.conectar(); //consql.conectar(); String ClaPro = "", Total = "", Ubicacion = "", Provee = "", FolLote = "", ClaLot = "", FecCad = ""; String F_Cb = "", F_ClaMar=""; String FolLotSql = ""; int cantSQL = 0, cant = 0; ResultSet rset = con.consulta("select * from tb_lote where F_IdLote = '" + request.getParameter("IdLote") + "'"); while (rset.next()) { ClaPro = rset.getString("F_ClaPro"); cant = rset.getInt("F_ExiLot"); ClaLot = rset.getString("F_ClaLot"); FecCad = rset.getString("F_FecCad"); Ubicacion = rset.getString("F_Ubica"); Provee = rset.getString("F_ClaOrg"); FolLote = rset.getString("F_FolLot"); F_Cb = rset.getString("F_Cb"); F_ClaMar = rset.getString("F_ClaMar"); } /*ResultSet rsetsql = consql.consulta("select F_FolLot, F_ExiLot from tb_lote where F_ClaLot = '" + ClaLot + "' and F_ClaPro= '" + ClaPro + "' and F_FecCad = '" + df2.format(df3.parse(FecCad)) + "' and F_ClaPrv = '" + Provee + "'"); while (rsetsql.next()) { FolLotSql = rsetsql.getString("F_FolLot"); cantSQL = rsetsql.getInt("F_ExiLot"); } */ double importe = devuelveImporte(ClaPro, cant); double iva = devuelveIVA(ClaPro, cant); double costo = devuelveCosto(ClaPro); int ncant = cantSQL - cant; String indMov = objSql.dameidMov(); byte[] a = request.getParameter("Obser").getBytes("ISO-8859-1"); String Observaciones = (new String(a, "UTF-8")).toUpperCase(); con.insertar("insert into tb_devolcompra values ('" + request.getParameter("IdLote") + "','" + Observaciones + "','0','" + cant + "','','')"); String F_FolLot = ""; con.insertar("update tb_lote set F_ExiLot = '0' where F_IdLote = '" + request.getParameter("IdLote") + "' "); ResultSet rset2 = con.consulta("select F_FolLot from tb_lote where F_ClaLot = '" + request.getParameter("F_ClaLot") + "' and F_FecCad = '" + request.getParameter("F_FecCad") + "' and F_Ubica='NUEVA'"); while (rset2.next()) { F_FolLot = rset2.getString("F_FolLot"); } Calendar cal = Calendar.getInstance(); cal.setTime(df3.parse(request.getParameter("F_FecCad"))); cal.add(Calendar.YEAR, -3); String Fecfab = "" + df3.format(cal.getTime()); if (F_FolLot.equals("")) { F_FolLot = devuelveIndLote() + ""; con.insertar("insert into tb_lote values (0,'" + ClaPro + "','" + request.getParameter("F_ClaLot") + "','" + request.getParameter("F_FecCad") + "','" + cant + "','" + F_FolLot + "','" + Provee + "','NUEVA','" + Fecfab + "','" + F_Cb + "','"+F_ClaMar+"') "); } else { con.insertar("update tb_lote set F_ExiLot = '0' where F_IdLote = '" + request.getParameter("IdLote") + "' "); } con.insertar("insert into tb_movinv values('0',CURDATE(),'0','53','" + ClaPro + "','" + cant + "','" + costo + "','" + importe + "','-1','" + FolLote + "','" + Ubicacion + "','" + Provee + "',CURTIME(),'" + (String) sesion.getAttribute("nombre") + "')"); con.insertar("insert into tb_movinv values('0',CURDATE(),'0','4','" + ClaPro + "','" + cant + "','" + costo + "','" + importe + "','1','" + F_FolLot + "','NUEVA','" + Provee + "',CURTIME(),'" + (String) sesion.getAttribute("nombre") + "')"); //consql.insertar("insert into TB_MovInv values(CONVERT(date,GETDATE()),'1','','52','" + ClaPro + "','" + cant + "','" + costo + "','" + iva + "','" + importe + "','-1','" + FolLotSql + "','" + indMov + "','A','0','','','','" + Provee + "','" + (String) sesion.getAttribute("nombre") + "')"); //consql.insertar("update TB_Lote set F_ExiLot='" + ncant + "' where F_FolLot = '" + FolLotSql + "'"); //consql.cierraConexion(); con.cierraConexion(); out.println("<script>alert('Cambio físico correcto')</script>"); out.println("<script>window.location='devolucionesInsumo.jsp'</script>"); } } catch (Exception e) { System.out.println(e.getMessage()); } } finally { out.close(); } } public double devuelveImporte(String clave, int cantidad) throws SQLException { ConectionDB con = new ConectionDB(); int Tipo = 0; double Costo = 0.0, IVA = 0.0, Monto = 0.0, IVAPro = 0.0, MontoIva = 0.0; con.conectar(); ResultSet rset = con.consulta("select F_TipMed, F_Costo from tb_medica where F_ClaPro = '" + clave + "'"); while (rset.next()) { Tipo = rset.getInt(1); Costo = rset.getDouble(2); } if (Tipo == 2504) { IVA = 0.0; } else { IVA = 0.16; } IVAPro = (cantidad * Costo) * IVA; Monto = cantidad * Costo; MontoIva = Monto + IVAPro; con.cierraConexion(); return MontoIva; } public double devuelveIVA(String clave, int cantidad) throws SQLException { ConectionDB con = new ConectionDB(); int Tipo = 0; double Costo = 0.0, IVA = 0.0, IVAPro = 0.0; con.conectar(); ResultSet rset = con.consulta("select F_TipMed, F_Costo from tb_medica where F_ClaPro = '" + clave + "'"); while (rset.next()) { Tipo = rset.getInt(1); Costo = rset.getDouble(2); } if (Tipo == 2504) { IVA = 0.0; } else { IVA = 0.16; } IVAPro = (cantidad * Costo) * IVA; con.cierraConexion(); return IVAPro; } public double devuelveCosto(String Clave) throws SQLException { ConectionDB con = new ConectionDB(); double Costo = 0.0; con.conectar(); ResultSet rset = con.consulta("select F_Costo from tb_medica where F_ClaPro = '" + Clave + "'"); while (rset.next()) { Costo = rset.getDouble(1); } return Costo; } public int devuelveIndLote() throws SQLException { ConectionDB con = new ConectionDB(); int indice = 0; con.conectar(); ResultSet rset_Ind = con.consulta("SELECT F_IndLote FROM tb_indice"); while (rset_Ind.next()) { indice = rset_Ind.getInt("F_IndLote"); int FolioLot = indice + 1; con.actualizar("update tb_indice set F_IndLote='" + FolioLot + "'"); } con.cierraConexion(); return indice; } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
[ "chp.chino@gmail.com" ]
chp.chino@gmail.com
c9e9f16593786fbcb379c7cb9b364d4099a40b1e
606bf20c15735aa04b4c20cb5d0c8636e0794e8c
/app/src/main/java/de/tomschachtner/obscontrol/OBSTransitionsButtonsAdapter.java
6af9379cb9dff5a9915f031a00471c518b22f613
[]
no_license
SchachtnerTh/ObsControl2
0ac43f962cd3349ce24357197d3a5825137111e6
75f47d00583217aafdfd8d86583ce6045ecb50b3
refs/heads/master
2023-07-07T20:54:26.702620
2023-06-22T16:41:49
2023-06-22T16:41:49
367,024,964
0
0
null
null
null
null
UTF-8
Java
false
false
9,763
java
package de.tomschachtner.obscontrol; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import org.jetbrains.annotations.NotNull; import de.tomschachtner.obscontrol.obsdata.ObsTransitionsList; public class OBSTransitionsButtonsAdapter extends RecyclerView.Adapter<de.tomschachtner.obscontrol.OBSTransitionsButtonsAdapter.ViewHolder> implements OBSWebSocketClient.ObsTransitionsChangedListener { private ObsTransitionsList mData; private LayoutInflater mInflater; private OnTransitionsClickListener mClickListener; private OnTransitionsLongClickListener mLongClickListener; private Context ctx; /** * The constructor creates the adapter object. * An adapter is a design pattern which connects some view element (here a RecyclerView) to a * data source, like an array or a database. * * During construction of a class instance, we obtain a reference to the LayoutInflater, as that * will be used later to inflate the child layouts for all the elements. * * We also get the list of data (here: an array) which should be included in the RecyclerView * This is also saved as an instance property for later use. * @param context System context (Activity) * @param data Values to be shown in the RecyclerView */ public OBSTransitionsButtonsAdapter(Context context, ObsTransitionsList data) { this.mInflater = LayoutInflater.from(context); this.mData = data; this.ctx = context; } /** * The onCreateViewHolder override makes sure to really inflate the object using the corres- * ponding layout XML file. The method "inflate" does exactly that. The corresponding inflater * is already available at Activity level and can be obtained via the static method * LayoutInflater.from(). This has already be done in the constructor and the inflater was saved * as a class property for later re-use. * * (I think, that here is, where the magic happens: in onCreateViewHolder, the framework * recognizes with type of ViewHolder is to be used (by looking at the template argument from * the class definition (here: <OBSSceneButtonsAdapter.ViewHolder>) and then automatically creates * an instance of that class for every element in the data source that the adapter encounters.) * * @param parent (unknown) * @param viewType (unknown) * @return The newly inflated ViewHolder */ @NonNull @NotNull @Override public de.tomschachtner.obscontrol.OBSTransitionsButtonsAdapter.ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.buttongrid, parent, false); return new OBSTransitionsButtonsAdapter.ViewHolder(view); } /** * In the onBindViewHolder, the contents of the ViewHolder's views are filled with actual values * from the underlying dataset. * * @param holder provides access to the instance of the ViewHolder that is currently being * processed and which should be filled with values. * @param position indicates at which position in the RecyclerView we currently are. This should * help determining which element of the dataset should be used to fill the * ViewHolder's views with. (That might me database IDs or just array indices.) */ @Override public void onBindViewHolder(@NonNull @NotNull de.tomschachtner.obscontrol.OBSTransitionsButtonsAdapter.ViewHolder holder, int position) { holder.myTextView.setText(mData.transitions.get(position)); if (mData.transitions.get(position).equals(mData.getCurrentTransition())) { // holder.myTextView.setBackgroundColor(Color.rgb(0xaa, 0xaa, 0xff)); holder.myTextView.setBackgroundResource(R.drawable.active_transition); holder.myTextView.setTextColor(Color.DKGRAY); } else { // holder.myTextView.setBackgroundColor(Color.rgb(0x00, 0x00, 0xff)); holder.myTextView.setBackgroundResource(R.drawable.non_active_transition); holder.myTextView.setTextColor(Color.BLACK); } holder.myTextView.setOnClickListener(holder); holder.myTextView.setOnLongClickListener(holder); } /** * Returns the total number of items in the data set held by the adapter. * * @return The total number of items in this adapter. */ @Override public int getItemCount() { return mData.transitions.size(); } String getItem(int id) { return mData.transitions.get(id); } /** * Here, we populate the class member mClickListener. This property holds an object which * implements the OnItemClickListener. This method is called from the main activity and provides * an argument which object to use as that listener * * @param itemClickListener is set by the calling object to whatever object that shall be the * listener. */ void setTransitionsClickListener(OnTransitionsClickListener transitionsClickListener) { this.mClickListener = transitionsClickListener; } void setTransitionsLongClickListener(OnTransitionsLongClickListener transitionsLongClickListener) { this.mLongClickListener = transitionsLongClickListener; } @Override public void onObsTransitionsChanged(ObsTransitionsList obsTransitionsList) { //mData = obsScenesList; ((MainActivity)ctx).runOnUiThread(new Runnable() { @Override public void run() { mData = obsTransitionsList; notifyDataSetChanged(); } }); } /** * Here, we define the OnSceneClickListener interface. This interface makes sure, that "everyone" * who "claims to be" an OnSceneClickListener, really implements the onSceneClick method. * This is needed by the OnSceneClickListener in the ViewHolder class, as there, the onSceneClick * method is invoked in an object implementing the OnSceneClickListener interface. */ public interface OnTransitionsClickListener { void onTransitionClick(View view, int position); } public interface OnTransitionsLongClickListener { void onTransitionLongClick(View view, int position); } /** * Using the ViewHolder pattern in Android allows for a smoother scrolling and for less * looking-up views and loading and inflating them. * The below class represents exactly one item in the RecyclerView which - in turn - can consist * of multiple Views. All the views are regarded as one item by the RecyclerView. * For more details, * @see https://stackoverflow.com/questions/21501316/what-is-the-benefit-of-viewholder-pattern-in-android * */ public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { // Here, we define the Views which are part of one item in a RecyclerView layout TextView myTextView; /** * The constructor creates an instance of the class. * It is called for each and every item in the RecyclerView. * First, it calls its super-constructor, then it binds the Views of the ViewHolder * to class variables to allow for value binding later in the callbacks... * * @param itemView is filled by the framework with the actual View to be instantiated */ public ViewHolder(@NonNull @NotNull View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.info_text); // The view gets an OnClickListener attached in order to react upon clicks. // as the ViewHolder class implements the interface View.OnClickListener, the // class itself can be used as the listener (this) itemView.setOnClickListener(this); } /** * This override is called when a View is clicked, as its OnClickListener is set to the * current class, this class implements the View.OnClickListener interface and this * interface guarantees that a method onClick(View view) is provided. This is this very * method... * * In this case, the onClick callback does not really handle the onClick event. * It rather forwards it to another event handler... (Things are getting confusing here...) * * @param view Filled by the framework with the View that has been clicked and whose click * has caused the event handler to be fired. */ @Override public void onClick(View view) { // if the variable mClickListener really contains a valid OnClickListener, // that OnClickListener is called with the View that was clicked and the position // in the list where the user clicked. (This information is not normally available // in a standard OnClickListener, but added there for conveniently working with the // list. if (mClickListener != null) mClickListener.onTransitionClick(view, getAdapterPosition()); } @Override public boolean onLongClick(View view) { if (mLongClickListener != null) mLongClickListener.onTransitionLongClick(view, getAdapterPosition()); return true; } } }
[ "thomas.schachtner@eltheim.de" ]
thomas.schachtner@eltheim.de
5e5fba598b3219764b44905c6897f5e4d654eb1f
cadadc8711553cb14be796f2ddcb50879a0484ed
/Insertion Sort/src/InsertionSort.java
6bf0100e627a647a5efdd709299d49480cb53503
[]
no_license
ikenna83/JavaNOVA
ed91c732544869ea0a5aaaabd836caec76342598
8917e1f468a498631d7756bae6a372afb2146d2e
refs/heads/master
2016-09-05T22:25:08.987704
2014-09-28T02:19:36
2014-09-28T02:19:36
23,746,999
0
0
null
null
null
null
UTF-8
Java
false
false
2,421
java
// insertSort.java // demonstrates insertion sort // to run this program: C>java InsertSortApp //-------------------------------------------------------------- class ArrayIns { private long[] a; // ref to array a private int nElems; // number of data items //-------------------------------------------------------------- public ArrayIns(int max) // constructor { a = new long[max]; // create the array nElems = 0; // no items yet } //-------------------------------------------------------------- public void insert(long value) // put element into array { a[nElems] = value; // insert it nElems++; // increment size } //-------------------------------------------------------------- public void display() // displays array contents { for(int j=0; j<nElems; j++) // for each element, System.out.print(a[j] + " "); // display it System.out.println(""); } //-------------------------------------------------------------- public void insertionSort() { int in, out; for(out=1; out<nElems; out++) // out is dividing line { long temp = a[out]; // remove marked item in = out; // start shifts at out while(in>0 && a[in-1] >= temp) // until one is smaller, { a[in] = a[in-1]; // shift item to right --in; // go left one position } a[in] = temp; // insert marked item } // end for } // end insertionSort() //-------------------------------------------------------------- } // end class ArrayIns //////////////////////////////////////////////////////////////// class insertSort { public static void main(String[] args) { int maxSize = 100; // array size ArrayIns arr; // reference to array arr = new ArrayIns(maxSize); // create the array arr.insert(77); // insert 10 items arr.insert(99); arr.insert(44); arr.insert(55); arr.insert(22); arr.insert(88); arr.insert(11); arr.insert(00); arr.insert(66); arr.insert(33); arr.display(); // display items arr.insertionSort(); // insertion-sort them arr.display(); // display them again } // end main() } // end class InsertSortApp ////////////////////////////////////////////////////////////////Here's the output from the insertSort.java program; it's the same
[ "odi_rodrigue@hotmail.com" ]
odi_rodrigue@hotmail.com
f6bdbc3f49171211333f778c56d7bdbcaf9a0852
2849bd9c835a77260e35449d810483fa43930f5d
/src/main/java/com/zhifou/dao/QuestionDAO.java
e902d69873b4ee1c8f5ef8baff2ab1f4a4fa5dfe
[]
no_license
hellojackhui/web-project-work
4ed67a77d71ceb3292517ce2115ab6136a79e948
f50c20b24d42e7872ee00e4320fc06b115a370bb
refs/heads/master
2020-12-30T15:42:18.460473
2017-06-11T15:31:02
2017-06-11T15:31:02
91,167,067
0
0
null
null
null
null
UTF-8
Java
false
false
1,039
java
package com.zhifou.dao; import com.zhifou.model.Question; import org.apache.ibatis.annotations.*; import java.util.List; /** * Created by nowcoder on 2016/7/2. */ @Mapper public interface QuestionDAO { String TABLE_NAME = " question "; String INSERT_FIELDS = " title, content, created_date, user_id, comment_count "; String SELECT_FIELDS = " id, " + INSERT_FIELDS; @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS, ") values (#{title},#{content},#{createdDate},#{userId},#{commentCount})"}) int addQuestion(Question question); List<Question> selectLatestQuestions(@Param("userId") int userId, @Param("offset") int offset, @Param("limit") int limit); @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " where id=#{id}"}) Question getById(int id); @Update({"update ", TABLE_NAME, " set comment_count = #{commentCount} where id=#{id}"}) int updateCommentCount(@Param("id") int id, @Param("commentCount") int commentCount); }
[ "HUIJIAWEI@hotmail.com" ]
HUIJIAWEI@hotmail.com
5ab60940179cd7fa716bba7aa67e3465ff31f874
7b73756ba240202ea92f8f0c5c51c8343c0efa5f
/classes5/hxy.java
5c8735df077100fbbe7221d148895af9995aa6d1
[]
no_license
meeidol-luo/qooq
588a4ca6d8ad579b28dec66ec8084399fb0991ef
e723920ac555e99d5325b1d4024552383713c28d
refs/heads/master
2020-03-27T03:16:06.616300
2016-10-08T07:33:58
2016-10-08T07:33:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,323
java
import com.tencent.biz.pubaccount.readinjoy.common.ReadInJoyUtils; import com.tencent.biz.pubaccount.readinjoy.model.ArticleInfoModule; import com.tencent.biz.pubaccount.readinjoy.struct.ArticleInfo; import com.tencent.biz.pubaccount.readinjoy.struct.DislikeInfo; import com.tencent.mobileqq.app.QQAppInterface; import com.tencent.mobileqq.hotpatch.NotVerifyClass; import com.tencent.qphone.base.util.QLog; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class hxy implements Runnable { public hxy(ArticleInfoModule paramArticleInfoModule, long paramLong1, int paramInt, byte[] paramArrayOfByte, boolean paramBoolean1, List paramList1, boolean paramBoolean2, long paramLong2, List paramList2) { paramBoolean1 = NotVerifyClass.DO_VERIFY_CLASS; } public void run() { boolean bool3 = false; if (this.jdField_a_of_type_Long == -1L) {} StringBuilder localStringBuilder; int i; for (boolean bool1 = true;; bool1 = false) { this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyModelArticleInfoModule.a(Integer.valueOf(this.jdField_a_of_type_Int), this.jdField_a_of_type_ArrayOfByte); if (!this.jdField_a_of_type_Boolean) { break label408; } localStringBuilder = new StringBuilder("\n"); if (this.jdField_a_of_type_JavaUtilList == null) { break label261; } localObject1 = this.jdField_a_of_type_JavaUtilList.iterator(); i = 0; if (!((Iterator)localObject1).hasNext()) { break label261; } localObject2 = (ArticleInfo)((Iterator)localObject1).next(); localStringBuilder.append("article【" + i + "】 id : " + ((ArticleInfo)localObject2).mArticleID + " seq : " + ((ArticleInfo)localObject2).mRecommendSeq + " title : " + ReadInJoyUtils.c(((ArticleInfo)localObject2).mTitle)); if ((!QLog.isColorLevel()) || (((ArticleInfo)localObject2).mDislikeInfos == null) || (((ArticleInfo)localObject2).mDislikeInfos.size() <= 0)) { break label251; } localStringBuilder.append(" dislik【 "); localObject2 = ((ArticleInfo)localObject2).mDislikeInfos.iterator(); while (((Iterator)localObject2).hasNext()) { localStringBuilder.append(((DislikeInfo)((Iterator)localObject2).next()).b); localStringBuilder.append(","); } } localStringBuilder.append("】\n"); for (;;) { i += 1; break; label251: localStringBuilder.append("\n"); } label261: Object localObject1 = ArticleInfoModule.jdField_a_of_type_JavaLangString; Object localObject2 = new StringBuilder().append("handleRefreshChannel success=").append(this.jdField_a_of_type_Boolean).append(" channelId=").append(this.jdField_a_of_type_Int).append(" noMoreData=").append(this.jdField_b_of_type_Boolean).append(" beginRecommendSeq=").append(this.jdField_a_of_type_Long).append(" endRecommendSeq=").append(this.jdField_b_of_type_Long).append(" isInMsgTab : "); boolean bool2 = bool3; if (this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyModelArticleInfoModule.jdField_a_of_type_ComTencentCommonAppAppInterface != null) { bool2 = bool3; if ((this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyModelArticleInfoModule.jdField_a_of_type_ComTencentCommonAppAppInterface instanceof QQAppInterface)) { bool2 = true; } } QLog.i((String)localObject1, 1, bool2 + " isRefresh : " + bool1 + ", " + localStringBuilder.toString()); label408: if (bool1) { ArticleInfoModule.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyModelArticleInfoModule, this.jdField_a_of_type_Boolean, this.jdField_a_of_type_Int, this.jdField_b_of_type_Boolean, this.jdField_a_of_type_JavaUtilList, this.jdField_a_of_type_Long, this.jdField_b_of_type_Long, this.jdField_b_of_type_JavaUtilList); return; } ArticleInfoModule.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyModelArticleInfoModule, this.jdField_a_of_type_Boolean, this.jdField_a_of_type_Int, this.jdField_b_of_type_Boolean, this.jdField_a_of_type_JavaUtilList, this.jdField_a_of_type_Long, this.jdField_b_of_type_Long); } } /* Location: E:\apk\QQ_91\classes5-dex2jar.jar!\hxy.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "1776098770@qq.com" ]
1776098770@qq.com
892f5c3be3b6caa95b9dfdf43248e8db304591c2
325a7c0eaf0ce4adaa7ab0ad60162bb7ec3a5fd1
/java8/src/streamProblems/EmployeedDB.java
316104bad2cd55a6e2625314536770d7a857bd5c
[]
no_license
kbhatt23/goldman-assignments
18d3c74f606a6514a417a4fdaeadeb9b88a3d49d
571210c5fba7a5ccc4f9f96b968b0e9c29da2291
refs/heads/master
2020-09-10T22:40:31.832023
2019-11-29T10:25:46
2019-11-29T10:25:46
221,854,658
0
0
null
null
null
null
UTF-8
Java
false
false
1,986
java
package streamProblems; import java.util.ArrayList; import java.util.List; public class EmployeedDB { public static List<Employee> fetchAllEmplyees() { List<Employee> employeeList = new ArrayList<Employee>(); employeeList.add(new Employee(111, "Jiya Brein", 32, "Female", "HR", 2011, 25000.0)); employeeList.add(new Employee(122, "Paul Niksui", 25, "Male", "Sales And Marketing", 2015, 13500.0)); employeeList.add(new Employee(133, "Martin Theron", 29, "Male", "Infrastructure", 2012, 18000.0)); employeeList.add(new Employee(144, "Murali Gowda", 28, "Male", "Product Development", 2014, 32500.0)); employeeList.add(new Employee(155, "Nima Roy", 27, "Female", "HR", 2013, 22700.0)); employeeList.add(new Employee(166, "Iqbal Hussain", 43, "Male", "Security And Transport", 2016, 10500.0)); employeeList.add(new Employee(177, "Manu Sharma", 35, "Male", "Account And Finance", 2010, 27000.0)); employeeList.add(new Employee(188, "Wang Liu", 31, "Male", "Product Development", 2015, 34500.0)); employeeList.add(new Employee(199, "Amelia Zoe", 24, "Female", "Sales And Marketing", 2016, 11500.0)); employeeList.add(new Employee(200, "Jaden Dough", 38, "Male", "Security And Transport", 2015, 11000.5)); employeeList.add(new Employee(211, "Jasna Kaur", 27, "Female", "Infrastructure", 2014, 15700.0)); employeeList.add(new Employee(222, "Nitin Joshi", 25, "Male", "Product Development", 2016, 28200.0)); employeeList.add(new Employee(233, "Jyothi Reddy", 27, "Female", "Account And Finance", 2013, 21300.0)); employeeList.add(new Employee(244, "Nicolus Den", 24, "Male", "Sales And Marketing", 2017, 10700.5)); employeeList.add(new Employee(255, "Ali Baig", 23, "Male", "Infrastructure", 2018, 34503.0)); employeeList.add(new Employee(266, "Sanvi Pandey", 26, "Female", "Product Development", 2015, 34502.0)); employeeList.add(new Employee(277, "Anuj Chettiar", 31, "Male", "Product Development", 2012, 34501.0)); return employeeList; } }
[ "kanbhatt1@WKWIN9908215.global.publicisgroupe.net" ]
kanbhatt1@WKWIN9908215.global.publicisgroupe.net
7c143052b03cea26504280fb8aa235ab54db6808
1d39ce0b8c1a8a7dac4d21e468ae7f1b564705a7
/app/src/main/java/com/example/ktmuyoklama/viewModel/studentViewModel/SelectLessonViewModel.java
33c9895f67d2d1aa0552f4621a4158bfbf6833fb
[]
no_license
rysbekovaroza25/ktmu
4aa44f4c9e3d2fc16f3fb8a975ec2757194e5900
5933f7644c74505968f29cdee0538f6be2100340
refs/heads/main
2023-05-07T23:19:56.107326
2021-06-01T12:00:38
2021-06-01T12:00:38
372,812,081
0
0
null
null
null
null
UTF-8
Java
false
false
3,179
java
package com.example.ktmuyoklama.viewModel.studentViewModel; import android.util.Log; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.example.ktmuyoklama.adapter.studentAdapter.SelectLessonAdapter; import com.example.ktmuyoklama.data.model.studentPageModel.RegisterLessonStudents; import com.example.ktmuyoklama.data.response.SelectLessonStudent; import com.example.ktmuyoklama.utils.RetrofitService; import com.example.ktmuyoklama.view.MainActivity; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SelectLessonViewModel extends ViewModel { public SelectLessonViewModel(){ super(); } @Override protected void onCleared() { super.onCleared(); } public LiveData<List<SelectLessonStudent>> getLiveDataLessonRegister() { MutableLiveData<List<SelectLessonStudent>> liveData = new MutableLiveData<>(); Call<List<SelectLessonStudent>> getDataCall = RetrofitService.getInstance().getApiService().selectLessonStudent(MainActivity.getToken()); getDataCall.enqueue(new Callback<List<SelectLessonStudent>>(){ @Override public void onResponse(Call<List<SelectLessonStudent>> call, Response<List<SelectLessonStudent>> response) { try { if (response.code() == 200) { liveData.setValue(response.body()); } else { Log.d("TAG", "Response from the server: " + response.code()); } } catch (Exception e) { Log.d("TAG", "error: " + e); } } @Override public void onFailure(Call<List<SelectLessonStudent>> call, Throwable t) { Log.d("TAG", "onFailure: Data " + t.getMessage()); } }); return liveData; } public LiveData<RegisterLessonStudents> getLiveDataSelectLesson(RegisterLessonStudents registerLessonStudents) { MutableLiveData<RegisterLessonStudents> liveData = new MutableLiveData<>(); Call<RegisterLessonStudents> getDataCall = RetrofitService.getInstance().getApiService().registerLessonStudents(MainActivity.getToken(), registerLessonStudents); getDataCall.enqueue(new Callback<RegisterLessonStudents>(){ @Override public void onResponse(Call<RegisterLessonStudents> call, Response<RegisterLessonStudents> response) { try { if (response.code() == 200) { liveData.setValue(response.body()); } else { Log.d("TAG", "Response from the server: " + response.code()); } } catch (Exception e) { Log.d("TAG", "error: " + e); } } @Override public void onFailure(Call<RegisterLessonStudents> call, Throwable t) { Log.d("TAG", "onFailure: Data " + t.getMessage()); } }); return liveData; } }
[ "rysbekovaroza97@gmail.com" ]
rysbekovaroza97@gmail.com
0d443c87da0ce928653c647fa5d6e21495fd9a58
300dfa1c003aaa705189e8d91a0e1e28b49dde63
/alura-springboot/gerenciador/src/br/com/alura/gerenciador/acao/NovaEmpresa.java
8ecd1c5e477bff29953c76aeaf72cf26bd29c25c
[]
no_license
rafaelcardosodev/alura
898d6431ff2bc5662758c5e9cee3ef7db0bc3213
8800b5a68c0a99bf870b09d71155c1e343176447
refs/heads/master
2023-06-12T12:00:58.475965
2021-07-01T16:06:52
2021-07-01T16:06:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,203
java
package br.com.alura.gerenciador.acao; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import br.com.alura.gerenciador.model.Banco; import br.com.alura.gerenciador.model.Empresa; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class NovaEmpresa { public String executa(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Cadastrando nova empresa"); String nomeEmpresa = request.getParameter("nome"); String paramDataEmpresa = request.getParameter("data"); Date dataAbertura = null; try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); dataAbertura = sdf.parse(paramDataEmpresa); } catch (ParseException e) { throw new ServletException(e); } Empresa empresa = new Empresa(); empresa.setNome(nomeEmpresa); empresa.setDataAbertura(dataAbertura); Banco banco = new Banco(); banco.adiciona(empresa); request.setAttribute("empresa", empresa.getNome()); return "redirect:entrada?acao=lista-empresas"; } }
[ "rafaelgremista2010@gmail.com" ]
rafaelgremista2010@gmail.com
a824c553e95b635f37e89e11eb502c71d36c1085
cd9e792971d9a1d0f85de560c4684d4fddf6ebc0
/xcmis-search-model/src/main/java/org/xcmis/search/model/constraint/DescendantNode.java
37b2208ea7fe957baa33c71babe5af6ff5dcf3e6
[]
no_license
exodev/xcmis
49d82868798a7b5506e6a399384bbf0d2b4b4179
55ac9d26080f1dfef65e3d5377905cf86a075000
refs/heads/master
2021-01-16T19:21:28.094467
2016-04-04T08:43:00
2016-04-04T08:43:00
7,485,023
0
0
null
null
null
null
UTF-8
Java
false
false
3,865
java
/* * Copyright (C) 2009 eXo Platform SAS. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xcmis.search.model.constraint; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.xcmis.search.QueryObjectModelVisitor; import org.xcmis.search.VisitException; import org.xcmis.search.Visitors; import org.xcmis.search.model.source.SelectorName; /** * A constraint requiring that the selected node is a descendant of the node reachable by the supplied absolute path */ public class DescendantNode extends Constraint { private static final long serialVersionUID = 1L; private final String ancestorPath; private final SelectorName selectorName; private final int hcode; /** * Create a constraint requiring that the node identified by the selector is a descendant of the node reachable by the * supplied absolute path. * * @param selectorName the name of the selector * @param ancestorPath the absolute path to the ancestor */ public DescendantNode(SelectorName selectorName, String ancestorPath) { Validate.notNull(selectorName, "The selectorName argument may not be null"); Validate.notNull(ancestorPath, "The ancestorPath argument may not be null"); this.selectorName = selectorName; this.ancestorPath = ancestorPath; this.hcode = new HashCodeBuilder() .append(selectorName) .append(ancestorPath).toHashCode(); } /** * @see org.xcmis.search.model.QueryElement#accept(org.xcmis.search.QueryObjectModelVisitor) */ public void accept(QueryObjectModelVisitor visitor) throws VisitException { visitor.visit(this); } /** * {@inheritDoc} * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } DescendantNode rhs = (DescendantNode)obj; return new EqualsBuilder() .append(selectorName, rhs.selectorName) .append(ancestorPath, rhs.ancestorPath) .isEquals(); } /** * Get the path of the node that is to be the ancestor of the target node. * * @return the path of the ancestor node; never null */ public final String getAncestorPath() { return ancestorPath; } /** * Get the name of the selector for the node. * * @return the selector name; never null */ public final SelectorName getSelectorName() { return selectorName; } /** * {@inheritDoc} * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return hcode; } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return Visitors.readable(this); } }
[ "ksmster@gmail.com" ]
ksmster@gmail.com
9e3065703830509be4ae01e402238034d778ddef
953e9430031fab7405d3e39c36798d5f4c54eaf0
/amino-cbbs/src/main/java/org/amino/alg/sort/DefaultSorter.java
4ffdd5aeaaa4c5663a62c08e8eeb7e2d7e5b4eec
[ "Apache-2.0" ]
permissive
javawp/amino-cbbs
210c09e58e4908490264659897c1784b56084315
068e6776087b07fe54fa19f5d1a21899ff78c338
refs/heads/master
2021-01-10T08:56:33.056914
2015-12-24T11:42:14
2015-12-24T11:42:14
48,534,377
2
0
null
null
null
null
UTF-8
Java
false
false
9,581
java
/* * Copyright (c) 2007 IBM Corporation * * 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.amino.alg.sort; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.ListIterator; /** * This is the simple default sorter class. Lots of room for improving * the implementation. Uses the array and list sorting routines. Provides * functions to sort by ascending and descending orders. */ public class DefaultSorter extends AbstractSorter { /** * * @param a is the byte array to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void reverse(byte[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * * @param a is the character array to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void reverse(char[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * * @param a is the short array to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void reverse(short[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * * @param a is the int array to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void reverse(int[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * * @param a is the long array to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void reverse(long[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * * @param a is the float array to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void reverse(float[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * * @param a is the double array to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void reverse(double[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * @param <T> data type * @param a is the array of Comparable objects to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public <T extends Comparable<T>> void reverse(T[] a, int from, int to) { Arrays.sort(a,from,to); final int len = to-from+1; for (int i=from, j = to-1; i < from+len/2; i++, j--) swap(a, i, j); } /** * @param <T> data type * @param a is the List of Comparable objects to be sorted in a descending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public <T extends Comparable<T>> void reverse(List<T> a, int from, int to) { List<T> aa = a.subList(from,to); Collections.sort(aa); ListIterator<T> ali = a.listIterator(to); ListIterator<T> aali = aa.listIterator(); for (int i=from; i<to; i++) { ali.previous(); ali.set(aali.next()); }; } /** * * @param a is the byte array to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void sort(byte[] a, int from, int to) { Arrays.sort(a,from,to); } /** * * @param a is the character array to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void sort(char[] a, int from, int to) { Arrays.sort(a,from,to); } /** * * @param a is the short array to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void sort(short[] a, int from, int to) { Arrays.sort(a,from,to); } /** * * @param a is the int array to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void sort(int[] a, int from, int to) { Arrays.sort(a,from,to); } /** * * @param a is the long array to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void sort(long[] a, int from, int to) { Arrays.sort(a,from,to); } /** * * @param a is the float array to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void sort(float[] a, int from, int to) { Arrays.sort(a,from,to); } /** * * @param a is the double array to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public void sort(double[] a, int from, int to) { Arrays.sort(a,from,to); } /** * @param <T> data type * @param a is an array of Comparable objects to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public <T extends Comparable<T>> void sort(T[] a, int from, int to) { Arrays.sort(a,from,to); } /** * @param <T> data type * @param a is an array of Comparable objects to be sorted * @param c is the Comparator * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public <T extends Comparable<T>> void sort(T[] a, int from, int to, Comparator<T> c) { Arrays.sort(a,from,to,c); } /** * @param <T> data type * @param a is a List of Comparable objects to be sorted in an ascending order * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public <T extends Comparable<T>> void sort(List<T> a, int from, int to) { List<T> aa = a.subList(from,to); Collections.sort(aa); ListIterator<T> ali = a.listIterator(to); ListIterator<T> aali = aa.listIterator(); for (int i=from; i<to; i++) { ali.next(); ali.set(aali.next()); }; } /** * @param <T> data type * @param a is a List of Comparable objects to be sorted * @param c is the Comparator * @param from is the start index of array to be sorted * @param to is the end index of array to be sorted * */ public <T extends Comparable<T>> void sort(List<T> a, int from, int to, Comparator<T> c) { List<T> aa = a.subList(from,to); Collections.sort(aa,c); ListIterator<T> ali = a.listIterator(to); ListIterator<T> aali = aa.listIterator(); for (int i=from; i<to; i++) { ali.next(); ali.set(aali.next()); }; } /** * @param <T> data type * @param a is a List of Comparable objects to be sorted in an ascending order * */ public <T extends Comparable<T>> void sort(List<T> a) { Collections.sort(a); } /** * @param <T> data type * @param a is a List of Comparable objects to be sorted * @param c is the Comparator * */ public <T extends Comparable<T>> void sort(List<T> a, Comparator<T> c) { Collections.sort(a,c); } /** * * @param p is the returned permuted index vector * @param a is the array to be sorted, based on which the permuted index vector is generated * @param from is the start index * @param to is the end index * */ public void sortp(int[] p, int[] a, int from, int to) { // FIXME: Just a simple bubble sort for now to keep it simple for (int i=from; i<to; i++) p[i-from] = i; for (int i=0; i<to-from-1; i++) for (int j=i+1; i<to-from; j++) if (a[p[i]] > a[p[j]]) swap(p,i,j); } }
[ "javawp@icloud.com" ]
javawp@icloud.com
caf11fd94b1e04098f675ebeaf252059d85f0849
196b9023ea3870dadc0a9cdbc4c56d4ef7f83636
/CaretakersApp/app/src/main/java/seniorproject/caretakers/caretakersapp/ui/actvities/AddGroceryItemActivity.java
19985bfaf9b8230847bd001a315d903736edb146
[]
no_license
AssistEm/assistem-android
a9484c64eff20c55e79fe1f158b9b3a83c671311
fa4b6e3415f7bc05d3e702090207932f3275fac3
refs/heads/master
2021-01-21T04:28:03.211686
2016-08-22T03:01:26
2016-08-22T03:01:26
44,981,247
2
0
null
2016-04-06T21:56:40
2015-10-26T16:20:36
Java
UTF-8
Java
false
false
10,109
java
package seniorproject.caretakers.caretakersapp.ui.actvities; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.text.InputType; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.doomonafireball.betterpickers.datepicker.DatePickerBuilder; import com.doomonafireball.betterpickers.datepicker.DatePickerDialogFragment; import com.doomonafireball.betterpickers.radialtimepicker.RadialTimePickerDialog; import com.doomonafireball.betterpickers.timepicker.TimePickerDialogFragment; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import seniorproject.caretakers.caretakersapp.R; import seniorproject.caretakers.caretakersapp.data.handlers.EventHandler; import seniorproject.caretakers.caretakersapp.data.handlers.GroceryHandler; /** * Activity that presents the UI for adding a GroceryItem */ public class AddGroceryItemActivity extends BaseActivity implements DatePickerDialogFragment.DatePickerDialogHandler, TimePickerDialogFragment.TimePickerDialogHandler, RadialTimePickerDialog.OnTimeSetListener { //Results for this activity that will be passed to calling activity public static final int GROCERY_ITEM_ADDED_RESULT = 10; EditText mTitleEdit; EditText mDescriptionEdit; EditText mQuantityEdit; EditText mLocationEdit; EditText mTimeEdit; EditText mDateEdit; Button mSubmitButton; //Currently selected start and end times and date (may be null if none are selected) Integer mHour, mMinute; Integer mYear, mMonth, mDay; /** * Listener for a focus change on a view. Used to open a date picker when the Date EditText is * selected */ View.OnFocusChangeListener mDateFocusListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if(hasFocus) { switch(view.getId()) { case R.id.date: openDatePicker(view.getId(), mYear, mMonth, mDay); break; } } } }; /** * Listener for a focus change on a view. Used to open a time picker when the Time EditText is * selected */ View.OnFocusChangeListener mTimeFocusListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if(hasFocus) { switch(view.getId()) { case R.id.time: openTimePicker(view.getId(), mHour, mMinute); break; } } } }; /** * Listener for a click on a view. Used to open a date picker when the Date EditText is clicked. */ View.OnClickListener mDateClickListener = new View.OnClickListener() { @Override public void onClick(View view) { switch(view.getId()) { case R.id.date: openDatePicker(view.getId(), mYear, mMonth, mDay); break; } } }; /** * Listener for a click on a view. Used to open a time picker when the Time EditText is clicked. */ View.OnClickListener mTimeClickListener = new View.OnClickListener() { @Override public void onClick(View view) { switch(view.getId()) { case R.id.start_time: openTimePicker(view.getId(), mHour, mMinute); break; } } }; /** * Click listener for the submit button. Validates the input, the initiates a request to add * a grocery item via the GroceryHandler singleton */ View.OnClickListener mSubmitClickListener = new View.OnClickListener() { @Override public void onClick(View view) { String title = mTitleEdit.getText().toString(); String description = mDescriptionEdit.getText().toString(); String location = mLocationEdit.getText().toString(); String quantity = mQuantityEdit.getText().toString(); if(title.isEmpty() || mYear == null || mHour == null) { return; } Calendar time = Calendar.getInstance(); time.set(mYear, mMonth, mDay, mHour, mMinute, 0); time.set(Calendar.MILLISECOND, 0); GroceryHandler.getInstance().addItem(AddGroceryItemActivity.this, title, description, quantity, location, time, mListener); } }; /** * GroceryListener for receiving a successful GroceryItem addition request */ GroceryHandler.GroceryListener mListener = new GroceryHandler.GroceryListener() { @Override public void onGroceryItemAdded() { setResult(GROCERY_ITEM_ADDED_RESULT); finish(); } }; /** * Callback for when the activity is first created. Initializes and finds views. * @param savedInstanceState Saved instance state of the activity */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTitleEdit = (EditText) findViewById(R.id.title); mDescriptionEdit = (EditText) findViewById(R.id.description); mQuantityEdit = (EditText) findViewById(R.id.quantity); mLocationEdit = (EditText) findViewById(R.id.location); mTimeEdit = (EditText) findViewById(R.id.time); mTimeEdit.setInputType(InputType.TYPE_NULL); mTimeEdit.setOnFocusChangeListener(mTimeFocusListener); mTimeEdit.setOnClickListener(mTimeClickListener); mDateEdit = (EditText) findViewById(R.id.date); mDateEdit.setInputType(InputType.TYPE_NULL); mDateEdit.setOnFocusChangeListener(mDateFocusListener); mDateEdit.setOnClickListener(mDateClickListener); mSubmitButton = (Button) findViewById(R.id.submit); mSubmitButton.setOnClickListener(mSubmitClickListener); } @Override public int getLayoutResource() { return R.layout.activity_add_grocery_item; } /** * Callback for when a DateDialog finishes. Receives the date set, and stores it and updates views * accordingly * @param reference Reference for the context in which the DateDialog was spawned * @param year Year selected * @param month Month selected * @param day Day selected */ @Override public void onDialogDateSet(int reference, int year, int month, int day) { GregorianCalendar calendar = new GregorianCalendar(year, month, day); switch(reference) { case R.id.date: mDateEdit.setText((calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + calendar.get(Calendar.YEAR)); mYear = year; mMonth = month; mDay = day; return; } } /** * Callback for when a TimeDialog finishes. Receives the time set, and stores it and updates * views accordingly * @param reference Reference for the context in which the DateDialog was spawned * @param hour Hour selected * @param minute Minute selected */ public void onDialogTimeSet(int reference, int hour, int minute) { Date date = new Date(); date.setMinutes(minute); date.setHours(hour); switch(reference) { case R.id.time: mTimeEdit.setText(DateUtils .formatDateTime(this, date.getTime(), DateUtils.FORMAT_SHOW_TIME)); mHour = hour; mMinute = minute; } } /** * Callback for the RadialTimePickerDialog library. Receives selected hour and minute and * passes them to the onDialogTimeSet method * @param radialTimePickerDialog Dialog reference * @param hour Hour selected * @param minute Minute selected */ @Override public void onTimeSet(RadialTimePickerDialog radialTimePickerDialog, int hour, int minute) { Bundle bundle = radialTimePickerDialog.getArguments(); int reference = bundle.getInt("reference"); onDialogTimeSet(reference, hour, minute); } /** * Method to open the date picker dialog * @param reference Reference to use for this dialog * @param year Previously selected year * @param month Previously selected month * @param day Previously selected day */ private void openDatePicker(int reference, Integer year, Integer month, Integer day) { DatePickerBuilder builder = new DatePickerBuilder() .setFragmentManager(getSupportFragmentManager()) .setStyleResId(R.style.DateTimePickers) .setReference(reference) .addDatePickerDialogHandler(AddGroceryItemActivity.this); if(year != null && month != null && day != null) { builder.setYear(year); builder.setMonthOfYear(month); builder.setDayOfMonth(day); } builder.show(); } /** * Method to open the time picker dialog * @param reference Reference to use for this dialog * @param hour Previously selected hour * @param minute Previously selected minute */ private void openTimePicker(int reference, Integer hour, Integer minute) { int hourInt = hour == null ? 0 : hour; int minuteInt = minute == null ? 0 : minute; Bundle bundle = new Bundle(); bundle.putInt("reference", reference); RadialTimePickerDialog dialog = RadialTimePickerDialog .newInstance(this, hourInt, minuteInt, DateFormat.is24HourFormat(this)); dialog.setArguments(bundle); dialog.show(getSupportFragmentManager(), "radial_dialog"); } }
[ "jasmsu@gmail.com" ]
jasmsu@gmail.com
1138784e51aa2ca0e4cfb3c4ae7d48df0440d3d1
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/28/28_4dde59afb2271848dfe46520baa78dc177207aed/KmeliaRequestRouter/28_4dde59afb2271848dfe46520baa78dc177207aed_KmeliaRequestRouter_t.java
63dd8a0c0050e2899a93ddbe420029b2428a84c1
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
122,723
java
/** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.kmelia.servlets; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.fileupload.FileItem; import org.xml.sax.SAXException; import com.silverpeas.form.DataRecord; import com.silverpeas.form.Form; import com.silverpeas.form.FormException; import com.silverpeas.form.PagesContext; import com.silverpeas.form.RecordSet; import com.silverpeas.kmelia.KmeliaConstants; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelper; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelperContext; import com.silverpeas.pdc.web.PdcClassificationEntity; import com.silverpeas.publicationTemplate.PublicationTemplate; import com.silverpeas.publicationTemplate.PublicationTemplateException; import com.silverpeas.publicationTemplate.PublicationTemplateImpl; import com.silverpeas.publicationTemplate.PublicationTemplateManager; import com.silverpeas.thumbnail.ThumbnailRuntimeException; import com.silverpeas.thumbnail.control.ThumbnailController; import com.silverpeas.thumbnail.model.ThumbnailDetail; import com.silverpeas.util.FileUtil; import com.silverpeas.util.ForeignPK; import com.silverpeas.util.MimeTypes; import com.silverpeas.util.StringUtil; import com.silverpeas.util.ZipManager; import com.silverpeas.util.i18n.I18NHelper; import com.silverpeas.util.web.servlet.FileUploadUtil; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter; import com.stratelia.silverpeas.selection.Selection; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.silverpeas.versioning.model.DocumentVersion; import com.stratelia.silverpeas.wysiwyg.control.WysiwygController; import com.stratelia.webactiv.SilverpeasRole; import com.stratelia.webactiv.beans.admin.ProfileInst; import com.stratelia.webactiv.kmelia.KmeliaSecurity; import com.stratelia.webactiv.kmelia.control.KmeliaSessionController; import com.stratelia.webactiv.kmelia.control.ejb.KmeliaHelper; import com.stratelia.webactiv.kmelia.model.FileFolder; import com.stratelia.webactiv.kmelia.model.KmeliaPublication; import com.stratelia.webactiv.kmelia.model.TopicDetail; import com.stratelia.webactiv.kmelia.model.updatechain.FieldUpdateChainDescriptor; import com.stratelia.webactiv.kmelia.model.updatechain.Fields; import com.stratelia.webactiv.kmelia.servlets.handlers.StatisticRequestHandler; import com.stratelia.webactiv.util.ClientBrowserUtil; import com.stratelia.webactiv.util.DateUtil; import com.stratelia.webactiv.util.FileRepositoryManager; import com.stratelia.webactiv.util.GeneralPropertiesManager; import com.stratelia.webactiv.util.ResourceLocator; import com.stratelia.webactiv.util.WAAttributeValuePair; import com.stratelia.webactiv.util.fileFolder.FileFolderManager; import com.stratelia.webactiv.util.node.model.NodeDetail; import com.stratelia.webactiv.util.node.model.NodePK; import com.stratelia.webactiv.util.publication.info.model.InfoDetail; import com.stratelia.webactiv.util.publication.info.model.InfoImageDetail; import com.stratelia.webactiv.util.publication.info.model.InfoTextDetail; import com.stratelia.webactiv.util.publication.info.model.ModelDetail; import com.stratelia.webactiv.util.publication.model.Alias; import com.stratelia.webactiv.util.publication.model.CompletePublication; import com.stratelia.webactiv.util.publication.model.PublicationDetail; public class KmeliaRequestRouter extends ComponentRequestRouter<KmeliaSessionController> { private static final long serialVersionUID = 1L; private static final StatisticRequestHandler statisticRequestHandler = new StatisticRequestHandler(); /** * This method creates a KmeliaSessionController instance * @param mainSessionCtrl The MainSessionController instance * @param context Context of current component instance * @return a KmeliaSessionController instance */ @Override public KmeliaSessionController createComponentSessionController( MainSessionController mainSessionCtrl, ComponentContext context) { return new KmeliaSessionController(mainSessionCtrl, context); } /** * This method has to be implemented in the component request rooter class. returns the session * control bean name to be put in the request object ex : for almanach, returns "almanach" */ @Override public String getSessionControlBeanName() { return "kmelia"; } /** * This method has to be implemented by the component request rooter it has to compute a * destination page * @param function The entering request function ( : "Main.jsp") * @param kmelia The component Session Control, build and initialised. * @param request The entering request. The request rooter need it to get parameters * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, KmeliaSessionController kmelia, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", kmaxMode); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("validateClassification")) { String[] publicationIds = request.getParameterValues("pubid"); Collection<KmeliaPublication> publications = kmelia.getPublications(asPks(kmelia. getComponentId(), publicationIds)); request.setAttribute("Context", GeneralPropertiesManager.getString("ApplicationURL")); request.setAttribute("PublicationsDetails", publications); destination = rootDestination + "validateImportedFilesClassification.jsp"; } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = kmelia.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = NodePK.ROOT_NODE_ID; } } kmelia.setCurrentFolderId(topicId, true); resetWizard(kmelia); request.setAttribute("CurrentFolderId", topicId); request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis()); request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled()); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", kmelia.isTopicHaveUpdateChainDescriptor()); request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", kmelia.getUserDetail().isAccessGuest()); request.setAttribute("RightsOnTopicsEnabled", kmelia.isRightsOnTopicsEnabled()); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeviewUsed()) { destination = rootDestination + "treeview.jsp"; } else if (kmelia.isTreeStructure()) { destination = rootDestination + "oneLevel.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } else if (function.equals("GoToCurrentTopic")) { if (!NodePK.ROOT_NODE_ID.equals(kmelia.getCurrentFolderId())) { request.setAttribute("Id", kmelia.getCurrentFolderId()); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type != null && ("Publication".equals(type) || "com.stratelia.webactiv.calendar.backbone.TodoDetail".equals(type) || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { processPath(kmelia, id); if ("Attachment".equals(type)) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if ("Document".equals(type)) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { // we have to find which page contains the right publication List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); KmeliaPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getDetail().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if ("Node".equals(type)) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", kmelia, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if ("Wysiwyg".equals(type)) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); kmelia.setSessionPublication(kmeliaPublication); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String id = request.getParameter("PubId"); if (StringUtil.isDefined(id)) { request.setAttribute("PubId", id); } request.setAttribute("Wizard", kmelia.getWizard()); List<NodeDetail> path = kmelia.getTopicPath(kmelia.getCurrentFolderId()); request.setAttribute("Path", path); request.setAttribute("Profile", kmelia.getProfile()); String action = (String) request.getAttribute("Action"); if (!StringUtil.isDefined(action)) { action = "UpdateView"; request.setAttribute("Action", action); } if ("UpdateView".equals(action)) { request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } else { // case of creation request.setAttribute("TaxonomyOK", true); request.setAttribute("ValidatorsOK", true); } destination = rootDestination + "publicationManager.jsp"; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK(). getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getCurrentFolder(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); KmeliaPublication kmeliaPublication = kmelia.getPublication(cloneId); kmelia.setSessionClone(kmeliaPublication); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } if (!kmaxMode) { boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath || KmeliaHelper.isToValidateFolder(kmelia.getCurrentFolderId())) { processPath(kmelia, id); } else { processPath(kmelia, null); } } KmeliaPublication kmeliaPublication = null; if (StringUtil.isDefined(id)) { kmeliaPublication = kmelia.getPublication(id, true); kmelia.setSessionPublication(kmeliaPublication); PublicationDetail pubDetail = kmeliaPublication.getDetail(); if (pubDetail.haveGotClone()) { KmeliaPublication clone = kmelia.getPublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { kmeliaPublication = kmelia.getSessionPublication(); id = kmeliaPublication.getDetail().getPK().getId(); } if (toolboxMode) { request.setAttribute("PubId", id); destination = getDestination("publicationManager.jsp", kmelia, request); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, kmeliaPublication. getDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = kmeliaPublication.getCompleteDetail().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("PubId", id); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", kmelia.getValidationType()); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", kmelia.isWriterApproval(id)); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // check is requested publication is an alias checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", kmelia.getRang()); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size()); } else { request.setAttribute("NbPublis", 1); } putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); // option Actualités décentralisées request.setAttribute("NewsManage", kmelia.isNewsManage()); if (kmelia.isNewsManage()) { request.setAttribute("DelegatedNews", kmelia.getDelegatedNews(id)); request .setAttribute("IsBasket", NodePK.BIN_NODE_ID.equals(kmelia.getCurrentFolderId())); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", kmelia, request); } else { String pubId = kmelia.getSessionPubliOrClone().getDetail().getPK().getId(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, kmelia, request); } else { request.setAttribute("PubId", pubId); destination = getDestination("publicationManager.jsp", kmelia, request); } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias KmeliaPublication kmeliaPublication = kmelia.getSessionPublication(); checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { request.setAttribute("Action", "New"); destination = getDestination("publicationManager", kmelia, request); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication String positions = FileUploadUtil.getParameter(parameters, "Positions"); PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification(); if (StringUtil.isDefined(positions)) { withClassification = PdcClassificationEntity.fromJSON(positions); } PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail, withClassification); // create vignette if exists processVignette(parameters, kmelia, pubDetail); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { KmeliaPublication kmeliaPublication = kmelia.getPublication(newPubId); kmelia.setSessionPublication(kmeliaPublication); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); if (toolboxMode) { request.setAttribute("Topics", kmelia.getAllTopics()); } else { List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("Components", kmelia.getComponents(aliases)); } destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); for (Alias oldAlias : oldAliases) { if (!loadedComponentIds.contains(oldAlias.getInstanceId())) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportPublications")) { String selectedIds = request.getParameter("SelectedIds"); String notSelectedIds = request.getParameter("NotSelectedIds"); List<String> ids = kmelia.processSelectedPublicationIds(selectedIds, notSelectedIds); List<WAAttributeValuePair> publicationIds = new ArrayList<WAAttributeValuePair>(); for (String id : ids) { publicationIds.add(new WAAttributeValuePair(id, kmelia.getComponentId())); } request.setAttribute("selectedResultsWa", publicationIds); kmelia.resetSelectedPublicationIds(); // Go to importExportPeas destination = "/RimportExportPeas/jsp/SelectExportMode"; } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (StringUtil.isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template request.setAttribute("Name", modelId); destination = getDestination("GoToXMLForm", kmelia, request); } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { setTemplatesUsedIntoRequest(kmelia, request); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { try { List<PublicationTemplate> templates = getPublicationTemplateManager().getPublicationTemplates(); request.setAttribute("XMLForms", templates); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ModelUsed)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if ("ChangeTemplate".equals(function)) { kmelia.removePublicationContent(); destination = getDestination("ToPubliContent", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getDetail().getPK(). getId())) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone(). getCompleteDetail()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); for (FileItem item : parameters) { if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = Integer.parseInt(item.getFieldName().substring(8, item.getFieldName().length())); textDetails.add(new InfoTextDetail(null, Integer.toString(textOrder), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = Long.toString(System.currentTimeMillis()) + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if ("gif".equalsIgnoreCase(type) || "jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type)) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, Integer.toString(imageOrder), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); if (!StringUtil.isDefined(xmlFormName)) { xmlFormName = (String) request.getAttribute("Name"); } setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); // template can be changed only if current topic is using at least two templates setTemplatesUsedIntoRequest(kmelia, request); @SuppressWarnings("unchecked") Collection<PublicationTemplate> templates = (Collection<PublicationTemplate>) request.getAttribute("XMLForms"); boolean wysiwygUsable = (Boolean) request.getAttribute("WysiwygValid"); request.setAttribute("IsChangingTemplateAllowed", templates.size() >= 2 || (!templates.isEmpty() && wysiwygUsable)); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { boolean creation = false; if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); creation = true; } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate( kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia .getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getCurrentFolderId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); context.setCreation(creation); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, true, 3)); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", kmelia, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } else if (function.equals("SuggestDelegatedNews")) { String pubId = kmelia.addDelegatedNews(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); }/*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia.getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", kmelia, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxViewUnbalanced")) { List<KmeliaPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<KmeliaPublication> publications = (List<KmeliaPublication>) basket. getKmeliaPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<KmeliaPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !"X".equals(timeCriteria)) { publications = kmelia.search(combination, Integer.parseInt(timeCriteria)); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia.getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else if ("statistics".equals(function)) { destination = rootDestination + statisticRequestHandler.handleRequest(request, function, kmelia); }else if("statSelectionGroup".equals(function)) { destination = statisticRequestHandler.handleRequest(request, function, kmelia); } else { destination = rootDestination + function; } if (profileError) { destination = GeneralPropertiesManager.getString("sessionTimeout"); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; } private String getDocumentNotFoundDestination(KmeliaSessionController kmelia, HttpServletRequest request) { request.setAttribute("ComponentId", kmelia.getComponentId()); return "/admin/jsp/documentNotFound.jsp"; } private PublicationDetail getPublicationDetail(List<FileItem> parameters, KmeliaSessionController kmelia) throws Exception { String id = FileUploadUtil.getParameter(parameters, "PubId"); String status = FileUploadUtil.getParameter(parameters, "Status"); String name = FileUploadUtil.getParameter(parameters, "Name"); String description = FileUploadUtil.getParameter(parameters, "Description"); String keywords = FileUploadUtil.getParameter(parameters, "Keywords"); String beginDate = FileUploadUtil.getParameter(parameters, "BeginDate"); String endDate = FileUploadUtil.getParameter(parameters, "EndDate"); String version = FileUploadUtil.getParameter(parameters, "Version"); String importance = FileUploadUtil.getParameter(parameters, "Importance"); String beginHour = FileUploadUtil.getParameter(parameters, "BeginHour"); String endHour = FileUploadUtil.getParameter(parameters, "EndHour"); String author = FileUploadUtil.getParameter(parameters, "Author"); String targetValidatorId = FileUploadUtil.getParameter(parameters, "ValideurId"); String tempId = FileUploadUtil.getParameter(parameters, "TempId"); String infoId = FileUploadUtil.getParameter(parameters, "InfoId"); String draftOutDate = FileUploadUtil.getParameter(parameters, "DraftOutDate"); Date jBeginDate = null; Date jEndDate = null; Date jDraftOutDate = null; if (StringUtil.isDefined(beginDate)) { jBeginDate = DateUtil.stringToDate(beginDate, kmelia.getLanguage()); } if (StringUtil.isDefined(endDate)) { jEndDate = DateUtil.stringToDate(endDate, kmelia.getLanguage()); } if (StringUtil.isDefined(draftOutDate)) { jDraftOutDate = DateUtil.stringToDate(draftOutDate, kmelia.getLanguage()); } String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, importance, version, keywords, "", status, "", author); pubDetail.setBeginHour(beginHour); pubDetail.setEndHour(endHour); pubDetail.setStatus(status); pubDetail.setDraftOutDate(jDraftOutDate); if (StringUtil.isDefined(targetValidatorId)) { pubDetail.setTargetValidatorId(targetValidatorId); } pubDetail.setCloneId(tempId); if (StringUtil.isDefined(infoId)) { pubDetail.setInfoId(infoId); } I18NHelper.setI18NInfo(pubDetail, parameters); return pubDetail; } private void processVignette(List<FileItem> parameters, KmeliaSessionController kmelia, PublicationDetail publication) throws Exception { // First, check if image have been uploaded FileItem file = FileUploadUtil.getFile(parameters, "WAIMGVAR0"); String mimeType = null; String physicalName = null; if (file != null) { String logicalName = file.getName().replace('\\', '/'); if (logicalName != null) { logicalName = logicalName.substring(logicalName.lastIndexOf('/') + 1, logicalName.length()); mimeType = FileUtil.getMimeType(logicalName); String type = FileRepositoryManager.getFileExtension(logicalName); if (FileUtil.isImage(logicalName)) { physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type; File dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + kmelia.getPublicationSettings().getString("imagesSubDirectory")); if (!dir.exists()) { dir.mkdirs(); } File target = new File(dir, physicalName); file.write(target); } } } // If no image have been uploaded, check if one have been picked up from a gallery if (physicalName == null) { // on a pas d'image, regarder s'il y a une provenant de la galerie String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery"); if (StringUtil.isDefined(nameImageFromGallery)) { physicalName = nameImageFromGallery; mimeType = "image/jpeg"; } } // If one image is defined, save it through Thumbnail service if (StringUtil.isDefined(physicalName)) { ThumbnailDetail detail = new ThumbnailDetail(kmelia.getComponentId(), Integer.parseInt(publication.getPK().getId()), ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE); detail.setOriginalFileName(physicalName); detail.setMimeType(mimeType); try { int[] thumbnailSize = kmelia.getThumbnailWidthAndHeight(); ThumbnailController.updateThumbnail(detail, thumbnailSize[0], thumbnailSize[1]); // force indexation to taking into account new thumbnail if (publication.isIndexable()) { kmelia.getPublicationBm().createIndex(publication.getPK()); } } catch (ThumbnailRuntimeException e) { SilverTrace.error("Thumbnail", "ThumbnailRequestRouter.addThumbnail", "root.MSG_GEN_PARAM_VALUE", e); try { ThumbnailController.deleteThumbnail(detail); } catch (Exception exp) { SilverTrace.info("Thumbnail", "ThumbnailRequestRouter.addThumbnail - remove after error", "root.MSG_GEN_PARAM_VALUE", exp); } } } } /** * Process Form Upload for publications import * @param kmeliaScc * @param request * @param routeDestination * @return destination */ private String processFormUpload(KmeliaSessionController kmeliaScc, HttpServletRequest request, String routeDestination, boolean isMassiveMode) { String destination = ""; String topicId = ""; String importMode = KmeliaSessionController.UNITARY_IMPORT_MODE; boolean draftMode = false; String logicalName = ""; String message = ""; String tempFolderName = ""; String tempFolderPath = ""; String fileType = ""; long fileSize = 0; long processStart = new Date().getTime(); ResourceLocator attachmentResourceLocator = new ResourceLocator( "com.stratelia.webactiv.util.attachment.multilang.attachment", kmeliaScc.getLanguage()); FileItem fileItem = null; int versionType = DocumentVersion.TYPE_DEFAULT_VERSION; try { List<FileItem> items = FileUploadUtil.parseRequest(request); topicId = FileUploadUtil.getParameter(items, "topicId"); importMode = FileUploadUtil.getParameter(items, "opt_importmode"); String sVersionType = FileUploadUtil.getParameter(items, "opt_versiontype"); if (StringUtil.isDefined(sVersionType)) { versionType = Integer.parseInt(sVersionType); } String sDraftMode = FileUploadUtil.getParameter(items, "chk_draft"); if (StringUtil.isDefined(sDraftMode)) { draftMode = StringUtil.getBooleanValue(sDraftMode); } fileItem = FileUploadUtil.getFile(items, "file_name"); if (fileItem != null) { logicalName = fileItem.getName(); if (logicalName != null) { boolean runOnUnix = !FileUtil.isWindows(); if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.processFormUpload", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); // Name of temp folder: timestamp and userId tempFolderName = Long.toString(System.currentTimeMillis()) + "_" + kmeliaScc.getUserId(); // Mime type of the file fileType = fileItem.getContentType(); // Zip contentType not detected under Firefox ! if (!ClientBrowserUtil.isInternetExplorer(request)) { fileType = MimeTypes.ARCHIVE_MIME_TYPE; } fileSize = fileItem.getSize(); // Directory Temp for the uploaded file tempFolderPath = FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName; if (!new File(tempFolderPath).exists()) { FileRepositoryManager.createAbsolutePath(kmeliaScc.getComponentId(), GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName); } // Creation of the file in the temp folder File fileUploaded = new File(FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName + File.separator + logicalName); fileItem.write(fileUploaded); // Is a real file ? if (fileSize > 0) { SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize=" + fileSize + " fileType=" + fileType + " importMode=" + importMode + " draftMode=" + draftMode); int nbFiles = 1; // Compute nbFiles only in unitary Import mode if (!importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE) && fileUploaded.getName().toLowerCase().endsWith(".zip")) { nbFiles = ZipManager.getNbFiles(fileUploaded); } // Import !! List<PublicationDetail> publicationDetails = kmeliaScc.importFile(fileUploaded, fileType, topicId, importMode, draftMode, versionType); long processDuration = new Date().getTime() - processStart; // Title for popup report String importModeTitle = ""; if (importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) { importModeTitle = kmeliaScc.getString("kmelia.ImportModeUnitaireTitre"); } else { importModeTitle = kmeliaScc.getString("kmelia.ImportModeMassifTitre"); } SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "nbFiles = " + nbFiles + " publicationDetails=" + publicationDetails + " ProcessDuration=" + processDuration + " ImportMode=" + importMode + " Draftmode=" + draftMode + " Title=" + importModeTitle); request.setAttribute("PublicationsDetails", publicationDetails); request.setAttribute("NbFiles", nbFiles); request.setAttribute("ProcessDuration", FileRepositoryManager.formatFileUploadTime( processDuration)); request.setAttribute("ImportMode", importMode); request.setAttribute("DraftMode", draftMode); request.setAttribute("Title", importModeTitle); request.setAttribute("Context", GeneralPropertiesManager.getString("ApplicationURL")); destination = routeDestination + "reportImportFiles.jsp"; String componentId = publicationDetails.get(0).getComponentInstanceId(); if (kmeliaScc.isDefaultClassificationModifiable(topicId, componentId)) { destination = routeDestination + "validateImportedFilesClassification.jsp"; } } else { // File access failed message = attachmentResourceLocator.getString("liaisonInaccessible"); request.setAttribute("Message", message); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } FileFolderManager.deleteFolder(tempFolderPath); } else { // the field did not contain a file request.setAttribute("Message", attachmentResourceLocator .getString("liaisonInaccessible")); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } } } /* * catch (IOException e) { //File size exceeds Maximum file size message = * attachmentResourceLocator.getString("fichierTropGrand")+ " (" + * FileRepositoryManager.formatFileSize(maxFileSize) + "&nbsp;" + * attachmentResourceLocator.getString("maximum") +") !!"; * request.setAttribute("Message",message); request.setAttribute("TopicId",topicId); * destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) destination = * routeDestination + "importMultiFiles.jsp"; } */catch (Exception e) { // Other exception request.setAttribute("Message", e.getMessage()); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } SilverTrace.warn("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED", e); } return destination; } private void processPath(KmeliaSessionController kmeliaSC, String id) throws RemoteException { if (!kmeliaSC.isKmaxMode) { NodePK pk = null; if (!StringUtil.isDefined(id)) { pk = kmeliaSC.getCurrentFolderPK(); } else { pk = kmeliaSC.getAllowedPublicationFather(id); // get publication parent kmeliaSC.setCurrentFolderId(pk.getId(), true); } Collection<NodeDetail> pathColl = kmeliaSC.getTopicPath(pk.getId()); String linkedPathString = kmeliaSC.displayPath(pathColl, true, 3); String pathString = kmeliaSC.displayPath(pathColl, false, 3); kmeliaSC.setSessionPath(linkedPathString); kmeliaSC.setSessionPathString(pathString); } } private void putXMLDisplayerIntoRequest(PublicationDetail pubDetail, KmeliaSessionController kmelia, HttpServletRequest request) throws PublicationTemplateException, FormException { String infoId = pubDetail.getInfoId(); String pubId = pubDetail.getPK().getId(); if (!StringUtil.isInteger(infoId)) { PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate( pubDetail. getPK().getInstanceId() + ":" + infoId); // RecordTemplate recordTemplate = pubTemplate.getRecordTemplate(); Form formView = pubTemplate.getViewForm(); // get displayed language String language = checkLanguage(kmelia, pubDetail); RecordSet recordSet = pubTemplate.getRecordSet(); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("XMLForm", formView); request.setAttribute("XMLData", data); } } private String processWizard(String function, KmeliaSessionController kmeliaSC, HttpServletRequest request, String rootDestination) throws RemoteException, PublicationTemplateException, FormException { String destination = ""; if (function.equals("WizardStart")) { // récupération de l'id du thème dans lequel on veux mettre la // publication // si on ne viens pas d'un theme-tracker String topicId = request.getParameter("TopicId"); if (StringUtil.isDefined(topicId)) { TopicDetail topic = kmeliaSC.getTopic(topicId); kmeliaSC.setSessionTopic(topic); } // recherche du dernier onglet String wizardLast = "1"; List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if (kmeliaSC.isKmaxMode) { wizardLast = "4"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { wizardLast = "3"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { wizardLast = "2"; } kmeliaSC.setWizardLast(wizardLast); request.setAttribute("WizardLast", wizardLast); kmeliaSC.setWizard("progress"); request.setAttribute("Action", "Wizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardHeader")) { // passage des paramètres String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } request.setAttribute("WizardRow", kmeliaSC.getWizardRow()); request.setAttribute("WizardLast", kmeliaSC.getWizardLast()); request.setAttribute("Action", "UpdateWizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); request.setAttribute("PubId", id); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardNext")) { // redirige vers l'onglet suivant de l'assistant de publication String position = request.getParameter("Position"); if (!StringUtil.isDefined(position)) { position = (String) request.getAttribute("Position"); } String next = "End"; String wizardRow = kmeliaSC.getWizardRow(); request.setAttribute("WizardRow", wizardRow); int numRow = 0; if (StringUtil.isDefined(wizardRow)) { numRow = Integer.parseInt(wizardRow); } List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if (position.equals("View")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { // on passe à la page du contenu next = "Content"; if (numRow <= 2) { wizardRow = "2"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Content")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Attachment")) { if (kmeliaSC.isKmaxMode) { next = "KmaxClassification"; } else { next = "End"; } if (!next.equals("End")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } } else if (position.equals("KmaxClassification")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "End"; } // mise à jour du rang en cours kmeliaSC.setWizardRow(wizardRow); // passage des paramètres setWizardParams(request, kmeliaSC); if (next.equals("View")) { destination = getDestination("WizardStart", kmeliaSC, request); } else if (next.equals("Content")) { destination = getDestination("ToPubliContent", kmeliaSC, request); } else if (next.equals("Attachment")) { destination = getDestination("ViewAttachments", kmeliaSC, request); } else if (next.equals("KmaxClassification")) { destination = getDestination("KmaxViewCombination", kmeliaSC, request); } else if (next.equals("End")) { // terminer la publication : la sortir du mode brouillon kmeliaSC.setWizard("finish"); kmeliaSC.draftOutPublication(); destination = getDestination("ViewPublication", kmeliaSC, request); } } return destination; } private void setWizardParams(HttpServletRequest request, KmeliaSessionController kmelia) { // Paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("WizardRow", kmelia.getWizardRow()); request.setAttribute("WizardLast", kmelia.getWizardLast()); } private void resetWizard(KmeliaSessionController kmelia) { kmelia.setWizard("none"); kmelia.setWizardLast("0"); kmelia.setWizardRow("0"); } private void setXMLForm(HttpServletRequest request, KmeliaSessionController kmelia, String xmlFormName) throws PublicationTemplateException, FormException { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); String pubId = pubDetail.getPK().getId(); String xmlFormShortName = null; if (!StringUtil.isDefined(xmlFormName)) { xmlFormShortName = pubDetail.getInfoId(); xmlFormName = null; } else { xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); SilverTrace.info("kmelia", "KmeliaRequestRouter.setXMLForm()", "root.MSG_GEN_PARAM_VALUE", "xmlFormShortName = " + xmlFormShortName); // register xmlForm to publication getPublicationTemplateManager().addDynamicPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName, xmlFormName); } PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate( kmelia. getComponentId() + ":" + xmlFormShortName, xmlFormName); Form formUpdate = pubTemplate.getUpdateForm(); RecordSet recordSet = pubTemplate.getRecordSet(); // get displayed language String language = checkLanguage(kmelia, pubDetail); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("Form", formUpdate); request.setAttribute("Data", data); request.setAttribute("XMLFormName", xmlFormName); } private void setLanguage(HttpServletRequest request, KmeliaSessionController kmelia) { String language = request.getParameter("SwitchLanguage"); if (StringUtil.isDefined(language)) { kmelia.setCurrentLanguage(language); } request.setAttribute("Language", kmelia.getCurrentLanguage()); } private String checkLanguage(KmeliaSessionController kmelia) { return checkLanguage(kmelia, kmelia.getSessionPublication().getDetail()); } private String checkLanguage(KmeliaSessionController kmelia, PublicationDetail pubDetail) { return pubDetail.getLanguageToDisplay(kmelia.getCurrentLanguage()); } private void checkAlias(KmeliaSessionController kmelia, KmeliaPublication publication) { if (!kmelia.getComponentId().equals( publication.getDetail().getPK().getInstanceId())) { publication.asAlias(); } } private void updatePubliDuringUpdateChain(String id, HttpServletRequest request, KmeliaSessionController kmelia) throws RemoteException { // enregistrement des modifications de la publi String name = request.getParameter("Name"); String description = request.getParameter("Description"); String keywords = request.getParameter("Keywords"); String tree = request.getParameter("Tree"); String[] topics = request.getParameterValues("topicChoice"); // sauvegarde des données Fields fields = kmelia.getFieldUpdateChain(); FieldUpdateChainDescriptor field = kmelia.getFieldUpdateChain().getName(); field.setName("Name"); field.setValue(name); fields.setName(field); field = kmelia.getFieldUpdateChain().getDescription(); field.setName("Description"); field.setValue(description); fields.setDescription(field); field = kmelia.getFieldUpdateChain().getKeywords(); field.setName("Keywords"); field.setValue(keywords); fields.setKeywords(field); field = kmelia.getFieldUpdateChain().getTree(); if (field != null) { field.setName("Topics"); field.setValue(tree); fields.setTree(field); } fields.setTopics(topics); kmelia.setFieldUpdateChain(fields); Date jBeginDate = null; Date jEndDate = null; String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, "0", "", keywords, "", "", "", ""); pubDetail.setStatus("Valid"); I18NHelper.setI18NInfo(pubDetail, request); try { // Execute helper String helperClassName = kmelia.getFieldUpdateChain().getHelper(); UpdateChainHelper helper; helper = (UpdateChainHelper) Class.forName(helperClassName).newInstance(); UpdateChainHelperContext uchc = new UpdateChainHelperContext(pubDetail, kmelia); uchc.setAllTopics(kmelia.getAllTopics()); helper.execute(uchc); pubDetail = uchc.getPubDetail(); // mettre à jour les emplacements si necessaire String[] calculedTopics = uchc.getTopics(); if (calculedTopics != null) { topics = calculedTopics; } } catch (Exception e) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, e.getMessage(), e); } kmelia.updatePublication(pubDetail); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } kmelia.setAliases(pubDetail.getPK(), aliases); } private String processUpdateChainOperation(String rootDestination, String function, KmeliaSessionController kmelia, HttpServletRequest request) throws IOException, ClassNotFoundException, SAXException, ParserConfigurationException { if (function.equals("UpdateChainInit")) { // récupération du descripteur kmelia.initUpdateChainDescriptor(); // Modification par chaine de toutes les publications du thème : // positionnement sur la première publi String pubId = kmelia.getFirst(); request.setAttribute("PubId", pubId); // initialiser le topic en cours kmelia.initUpdateChainTopicChoice(pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainPublications")) { String id = (String) request.getAttribute("PubId"); request.setAttribute("Action", "UpdateChain"); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("PubId", id); request.setAttribute("SaveFields", kmelia.getFieldUpdateChain()); if (StringUtil.isDefined(id)) { request.setAttribute("Rang", kmelia.getRang()); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size()); } else { request.setAttribute("NbPublis", 1); } // request.setAttribute("PathList",kmelia.getPublicationFathers(id)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getUpdateChainTopics()); // mise à jour de la publication en session pour récupérer les alias KmeliaPublication kmeliaPublication = kmelia.getPublication(id); kmelia.setSessionPublication(kmeliaPublication); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); // url du fichier joint request.setAttribute("FileUrl", kmelia.getFirstAttachmentURLOfCurrentPublication()); return rootDestination + "updateByChain.jsp"; } } else if (function.equals("UpdateChainNextUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // récupération de la publication suivante String nextPubId = kmelia.getNext(); request.setAttribute("PubId", nextPubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainLastUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getCurrentFolderId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainSkipUpdate")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainEndUpdate")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getCurrentFolderId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainUpdateAll")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getCurrentFolderId()); // enregistrement des modifications sur toutes les publications restantes // publication courante String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // passer à la suivante si elle existe int rang = kmelia.getRang(); int nbPublis = kmelia.getSessionPublicationsList().size(); while (rang < nbPublis - 1) { String pubId = kmelia.getNext(); updatePubliDuringUpdateChain(pubId, request, kmelia); rang = kmelia.getRang(); } // retour au thème return getDestination("GoToTopic", kmelia, request); } return ""; } /** * Gets an instance of PublicationTemplateManager. * @return an instance of PublicationTemplateManager. */ public PublicationTemplateManager getPublicationTemplateManager() { return PublicationTemplateManager.getInstance(); } private void setTemplatesUsedIntoRequest(KmeliaSessionController kmelia, HttpServletRequest request) throws RemoteException { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = new ArrayList<PublicationTemplate>(); try { templates = getPublicationTemplateManager().getPublicationTemplates(); // recherche de la liste des modèles utilisables PublicationTemplate xmlForm; for (PublicationTemplate template : templates) { xmlForm = template; // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ListModels)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); for (ModelDetail modelDetail : dbForms) { // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", wysiwygValid); // s'il n'y a pas de modèles selectionnés, les présenter tous if ((listModelXml == null || listModelXml.isEmpty()) && (listModelForm == null || listModelForm.isEmpty()) && !wysiwygValid) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } } /** * Converts the specified identifier into a Silverpeas content primary key. * @param instanceId the unique identifier of the component instance to which the contents * belongs. * @param ids one or several identifiers of Silverpeas contents. * @return a list of one or several Silverpeas primary keys, each of them corresponding to one * specified identifier. */ private List<ForeignPK> asPks(String instanceId, String... ids) { List<ForeignPK> pks = new ArrayList<ForeignPK>(); for (String oneId : ids) { pks.add(new ForeignPK(oneId, instanceId)); } return pks; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
041ebc7bf358ddabe1bfa8b61151f8b472363924
46cb512749dc57cacc1cf23a63748baf81f1d62c
/app/src/main/java/com/atmavedagana/shivoham/shivoham/MainActivity.java
86810cf8f790862b23615a519d59dc34da0c7ef8
[]
no_license
mapsver/Shivoham
9c4680f8150390194325777c675780d48bcb7d22
38c9facac58f125cd4fa55f0c5e5308a73702caf
refs/heads/master
2021-09-16T13:16:51.105659
2018-01-23T04:03:47
2018-01-23T04:03:47
110,180,810
0
0
null
null
null
null
UTF-8
Java
false
false
4,181
java
/* * Copyright (C) 2016 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.atmavedagana.shivoham.shivoham; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.atmavedagana.shivoham.shivoham.utils.FileUtils; import java.io.File; //import com.dropbox.client2.DropboxAPI; //import com.dropbox.client2.ProgressListener; //import com.dropbox.client2.android.AndroidAuthSession; //import com.dropbox.client2.session.AppKeyPair; public class MainActivity extends AppCompatActivity { private String mlocalJsonFileDownloadPath = null; private String mlocalPDFFileDownloadPath = null; private String mlocalAudioFileDownloadPath = null; private String mdropBoxPDFFileDownloadPath = null; private String mdropBoxAudioFileDownloadPath = null; public static String mlocalDirPath = null; private TextView mtv_results; private BaseDownloader mDownloaderClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FileUtils.verifyStoragePermissions(this); mtv_results = (TextView) findViewById(R.id.tv_results); mlocalDirPath = FileUtils.getMediaStorageRootFolder(this); mlocalPDFFileDownloadPath = mlocalDirPath + "/firstPDFDownloadJGD.pdf"; mlocalAudioFileDownloadPath = mlocalDirPath + "/firstAudioDownloadJGD.mp3"; mdropBoxAudioFileDownloadPath = "/MedhaSuktam/MedhaSuktam.mp3"; mdropBoxPDFFileDownloadPath = "/MedhaSuktam/MedhaSuktam lesson.pdf"; mDownloaderClient = new DropBoxDownloader(); mDownloaderClient.setupDownloaderClient(); } public void onClickDownloadFromDropboxButton(View v) { } public void openPDFV2(String downloadFilePath) { String[] strArr = new String[2]; strArr[0] = downloadFilePath; strArr[1] = mlocalAudioFileDownloadPath; Intent openPDFIntent = new Intent(this, PDF_Activity.class); openPDFIntent.putExtra(Intent.ACTION_OPEN_DOCUMENT, strArr); startActivity(openPDFIntent); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void onClickOpenPDF(View v) { try { File file = new File(mlocalPDFFileDownloadPath); File audfile = new File(mlocalAudioFileDownloadPath); if (audfile == null || !audfile.exists()) { new AlertDialog.Builder(this) .setMessage("JGD ! Audio file does'nt exist ! Unable to proceed.") .setPositiveButton(android.R.string.ok, null) .show(); return; } if (file != null && file.exists()) { // OpenPDFInNewActivity(mlocalPDFFileDownloadPath + ".pdf"); openPDFV2(mlocalPDFFileDownloadPath); } else { new AlertDialog.Builder(this) .setMessage("JGD ! PDF file does'nt exist ! Unable to proceed.") .setPositiveButton(android.R.string.ok, null) .show(); return; } } catch (Exception e) { e.printStackTrace(); return; } } }
[ "31552502+mapsver@users.noreply.github.com" ]
31552502+mapsver@users.noreply.github.com
be9015769a2711c54e42711b5b5d9e551b317194
4dd35b2866442e6e1f9a65ee2184d90ea909eb32
/edugl/src/com/jlict/edu/file/service/FileService.java
0536ac1a850fadc73a969eb9b49d68ce7b2f175f
[]
no_license
jlictedu/JlictEdugl
bf386eb394417af610cef6aac90a58fa23df87f5
7af99d7d47cf180d3726ce951ee3bc16a7184629
refs/heads/master
2020-06-05T05:13:00.612816
2014-05-13T06:48:21
2014-05-13T06:48:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
527
java
package com.jlict.edu.file.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jlict.edu.core.dao.PagingJson; import com.jlict.edu.file.dao.FileDao; import com.jlict.edu.file.dao.FileVo; @Service public class FileService { @Autowired private FileDao dao; public PagingJson queryFile(int pageIndex, int pageSize) { return this.dao.queryFile(pageIndex, pageSize); } public FileVo getFile(String id) { return this.dao.getFile(id); } }
[ "zhu91aizhu@126.com" ]
zhu91aizhu@126.com
4a9703e0f756e68358b9effc1433530f1f84753c
0abe5df97c360b566a25497d47cde0adf740a118
/quicksort.java
95c88666134954e2e3f824938c73a246348579f5
[]
no_license
ashutoshjv661/JAVA-LAB
817d3a311f130c3ccbd86c9944951ae50909fecd
32da0eb43ba89cc5006f81b9d25dde33626474cd
refs/heads/master
2021-07-15T08:03:38.147618
2020-05-09T18:28:17
2020-05-09T18:28:17
140,252,985
1
1
null
null
null
null
UTF-8
Java
false
false
1,221
java
import java.util.Scanner; public class QuickSort { static int a[]; static void qsort(int left, int right) { if(left<right) { int p = partition(left, right); qsort(left, p-1); qsort(p+1, right); } } static int partition(int low, int high) { int pivot = a[high]; int pindex=low; for(int i=low;i<=high-1;i++) { if(a[i]<=pivot) { int temp = a[pindex]; a[pindex] = a[i]; a[i] = temp; pindex++; } } int temp = a[pindex]; a[pindex] = a[high]; a[high] = temp; return pindex; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n, i; System.out.println("Enter the no. of elements: "); n = s.nextInt(); a = new int[n]; System.out.println("The Random Numbers are:"); for (i = 0; i < n; i++) { a[i] = (int) (Math.random() * 100); System.out.print(a[i]+" "); } long startTime = System.nanoTime(); qsort( 0, n-1); long endTime = System.nanoTime(); long duration = (endTime - startTime); System.out.println("\nThe Sorted Numbers are:"); for (i = 0; i < n; i++) { System.out.print(a[i]+" "); } System.out.println("\nTime taken is "+ duration/1000+" microseconds" ); } }
[ "noreply@github.com" ]
ashutoshjv661.noreply@github.com
58f23e4d862d87c0f2b54bd6867aeb9f7a25bb5c
e861c6590f6ece5e3c31192e2483c4fa050d0545
/app/src/main/java/plugin/android/ss/com/testsettings/settings/bluetooth/DeviceProfilesSettings.java
f3e3720a306caa70c93acc82534c2410b33b7945
[]
no_license
calm-sjf/TestSettings
fc9a9c466f007d5eac6b4acdf674cd2e0cffb9a1
fddbb049542ff8423bdecb215b71dbdcc143930c
refs/heads/master
2023-03-22T02:46:23.057328
2020-12-10T07:37:27
2020-12-10T07:37:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
17,456
java
/* * Copyright (C) 2011 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 plugin.android.ss.com.testsettings.settings.bluetooth; import android.app.AlertDialog; import android.app.Dialog; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.text.Html; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import com.android.internal.logging.nano.MetricsProto; import com.android.settings.R; import com.android.settings.core.instrumentation.InstrumentedDialogFragment; import com.android.settingslib.bluetooth.A2dpProfile; import com.android.settingslib.bluetooth.CachedBluetoothDevice; import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager; import com.android.settingslib.bluetooth.LocalBluetoothManager; import com.android.settingslib.bluetooth.LocalBluetoothProfile; import com.android.settingslib.bluetooth.LocalBluetoothProfileManager; import com.android.settingslib.bluetooth.MapProfile; import com.android.settingslib.bluetooth.PanProfile; import com.android.settingslib.bluetooth.PbapServerProfile; public final class DeviceProfilesSettings extends InstrumentedDialogFragment implements CachedBluetoothDevice.Callback, DialogInterface.OnClickListener, OnClickListener { private static final String TAG = "DeviceProfilesSettings"; public static final String ARG_DEVICE_ADDRESS = "device_address"; private static final String KEY_PROFILE_CONTAINER = "profile_container"; private static final String KEY_UNPAIR = "unpair"; private static final String KEY_PBAP_SERVER = "PBAP Server"; @VisibleForTesting static final String HIGH_QUALITY_AUDIO_PREF_TAG = "A2dpProfileHighQualityAudio"; private CachedBluetoothDevice mCachedDevice; private LocalBluetoothManager mManager; private LocalBluetoothProfileManager mProfileManager; private ViewGroup mProfileContainer; private TextView mProfileLabel; private AlertDialog mDisconnectDialog; private boolean mProfileGroupIsRemoved; private View mRootView; @Override public int getMetricsCategory() { return MetricsProto.MetricsEvent.DIALOG_BLUETOOTH_PAIRED_DEVICE_PROFILE; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mManager = Utils.getLocalBtManager(getActivity()); CachedBluetoothDeviceManager deviceManager = mManager.getCachedDeviceManager(); String address = getArguments().getString(ARG_DEVICE_ADDRESS); BluetoothDevice remoteDevice = mManager.getBluetoothAdapter().getRemoteDevice(address); mCachedDevice = deviceManager.findDevice(remoteDevice); if (mCachedDevice == null) { mCachedDevice = deviceManager.addDevice(mManager.getBluetoothAdapter(), mManager.getProfileManager(), remoteDevice); } mProfileManager = mManager.getProfileManager(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mRootView = LayoutInflater.from(getContext()).inflate(R.layout.device_profiles_settings, null); mProfileContainer = (ViewGroup) mRootView.findViewById(R.id.profiles_section); mProfileLabel = (TextView) mRootView.findViewById(R.id.profiles_label); final EditText deviceName = (EditText) mRootView.findViewById(R.id.name); deviceName.setText(mCachedDevice.getName(), TextView.BufferType.EDITABLE); return new AlertDialog.Builder(getContext()) .setView(mRootView) .setNeutralButton(R.string.forget, this) .setPositiveButton(R.string.okay, this) .setTitle(R.string.bluetooth_preference_paired_devices) .create(); } @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: EditText deviceName = (EditText) mRootView.findViewById(R.id.name); mCachedDevice.setName(deviceName.getText().toString()); break; case DialogInterface.BUTTON_NEUTRAL: mCachedDevice.unpair(); break; } } @Override public void onDestroy() { super.onDestroy(); if (mDisconnectDialog != null) { mDisconnectDialog.dismiss(); mDisconnectDialog = null; } if (mCachedDevice != null) { mCachedDevice.unregisterCallback(this); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override public void onResume() { super.onResume(); mManager.setForegroundActivity(getActivity()); if (mCachedDevice != null) { mCachedDevice.registerCallback(this); if (mCachedDevice.getBondState() == BluetoothDevice.BOND_NONE) { dismiss(); return; } addPreferencesForProfiles(); refresh(); } } @Override public void onPause() { super.onPause(); if (mCachedDevice != null) { mCachedDevice.unregisterCallback(this); } mManager.setForegroundActivity(null); } private void addPreferencesForProfiles() { mProfileContainer.removeAllViews(); for (LocalBluetoothProfile profile : mCachedDevice.getConnectableProfiles()) { CheckBox pref = createProfilePreference(profile); // MAP and PBAP profiles would be added based on permission access if (!((profile instanceof PbapServerProfile) || (profile instanceof MapProfile))) { mProfileContainer.addView(pref); } if (profile instanceof A2dpProfile) { BluetoothDevice device = mCachedDevice.getDevice(); A2dpProfile a2dpProfile = (A2dpProfile) profile; if (a2dpProfile.supportsHighQualityAudio(device)) { CheckBox highQualityPref = new CheckBox(getActivity()); highQualityPref.setTag(HIGH_QUALITY_AUDIO_PREF_TAG); highQualityPref.setOnClickListener(v -> { a2dpProfile.setHighQualityAudioEnabled(device, highQualityPref.isChecked()); }); highQualityPref.setVisibility(View.GONE); mProfileContainer.addView(highQualityPref); } refreshProfilePreference(pref, profile); } } final int pbapPermission = mCachedDevice.getPhonebookPermissionChoice(); Log.d(TAG, "addPreferencesForProfiles: pbapPermission = " + pbapPermission); // Only provide PBAP cabability if the client device has requested PBAP. if (pbapPermission != CachedBluetoothDevice.ACCESS_UNKNOWN) { final PbapServerProfile psp = mManager.getProfileManager().getPbapProfile(); CheckBox pbapPref = createProfilePreference(psp); mProfileContainer.addView(pbapPref); } final MapProfile mapProfile = mManager.getProfileManager().getMapProfile(); final int mapPermission = mCachedDevice.getMessagePermissionChoice(); Log.d(TAG, "addPreferencesForProfiles: mapPermission = " + mapPermission); if (mapPermission != CachedBluetoothDevice.ACCESS_UNKNOWN) { CheckBox mapPreference = createProfilePreference(mapProfile); mProfileContainer.addView(mapPreference); } showOrHideProfileGroup(); } private void showOrHideProfileGroup() { int numProfiles = mProfileContainer.getChildCount(); if (!mProfileGroupIsRemoved && numProfiles == 0) { mProfileContainer.setVisibility(View.GONE); mProfileLabel.setVisibility(View.GONE); mProfileGroupIsRemoved = true; } else if (mProfileGroupIsRemoved && numProfiles != 0) { mProfileContainer.setVisibility(View.VISIBLE); mProfileLabel.setVisibility(View.VISIBLE); mProfileGroupIsRemoved = false; } } /** * Creates a checkbox preference for the particular profile. The key will be * the profile's name. * * @param profile The profile for which the preference controls. * @return A preference that allows the user to choose whether this profile * will be connected to. */ private CheckBox createProfilePreference(LocalBluetoothProfile profile) { CheckBox pref = new CheckBox(getActivity()); pref.setTag(profile.toString()); pref.setText(profile.getNameResource(mCachedDevice.getDevice())); pref.setOnClickListener(this); refreshProfilePreference(pref, profile); return pref; } @Override public void onClick(View v) { if (v instanceof CheckBox) { LocalBluetoothProfile prof = getProfileOf(v); onProfileClicked(prof, (CheckBox) v); } } private void onProfileClicked(LocalBluetoothProfile profile, CheckBox profilePref) { BluetoothDevice device = mCachedDevice.getDevice(); if (!profilePref.isChecked()) { // Recheck it, until the dialog is done. profilePref.setChecked(true); askDisconnect(mManager.getForegroundActivity(), profile); } else { if (profile instanceof MapProfile) { mCachedDevice.setMessagePermissionChoice(BluetoothDevice.ACCESS_ALLOWED); } if (profile instanceof PbapServerProfile) { mCachedDevice.setPhonebookPermissionChoice(BluetoothDevice.ACCESS_ALLOWED); refreshProfilePreference(profilePref, profile); // PBAP server is not preffered profile and cannot initiate connection, so return return; } if (profile.isPreferred(device)) { // profile is preferred but not connected: disable auto-connect if (profile instanceof PanProfile) { mCachedDevice.connectProfile(profile); } else { profile.setPreferred(device, false); } } else { profile.setPreferred(device, true); mCachedDevice.connectProfile(profile); } refreshProfilePreference(profilePref, profile); } } private void askDisconnect(Context context, final LocalBluetoothProfile profile) { // local reference for callback final CachedBluetoothDevice device = mCachedDevice; String name = device.getName(); if (TextUtils.isEmpty(name)) { name = context.getString(R.string.bluetooth_device); } String profileName = context.getString(profile.getNameResource(device.getDevice())); String title = context.getString(R.string.bluetooth_disable_profile_title); String message = context.getString(R.string.bluetooth_disable_profile_message, profileName, name); DialogInterface.OnClickListener disconnectListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Disconnect only when user has selected OK otherwise ignore if (which == DialogInterface.BUTTON_POSITIVE) { device.disconnect(profile); profile.setPreferred(device.getDevice(), false); if (profile instanceof MapProfile) { device.setMessagePermissionChoice(BluetoothDevice.ACCESS_REJECTED); } if (profile instanceof PbapServerProfile) { device.setPhonebookPermissionChoice(BluetoothDevice.ACCESS_REJECTED); } } refreshProfilePreference(findProfile(profile.toString()), profile); } }; mDisconnectDialog = Utils.showDisconnectDialog(context, mDisconnectDialog, disconnectListener, title, Html.fromHtml(message)); } @Override public void onDeviceAttributesChanged() { refresh(); } private void refresh() { final EditText deviceNameField = (EditText) mRootView.findViewById(R.id.name); if (deviceNameField != null) { deviceNameField.setText(mCachedDevice.getName()); com.android.settings.Utils.setEditTextCursorPosition(deviceNameField); } refreshProfiles(); } private void refreshProfiles() { for (LocalBluetoothProfile profile : mCachedDevice.getConnectableProfiles()) { CheckBox profilePref = findProfile(profile.toString()); if (profilePref == null) { profilePref = createProfilePreference(profile); mProfileContainer.addView(profilePref); } else { refreshProfilePreference(profilePref, profile); } } for (LocalBluetoothProfile profile : mCachedDevice.getRemovedProfiles()) { CheckBox profilePref = findProfile(profile.toString()); if (profilePref != null) { if (profile instanceof PbapServerProfile) { final int pbapPermission = mCachedDevice.getPhonebookPermissionChoice(); Log.d(TAG, "refreshProfiles: pbapPermission = " + pbapPermission); if (pbapPermission != CachedBluetoothDevice.ACCESS_UNKNOWN) continue; } if (profile instanceof MapProfile) { final int mapPermission = mCachedDevice.getMessagePermissionChoice(); Log.d(TAG, "refreshProfiles: mapPermission = " + mapPermission); if (mapPermission != CachedBluetoothDevice.ACCESS_UNKNOWN) continue; } Log.d(TAG, "Removing " + profile.toString() + " from profile list"); mProfileContainer.removeView(profilePref); } } showOrHideProfileGroup(); } private CheckBox findProfile(String profile) { return (CheckBox) mProfileContainer.findViewWithTag(profile); } private void refreshProfilePreference(CheckBox profilePref, LocalBluetoothProfile profile) { BluetoothDevice device = mCachedDevice.getDevice(); // Gray out checkbox while connecting and disconnecting. profilePref.setEnabled(!mCachedDevice.isBusy()); if (profile instanceof MapProfile) { profilePref.setChecked(mCachedDevice.getMessagePermissionChoice() == CachedBluetoothDevice.ACCESS_ALLOWED); } else if (profile instanceof PbapServerProfile) { profilePref.setChecked(mCachedDevice.getPhonebookPermissionChoice() == CachedBluetoothDevice.ACCESS_ALLOWED); } else if (profile instanceof PanProfile) { profilePref.setChecked(profile.getConnectionStatus(device) == BluetoothProfile.STATE_CONNECTED); } else { profilePref.setChecked(profile.isPreferred(device)); } if (profile instanceof A2dpProfile) { A2dpProfile a2dpProfile = (A2dpProfile) profile; View v = mProfileContainer.findViewWithTag(HIGH_QUALITY_AUDIO_PREF_TAG); if (v instanceof CheckBox) { CheckBox highQualityPref = (CheckBox) v; highQualityPref.setText(a2dpProfile.getHighQualityAudioOptionLabel(device)); highQualityPref.setChecked(a2dpProfile.isHighQualityAudioEnabled(device)); if (a2dpProfile.isPreferred(device)) { v.setVisibility(View.VISIBLE); v.setEnabled(!mCachedDevice.isBusy()); } else { v.setVisibility(View.GONE); } } } } private LocalBluetoothProfile getProfileOf(View v) { if (!(v instanceof CheckBox)) { return null; } String key = (String) v.getTag(); if (TextUtils.isEmpty(key)) return null; try { return mProfileManager.getProfileByName(key); } catch (IllegalArgumentException ignored) { return null; } } }
[ "xiaoxiaoyu@bytedance.com" ]
xiaoxiaoyu@bytedance.com
cd92454e073d8b3bd036cdc32b557ccbfad50883
5598faaaaa6b3d1d8502cbdaca903f9037d99600
/code_changes/Apache_projects/ZOOKEEPER-2383/d99d93a46cba7caf5ed44dfe4c2447a34ad0e383/NettyServerCnxn.java
32fc371e6de78196ac3d3085fa3978935b28a389
[]
no_license
SPEAR-SE/LogInBugReportsEmpirical_Data
94d1178346b4624ebe90cf515702fac86f8e2672
ab9603c66899b48b0b86bdf63ae7f7a604212b29
refs/heads/master
2022-12-18T02:07:18.084659
2020-09-09T16:49:34
2020-09-09T16:49:34
286,338,252
0
2
null
null
null
null
UTF-8
Java
false
false
28,903
java
/** * 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.zookeeper.server; import static org.jboss.netty.buffer.ChannelBuffers.wrappedBuffer; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.util.AbstractSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.apache.jute.BinaryInputArchive; import org.apache.jute.BinaryOutputArchive; import org.apache.jute.Record; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.zookeeper.Environment; import org.apache.zookeeper.Version; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.proto.ReplyHeader; import org.apache.zookeeper.proto.WatcherEvent; import org.apache.zookeeper.server.quorum.Leader; import org.apache.zookeeper.server.quorum.LeaderZooKeeperServer; import org.apache.zookeeper.server.quorum.ReadOnlyZooKeeperServer; import org.apache.zookeeper.server.util.OSMXBean; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.MessageEvent; public class NettyServerCnxn extends ServerCnxn { Logger LOG = LoggerFactory.getLogger(NettyServerCnxn.class); Channel channel; ChannelBuffer queuedBuffer; volatile boolean throttled; ByteBuffer bb; ByteBuffer bbLen = ByteBuffer.allocate(4); long sessionId; int sessionTimeout; AtomicLong outstandingCount = new AtomicLong(); /** The ZooKeeperServer for this connection. May be null if the server * is not currently serving requests (for example if the server is not * an active quorum participant. */ private volatile ZooKeeperServer zkServer; NettyServerCnxnFactory factory; boolean initialized; NettyServerCnxn(Channel channel, ZooKeeperServer zks, NettyServerCnxnFactory factory) { this.channel = channel; this.zkServer = zks; this.factory = factory; if (this.factory.login != null) { this.zooKeeperSaslServer = new ZooKeeperSaslServer(factory.login); } } @Override public void close() { if (LOG.isDebugEnabled()) { LOG.debug("close called for sessionid:0x" + Long.toHexString(sessionId)); } synchronized(factory.cnxns){ // if this is not in cnxns then it's already closed if (!factory.cnxns.remove(this)) { if (LOG.isDebugEnabled()) { LOG.debug("cnxns size:" + factory.cnxns.size()); } return; } if (LOG.isDebugEnabled()) { LOG.debug("close in progress for sessionid:0x" + Long.toHexString(sessionId)); } synchronized (factory.ipMap) { Set<NettyServerCnxn> s = factory.ipMap.get(((InetSocketAddress)channel .getRemoteAddress()).getAddress()); s.remove(this); } } if (channel.isOpen()) { channel.close(); } factory.unregisterConnection(this); } @Override public long getSessionId() { return sessionId; } @Override public int getSessionTimeout() { return sessionTimeout; } @Override public void process(WatchedEvent event) { ReplyHeader h = new ReplyHeader(-1, -1L, 0); if (LOG.isTraceEnabled()) { ZooTrace.logTraceMessage(LOG, ZooTrace.EVENT_DELIVERY_TRACE_MASK, "Deliver event " + event + " to 0x" + Long.toHexString(this.sessionId) + " through " + this); } // Convert WatchedEvent to a type that can be sent over the wire WatcherEvent e = event.getWrapper(); try { sendResponse(h, e, "notification"); } catch (IOException e1) { if (LOG.isDebugEnabled()) { LOG.debug("Problem sending to " + getRemoteSocketAddress(), e1); } close(); } } private static final byte[] fourBytes = new byte[4]; static class ResumeMessageEvent implements MessageEvent { Channel channel; ResumeMessageEvent(Channel channel) { this.channel = channel; } @Override public Object getMessage() {return null;} @Override public SocketAddress getRemoteAddress() {return null;} @Override public Channel getChannel() {return channel;} @Override public ChannelFuture getFuture() {return null;} }; @Override public void sendResponse(ReplyHeader h, Record r, String tag) throws IOException { if (!channel.isOpen()) { return; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Make space for length BinaryOutputArchive bos = BinaryOutputArchive.getArchive(baos); try { baos.write(fourBytes); bos.writeRecord(h, "header"); if (r != null) { bos.writeRecord(r, tag); } baos.close(); } catch (IOException e) { LOG.error("Error serializing response"); } byte b[] = baos.toByteArray(); ByteBuffer bb = ByteBuffer.wrap(b); bb.putInt(b.length - 4).rewind(); sendBuffer(bb); if (h.getXid() > 0) { // zks cannot be null otherwise we would not have gotten here! if (!zkServer.shouldThrottle(outstandingCount.decrementAndGet())) { enableRecv(); } } } @Override public void setSessionId(long sessionId) { this.sessionId = sessionId; } @Override public void enableRecv() { if (throttled) { throttled = false; if (LOG.isDebugEnabled()) { LOG.debug("Sending unthrottle event " + this); } channel.getPipeline().sendUpstream(new ResumeMessageEvent(channel)); } } @Override public void sendBuffer(ByteBuffer sendBuffer) { if (sendBuffer == ServerCnxnFactory.closeConn) { close(); return; } channel.write(wrappedBuffer(sendBuffer)); packetSent(); } /** * clean up the socket related to a command and also make sure we flush the * data before we do that * * @param pwriter * the pwriter for a command socket */ private void cleanupWriterSocket(PrintWriter pwriter) { try { if (pwriter != null) { pwriter.flush(); pwriter.close(); } } catch (Exception e) { LOG.info("Error closing PrintWriter ", e); } finally { try { close(); } catch (Exception e) { LOG.error("Error closing a command socket ", e); } } } /** * This class wraps the sendBuffer method of NIOServerCnxn. It is * responsible for chunking up the response to a client. Rather * than cons'ing up a response fully in memory, which may be large * for some commands, this class chunks up the result. */ private class SendBufferWriter extends Writer { private StringBuffer sb = new StringBuffer(); /** * Check if we are ready to send another chunk. * @param force force sending, even if not a full chunk */ private void checkFlush(boolean force) { if ((force && sb.length() > 0) || sb.length() > 2048) { sendBuffer(ByteBuffer.wrap(sb.toString().getBytes())); // clear our internal buffer sb.setLength(0); } } @Override public void close() throws IOException { if (sb == null) return; checkFlush(true); sb = null; // clear out the ref to ensure no reuse } @Override public void flush() throws IOException { checkFlush(true); } @Override public void write(char[] cbuf, int off, int len) throws IOException { sb.append(cbuf, off, len); checkFlush(false); } } private static final String ZK_NOT_SERVING = "This ZooKeeper instance is not currently serving requests"; /** * Set of threads for commmand ports. All the 4 * letter commands are run via a thread. Each class * maps to a correspoding 4 letter command. CommandThread * is the abstract class from which all the others inherit. */ private abstract class CommandThread /*extends Thread*/ { PrintWriter pw; CommandThread(PrintWriter pw) { this.pw = pw; } public void start() { run(); } public void run() { try { commandRun(); } catch (IOException ie) { LOG.error("Error in running command ", ie); } finally { cleanupWriterSocket(pw); } } public abstract void commandRun() throws IOException; } private class RuokCommand extends CommandThread { public RuokCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { pw.print("imok"); } } private class TraceMaskCommand extends CommandThread { TraceMaskCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { long traceMask = ZooTrace.getTextTraceLevel(); pw.print(traceMask); } } private class SetTraceMaskCommand extends CommandThread { long trace = 0; SetTraceMaskCommand(PrintWriter pw, long trace) { super(pw); this.trace = trace; } @Override public void commandRun() { pw.print(trace); } } private class EnvCommand extends CommandThread { EnvCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { List<Environment.Entry> env = Environment.list(); pw.println("Environment:"); for(Environment.Entry e : env) { pw.print(e.getKey()); pw.print("="); pw.println(e.getValue()); } } } private class ConfCommand extends CommandThread { ConfCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { if (!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); } else { zkServer.dumpConf(pw); } } } private class StatResetCommand extends CommandThread { public StatResetCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { if (!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); } else { zkServer.serverStats().reset(); pw.println("Server stats reset."); } } } private class CnxnStatResetCommand extends CommandThread { public CnxnStatResetCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { if (!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); } else { synchronized(factory.cnxns){ for(ServerCnxn c : factory.cnxns){ c.resetStats(); } } pw.println("Connection stats reset."); } } } private class DumpCommand extends CommandThread { public DumpCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { if (!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); } else { pw.println("SessionTracker dump:"); zkServer.sessionTracker.dumpSessions(pw); pw.println("ephemeral nodes dump:"); zkServer.dumpEphemerals(pw); } } } private class StatCommand extends CommandThread { int len; public StatCommand(PrintWriter pw, int len) { super(pw); this.len = len; } @Override public void commandRun() { if (!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); } else { pw.print("Zookeeper version: "); pw.println(Version.getFullVersion()); if (zkServer instanceof ReadOnlyZooKeeperServer) { pw.println("READ-ONLY mode; serving only " + "read-only clients"); } if (len == statCmd) { LOG.info("Stat command output"); pw.println("Clients:"); // clone should be faster than iteration // ie give up the cnxns lock faster HashSet<ServerCnxn> cnxns; synchronized(factory.cnxns){ cnxns = new HashSet<ServerCnxn>(factory.cnxns); } for(ServerCnxn c : cnxns){ c.dumpConnectionInfo(pw, true); pw.println(); } pw.println(); } pw.print(zkServer.serverStats().toString()); pw.print("Node count: "); pw.println(zkServer.getZKDatabase().getNodeCount()); } } } private class ConsCommand extends CommandThread { public ConsCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { if (!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); } else { // clone should be faster than iteration // ie give up the cnxns lock faster AbstractSet<ServerCnxn> cnxns; synchronized (factory.cnxns) { cnxns = new HashSet<ServerCnxn>(factory.cnxns); } for (ServerCnxn c : cnxns) { c.dumpConnectionInfo(pw, false); pw.println(); } pw.println(); } } } private class WatchCommand extends CommandThread { int len = 0; public WatchCommand(PrintWriter pw, int len) { super(pw); this.len = len; } @Override public void commandRun() { if (!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); } else { DataTree dt = zkServer.getZKDatabase().getDataTree(); if (len == wchsCmd) { dt.dumpWatchesSummary(pw); } else if (len == wchpCmd) { dt.dumpWatches(pw, true); } else { dt.dumpWatches(pw, false); } pw.println(); } } } private class MonitorCommand extends CommandThread { MonitorCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { if(!isZKServerRunning()) { pw.println(ZK_NOT_SERVING); return; } ZKDatabase zkdb = zkServer.getZKDatabase(); ServerStats stats = zkServer.serverStats(); print("version", Version.getFullVersion()); print("avg_latency", stats.getAvgLatency()); print("max_latency", stats.getMaxLatency()); print("min_latency", stats.getMinLatency()); print("packets_received", stats.getPacketsReceived()); print("packets_sent", stats.getPacketsSent()); print("num_alive_connections", stats.getNumAliveClientConnections()); print("outstanding_requests", stats.getOutstandingRequests()); print("server_state", stats.getServerState()); print("znode_count", zkdb.getNodeCount()); print("watch_count", zkdb.getDataTree().getWatchCount()); print("ephemerals_count", zkdb.getDataTree().getEphemeralsCount()); print("approximate_data_size", zkdb.getDataTree().approximateDataSize()); OSMXBean osMbean = new OSMXBean(); if (osMbean != null && osMbean.getUnix() == true) { print("open_file_descriptor_count", osMbean.getOpenFileDescriptorCount()); print("max_file_descriptor_count", osMbean.getMaxFileDescriptorCount()); } if(stats.getServerState().equals("leader")) { Leader leader = ((LeaderZooKeeperServer)zkServer).getLeader(); print("followers", leader.getLearners().size()); print("synced_followers", leader.getForwardingFollowers().size()); print("pending_syncs", leader.getNumPendingSyncs()); } } private void print(String key, long number) { print(key, "" + number); } private void print(String key, String value) { pw.print("zk_"); pw.print(key); pw.print("\t"); pw.println(value); } } private class IsroCommand extends CommandThread { public IsroCommand(PrintWriter pw) { super(pw); } @Override public void commandRun() { if (!isZKServerRunning()) { pw.print("null"); } else if (zkServer instanceof ReadOnlyZooKeeperServer) { pw.print("ro"); } else { pw.print("rw"); } } } /** Return if four letter word found and responded to, otw false **/ private boolean checkFourLetterWord(final Channel channel, ChannelBuffer message, final int len) throws IOException { // We take advantage of the limited size of the length to look // for cmds. They are all 4-bytes which fits inside of an int String cmd = cmd2String.get(len); if (cmd == null) { return false; } channel.setInterestOps(0).awaitUninterruptibly(); LOG.info("Processing " + cmd + " command from " + channel.getRemoteAddress()); packetReceived(); final PrintWriter pwriter = new PrintWriter( new BufferedWriter(new SendBufferWriter())); if (len == ruokCmd) { RuokCommand ruok = new RuokCommand(pwriter); ruok.start(); return true; } else if (len == getTraceMaskCmd) { TraceMaskCommand tmask = new TraceMaskCommand(pwriter); tmask.start(); return true; } else if (len == setTraceMaskCmd) { ByteBuffer mask = ByteBuffer.allocate(8); message.readBytes(mask); mask.flip(); long traceMask = mask.getLong(); ZooTrace.setTextTraceLevel(traceMask); SetTraceMaskCommand setMask = new SetTraceMaskCommand(pwriter, traceMask); setMask.start(); return true; } else if (len == enviCmd) { EnvCommand env = new EnvCommand(pwriter); env.start(); return true; } else if (len == confCmd) { ConfCommand ccmd = new ConfCommand(pwriter); ccmd.start(); return true; } else if (len == srstCmd) { StatResetCommand strst = new StatResetCommand(pwriter); strst.start(); return true; } else if (len == crstCmd) { CnxnStatResetCommand crst = new CnxnStatResetCommand(pwriter); crst.start(); return true; } else if (len == dumpCmd) { DumpCommand dump = new DumpCommand(pwriter); dump.start(); return true; } else if (len == statCmd || len == srvrCmd) { StatCommand stat = new StatCommand(pwriter, len); stat.start(); return true; } else if (len == consCmd) { ConsCommand cons = new ConsCommand(pwriter); cons.start(); return true; } else if (len == wchpCmd || len == wchcCmd || len == wchsCmd) { WatchCommand wcmd = new WatchCommand(pwriter, len); wcmd.start(); return true; } else if (len == mntrCmd) { MonitorCommand mntr = new MonitorCommand(pwriter); mntr.start(); return true; } else if (len == isroCmd) { IsroCommand isro = new IsroCommand(pwriter); isro.start(); return true; } return false; } public void receiveMessage(ChannelBuffer message) { try { while(message.readable() && !throttled) { if (bb != null) { if (LOG.isTraceEnabled()) { LOG.trace("message readable " + message.readableBytes() + " bb len " + bb.remaining() + " " + bb); ByteBuffer dat = bb.duplicate(); dat.flip(); LOG.trace(Long.toHexString(sessionId) + " bb 0x" + ChannelBuffers.hexDump( ChannelBuffers.copiedBuffer(dat))); } if (bb.remaining() > message.readableBytes()) { int newLimit = bb.position() + message.readableBytes(); bb.limit(newLimit); } message.readBytes(bb); bb.limit(bb.capacity()); if (LOG.isTraceEnabled()) { LOG.trace("after readBytes message readable " + message.readableBytes() + " bb len " + bb.remaining() + " " + bb); ByteBuffer dat = bb.duplicate(); dat.flip(); LOG.trace("after readbytes " + Long.toHexString(sessionId) + " bb 0x" + ChannelBuffers.hexDump( ChannelBuffers.copiedBuffer(dat))); } if (bb.remaining() == 0) { packetReceived(); bb.flip(); ZooKeeperServer zks = this.zkServer; if (zks == null || !zks.isRunning()) { throw new IOException("ZK down"); } if (initialized) { zks.processPacket(this, bb); if (zks.shouldThrottle(outstandingCount.incrementAndGet())) { disableRecvNoWait(); } } else { LOG.debug("got conn req request from " + getRemoteSocketAddress()); zks.processConnectRequest(this, bb); initialized = true; } bb = null; } } else { if (LOG.isTraceEnabled()) { LOG.trace("message readable " + message.readableBytes() + " bblenrem " + bbLen.remaining()); ByteBuffer dat = bbLen.duplicate(); dat.flip(); LOG.trace(Long.toHexString(sessionId) + " bbLen 0x" + ChannelBuffers.hexDump( ChannelBuffers.copiedBuffer(dat))); } if (message.readableBytes() < bbLen.remaining()) { bbLen.limit(bbLen.position() + message.readableBytes()); } message.readBytes(bbLen); bbLen.limit(bbLen.capacity()); if (bbLen.remaining() == 0) { bbLen.flip(); if (LOG.isTraceEnabled()) { LOG.trace(Long.toHexString(sessionId) + " bbLen 0x" + ChannelBuffers.hexDump( ChannelBuffers.copiedBuffer(bbLen))); } int len = bbLen.getInt(); if (LOG.isTraceEnabled()) { LOG.trace(Long.toHexString(sessionId) + " bbLen len is " + len); } bbLen.clear(); if (!initialized) { if (checkFourLetterWord(channel, message, len)) { return; } } if (len < 0 || len > BinaryInputArchive.maxBuffer) { throw new IOException("Len error " + len); } bb = ByteBuffer.allocate(len); } } } } catch(IOException e) { LOG.warn("Closing connection to " + getRemoteSocketAddress(), e); close(); } } @Override public void disableRecv() { disableRecvNoWait().awaitUninterruptibly(); } private ChannelFuture disableRecvNoWait() { throttled = true; if (LOG.isDebugEnabled()) { LOG.debug("Throttling - disabling recv " + this); } return channel.setReadable(false); } @Override public long getOutstandingRequests() { return outstandingCount.longValue(); } @Override public void setSessionTimeout(int sessionTimeout) { this.sessionTimeout = sessionTimeout; } @Override public int getInterestOps() { return channel.getInterestOps(); } @Override public InetSocketAddress getRemoteSocketAddress() { return (InetSocketAddress)channel.getRemoteAddress(); } /** Send close connection packet to the client. */ @Override public void sendCloseSession() { sendBuffer(ServerCnxnFactory.closeConn); } @Override protected ServerStats serverStats() { if (!isZKServerRunning()) { return null; } return zkServer.serverStats(); } /** * @return true if the server is running, false otherwise. */ boolean isZKServerRunning() { return zkServer != null && zkServer.isRunning(); } }
[ "archen94@gmail.com" ]
archen94@gmail.com
5956123bdf89ad15ff86ec77d56fe906a7df580f
2924d8078ea66581cd665fdc463687b1b329df3c
/src/main/java/pers/robin/revolver/dao/UserDao.java
341a1a53a4d0dc4cf5b8342c58fef532fe741da9
[]
no_license
ChowRobin/revolver
a14e0352d1738bb68b3e0dc3643615e8ad2913d1
df8f47658651ec320a35b25249ce8be624fe2ff8
refs/heads/master
2021-08-07T02:21:24.713629
2018-11-19T04:59:51
2018-11-19T04:59:51
136,633,248
0
0
null
null
null
null
UTF-8
Java
false
false
415
java
package pers.robin.revolver.dao; import org.apache.ibatis.annotations.Mapper; import pers.robin.revolver.model.User; import java.util.List; import java.util.Map; @Mapper public interface UserDao { List<User> getList(Map<String, Object> map); User read(Integer id); User findByUserName(String userName); Integer create(User user); void update(User user); void delete(Integer id); }
[ "robinchow8991@gmail.com" ]
robinchow8991@gmail.com
f6d36b21cee89046704bc61990e94ddcbec5c926
fb585b533edc581175abe8cfa291931b04a3cfba
/src/main/java/com/bank/example/dao/EventDaoImpl.java
9643277824762eec229f7939a379335f672413ec
[]
no_license
IvanCherepica/bank
21a6575ad976cfb16ef7aa9dfe38d015285f7462
b102a3ded9ad755696697b3fbb26afe190acb11f
refs/heads/master
2023-04-05T09:23:23.212951
2021-04-08T13:35:45
2021-04-08T13:35:45
355,922,780
1
0
null
null
null
null
UTF-8
Java
false
false
214
java
package com.bank.example.dao; import com.bank.example.model.Event; import org.springframework.stereotype.Repository; @Repository public class EventDaoImpl extends AbstractDao<Long, Event> implements EventDao { }
[ "ussr211114@gmail.com" ]
ussr211114@gmail.com
139bd507d62d2eaf6ba400987562e1d49338ff90
f7f6a1fcdb117c9dd2caceb02453a4a2c3603fa6
/code/java-study/src/main/java/com/xl/java/week8/FileCopy.java
3ce239011c79832f91313bc8db684de50348456c
[]
no_license
772766964/Java-study
98b81b7a5713f18fe5c34ec7ab937d9b5aad6f13
6683ba2f4049643dcf45ca52a5390351401554dd
refs/heads/main
2023-01-05T23:16:42.738317
2020-11-01T14:53:13
2020-11-01T14:53:13
302,222,085
0
0
null
null
null
null
UTF-8
Java
false
false
1,732
java
package com.xl.java.week8; import lombok.ToString; import java.io.*; import java.util.Arrays; import java.util.UUID; /** * @ClassName FileCopy * @Description TODO * @Author 1 * @Date 2020/10/29 **/ public class FileCopy { public static void main(String[] args) throws IOException { /* //1. 将源文件读入内存数组 File file = new File("C:/Users/1/Pictures/0.jpg"); InputStream is = new FileInputStream(file); byte[] b = new byte[(int) file.length()]; int readResult = is.read(b); System.out.println(Arrays.toString(b)); System.out.println(readResult); //2. 将内存数组中的值写到目标文件 File file2 = new File("C:/Users/1/Pictures/" + UUID.randomUUID().toString() + ".jpg"); OutputStream os = new FileOutputStream(file2); os.write(b); os.close(); is.close(); */ //1、将源文件读入内存数组 File inputFile = new File("C:/Users/1/Pictures/a.txt"); InputStream file1 = new FileInputStream(inputFile); InputStreamReader is = new InputStreamReader(file1); char[] b = new char[(char) inputFile.length()]; //read没有返回值 int read = is.read(b); System.out.println(b); System.out.println(read); //2、将内存数组中的值写到目标文件 File outputFile = new File("C:/Users/1/Pictures/" + UUID.randomUUID().toString() + ".txt"); OutputStream file2 = new FileOutputStream(outputFile); OutputStreamWriter os = new OutputStreamWriter(file2); os.write(b); is.close(); os.close(); } }
[ "772766964@qq.com" ]
772766964@qq.com
a06c5a9028d700b1649207b83f25370cc3155c00
c7a3d5be5b36617a611bd00a3ef31893cbc6e2cb
/iTesaApp/src/com/funellites/iTesa/Graph.java
729741ccb77954e8327adc376243450442e6f670
[ "Apache-2.0" ]
permissive
jakubczaplicki/iTesa
4aca0d08d1b6174aea7de0266389a824cdbf59a9
98dd21f191f8813cc8ab70668d052ce3e9751b02
refs/heads/master
2021-01-21T09:50:00.270078
2012-03-21T18:31:24
2012-03-21T18:31:24
2,446,393
2
0
null
null
null
null
UTF-8
Java
false
false
4,162
java
/* * Copyright (C) 2011 The iTesa 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.funellites.iTesa; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.util.Log; public class Graph { public final static String TAG = "iTesa"; private static final String KEY_LAT = "lat"; private static final String KEY_LNG = "lng"; private static final String KEY_ABSB = "absB"; static DBAdapter dbAdapter; static String dataDirName; static String pngFileName; public Graph(DBAdapter _dbAdapter, String _dataDirName, String _pngFileName ) { dbAdapter = _dbAdapter; dataDirName = _dataDirName; pngFileName = _pngFileName; } private static final int WIDTH = 1200; //1440; private static final int HEIGHT = 600; //720; private static final int STRIDE = WIDTH; // must be >= WIDTH public void updateBitmap() { /* Database related code */ long lastRow = dbAdapter.getLastCursor(); Cursor cursor = dbAdapter.getDataTelemetry( lastRow ); // Log.d(TAG, "Last row was : "+ lastRow); /* Load PNG bitmap */ String path = Environment.getExternalStorageDirectory().toString(); File file = new File(path + "/" + dataDirName + "/" + pngFileName); Bitmap bitmap = null; try { InputStream inStream = new FileInputStream(file); bitmap = BitmapFactory.decodeStream(inStream).copy(Bitmap.Config.ARGB_8888, true); } catch (Exception e) { Log.e(TAG,"Can't load the png file."); Log.e(TAG,e.getMessage()); } /* Modify bitmap based on data from sqlite */ int[] colors = new int[ WIDTH * HEIGHT ]; bitmap.getPixels(colors, 0, STRIDE, 0, 0, WIDTH , HEIGHT ); if (cursor.moveToFirst()) { do { float lng = cursor.getFloat(cursor.getColumnIndex(KEY_LNG)); float lat = cursor.getFloat(cursor.getColumnIndex(KEY_LAT)); float absB = cursor.getFloat(cursor.getColumnIndex(KEY_ABSB)); /* TODO: this needs reworking and rescaling */ int r = (int) ( (double) absB * 255.0 / 200.0); int g = (int) ( (double) absB * 255.0 / 200.0); int b = 255 - Math.min(r, g); int a = 255; int x = (int) ( (double) lng * ( (double) (WIDTH-1) / 360.0 ) ); int y = (int) ( (double) lat * ( (double) (HEIGHT-1) / 180.0 ) ); Log.d(TAG, "" + x + "," + y); if ((y * WIDTH + x) < (WIDTH * HEIGHT) ) colors[y * WIDTH + x] = (a << 24) | (r << 16) | (g << 8) | b; else Log.d(TAG,"Array out of bounds !!"); } while(cursor.moveToNext()); dbAdapter.updateCursors( lastRow + (long) cursor.getPosition() ); // Log.d(TAG, "Last cursor pos: "+ (lastRow + cursor.getPosition()) ); } bitmap.setPixels(colors, 0, STRIDE, 0, 0, WIDTH , HEIGHT ); /* Save bitmap */ try { OutputStream outStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 85, outStream); outStream.flush(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
[ "jakub.czaplicki@gmail.com" ]
jakub.czaplicki@gmail.com
374fa62dac87ad21926ac98656ad754d53574057
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-workmail/src/main/java/com/amazonaws/services/workmail/model/GetMobileDeviceAccessOverrideResult.java
b0dea47bf7c61b869b793f2964f3da326fbd35fc
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379135
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
2023-09-13T23:35:28
2010-03-22T23:34:58
null
UTF-8
Java
false
false
12,195
java
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.workmail.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/GetMobileDeviceAccessOverride" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetMobileDeviceAccessOverrideResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The WorkMail user to which the access override applies. * </p> */ private String userId; /** * <p> * The device to which the access override applies. * </p> */ private String deviceId; /** * <p> * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * </p> */ private String effect; /** * <p> * A description of the override. * </p> */ private String description; /** * <p> * The date the override was first created. * </p> */ private java.util.Date dateCreated; /** * <p> * The date the description was last modified. * </p> */ private java.util.Date dateModified; /** * <p> * The WorkMail user to which the access override applies. * </p> * * @param userId * The WorkMail user to which the access override applies. */ public void setUserId(String userId) { this.userId = userId; } /** * <p> * The WorkMail user to which the access override applies. * </p> * * @return The WorkMail user to which the access override applies. */ public String getUserId() { return this.userId; } /** * <p> * The WorkMail user to which the access override applies. * </p> * * @param userId * The WorkMail user to which the access override applies. * @return Returns a reference to this object so that method calls can be chained together. */ public GetMobileDeviceAccessOverrideResult withUserId(String userId) { setUserId(userId); return this; } /** * <p> * The device to which the access override applies. * </p> * * @param deviceId * The device to which the access override applies. */ public void setDeviceId(String deviceId) { this.deviceId = deviceId; } /** * <p> * The device to which the access override applies. * </p> * * @return The device to which the access override applies. */ public String getDeviceId() { return this.deviceId; } /** * <p> * The device to which the access override applies. * </p> * * @param deviceId * The device to which the access override applies. * @return Returns a reference to this object so that method calls can be chained together. */ public GetMobileDeviceAccessOverrideResult withDeviceId(String deviceId) { setDeviceId(deviceId); return this; } /** * <p> * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * </p> * * @param effect * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * @see MobileDeviceAccessRuleEffect */ public void setEffect(String effect) { this.effect = effect; } /** * <p> * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * </p> * * @return The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * @see MobileDeviceAccessRuleEffect */ public String getEffect() { return this.effect; } /** * <p> * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * </p> * * @param effect * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see MobileDeviceAccessRuleEffect */ public GetMobileDeviceAccessOverrideResult withEffect(String effect) { setEffect(effect); return this; } /** * <p> * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * </p> * * @param effect * The effect of the override, <code>ALLOW</code> or <code>DENY</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see MobileDeviceAccessRuleEffect */ public GetMobileDeviceAccessOverrideResult withEffect(MobileDeviceAccessRuleEffect effect) { this.effect = effect.toString(); return this; } /** * <p> * A description of the override. * </p> * * @param description * A description of the override. */ public void setDescription(String description) { this.description = description; } /** * <p> * A description of the override. * </p> * * @return A description of the override. */ public String getDescription() { return this.description; } /** * <p> * A description of the override. * </p> * * @param description * A description of the override. * @return Returns a reference to this object so that method calls can be chained together. */ public GetMobileDeviceAccessOverrideResult withDescription(String description) { setDescription(description); return this; } /** * <p> * The date the override was first created. * </p> * * @param dateCreated * The date the override was first created. */ public void setDateCreated(java.util.Date dateCreated) { this.dateCreated = dateCreated; } /** * <p> * The date the override was first created. * </p> * * @return The date the override was first created. */ public java.util.Date getDateCreated() { return this.dateCreated; } /** * <p> * The date the override was first created. * </p> * * @param dateCreated * The date the override was first created. * @return Returns a reference to this object so that method calls can be chained together. */ public GetMobileDeviceAccessOverrideResult withDateCreated(java.util.Date dateCreated) { setDateCreated(dateCreated); return this; } /** * <p> * The date the description was last modified. * </p> * * @param dateModified * The date the description was last modified. */ public void setDateModified(java.util.Date dateModified) { this.dateModified = dateModified; } /** * <p> * The date the description was last modified. * </p> * * @return The date the description was last modified. */ public java.util.Date getDateModified() { return this.dateModified; } /** * <p> * The date the description was last modified. * </p> * * @param dateModified * The date the description was last modified. * @return Returns a reference to this object so that method calls can be chained together. */ public GetMobileDeviceAccessOverrideResult withDateModified(java.util.Date dateModified) { setDateModified(dateModified); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getUserId() != null) sb.append("UserId: ").append(getUserId()).append(","); if (getDeviceId() != null) sb.append("DeviceId: ").append(getDeviceId()).append(","); if (getEffect() != null) sb.append("Effect: ").append(getEffect()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getDateCreated() != null) sb.append("DateCreated: ").append(getDateCreated()).append(","); if (getDateModified() != null) sb.append("DateModified: ").append(getDateModified()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetMobileDeviceAccessOverrideResult == false) return false; GetMobileDeviceAccessOverrideResult other = (GetMobileDeviceAccessOverrideResult) obj; if (other.getUserId() == null ^ this.getUserId() == null) return false; if (other.getUserId() != null && other.getUserId().equals(this.getUserId()) == false) return false; if (other.getDeviceId() == null ^ this.getDeviceId() == null) return false; if (other.getDeviceId() != null && other.getDeviceId().equals(this.getDeviceId()) == false) return false; if (other.getEffect() == null ^ this.getEffect() == null) return false; if (other.getEffect() != null && other.getEffect().equals(this.getEffect()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getDateCreated() == null ^ this.getDateCreated() == null) return false; if (other.getDateCreated() != null && other.getDateCreated().equals(this.getDateCreated()) == false) return false; if (other.getDateModified() == null ^ this.getDateModified() == null) return false; if (other.getDateModified() != null && other.getDateModified().equals(this.getDateModified()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getUserId() == null) ? 0 : getUserId().hashCode()); hashCode = prime * hashCode + ((getDeviceId() == null) ? 0 : getDeviceId().hashCode()); hashCode = prime * hashCode + ((getEffect() == null) ? 0 : getEffect().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getDateCreated() == null) ? 0 : getDateCreated().hashCode()); hashCode = prime * hashCode + ((getDateModified() == null) ? 0 : getDateModified().hashCode()); return hashCode; } @Override public GetMobileDeviceAccessOverrideResult clone() { try { return (GetMobileDeviceAccessOverrideResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
[ "" ]
6e9014ac2d7a36664990d31fea47fb3a427cfec3
bd44d2fca4bf4983d8d6261b3473997cad7f15de
/app/src/main/java/com/vpulse/ftpnext/ftpnavigation/NavigationDelete.java
483c3318aca71df688966457f73c59f0850987b1
[]
no_license
AnderJoeSun/FTPNext
19cc40004d5fe77c3a6955964afe3d66537fe866
d857e4464201d410e7b083e5d38b3f1dcb294457
refs/heads/master
2021-05-16T22:31:21.619335
2020-03-24T22:07:01
2020-03-24T22:08:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,521
java
package com.vpulse.ftpnext.ftpnavigation; import android.content.DialogInterface; import android.os.Handler; import android.view.View; import android.widget.CheckBox; import android.widget.ProgressBar; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import com.vpulse.ftpnext.R; import org.apache.commons.net.ftp.FTPFile; import static com.vpulse.ftpnext.ftpnavigation.FTPNavigationActivity.NAVIGATION_MESSAGE_DELETE_FINISHED; import static com.vpulse.ftpnext.ftpnavigation.FTPNavigationActivity.NAVIGATION_ORDER_DISMISS_DIALOGS; import static com.vpulse.ftpnext.ftpnavigation.FTPNavigationActivity.NAVIGATION_ORDER_REFRESH_DATA; import static com.vpulse.ftpnext.ftpnavigation.FTPNavigationActivity.NAVIGATION_ORDER_SELECTED_MODE_OFF; public class NavigationDelete { private final static String TAG = "NAVIGATION DELETE"; private final FTPNavigationActivity mContextActivity; private final Handler mHandler; private NavigationDelete() throws InstantiationException { mContextActivity = null; mHandler = null; throw new InstantiationException("Constructor not allowed"); } protected NavigationDelete(FTPNavigationActivity iContextActivity, Handler iHandler) { mContextActivity = iContextActivity; mHandler = iHandler; } protected void onResume() { } protected void createDialogDeleteSelection() { final FTPFile[] lSelectedFiles = mContextActivity.mCurrentAdapter.getSelection(); if (lSelectedFiles.length == 0) mContextActivity.createDialogError("Select something.").show(); else { mContextActivity.mDeletingInfoDialog = new AlertDialog.Builder(mContextActivity) .setTitle("Deleting :") // TODO : Strings .setMessage("Are you sure to delete the selection ? (" + lSelectedFiles.length + " files)") .setPositiveButton("yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface iDialog, int iWhich) { iDialog.dismiss(); deleteFile(lSelectedFiles); } }) .setNegativeButton("cancel", null) .show(); } } private void deleteFile(FTPFile[] iSelectedFiles) { mHandler.sendEmptyMessage(NAVIGATION_ORDER_SELECTED_MODE_OFF); mContextActivity.mFTPServices.deleteFiles(iSelectedFiles, mContextActivity.mFTPServices.new OnDeleteListener() { ProgressBar mProgressDirectory; ProgressBar mProgressSubDirectory; TextView mTextViewDirectory; TextView mTextViewSubDirectory; @Override public void onStartDelete() { mHandler.post(new Runnable() { @Override public void run() { final AlertDialog.Builder lBuilder = new AlertDialog.Builder(mContextActivity); lBuilder.setTitle("Deleting"); // TODO : strings View lDialogDoubleProgress = View.inflate(mContextActivity, R.layout.dialog_double_progress, null); mProgressDirectory = lDialogDoubleProgress.findViewById(R.id.dialog_double_progress_progress_1); mTextViewDirectory = lDialogDoubleProgress.findViewById(R.id.dialog_double_progress_text_1); mProgressSubDirectory = lDialogDoubleProgress.findViewById(R.id.dialog_double_progress_progress_2); mTextViewSubDirectory = lDialogDoubleProgress.findViewById(R.id.dialog_double_progress_text_2); lBuilder.setView(lDialogDoubleProgress); lBuilder.setCancelable(false); lBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // TODO : Strings @Override public void onClick(DialogInterface dialog, int which) { stopDeleting(); } }); mContextActivity.mDeletingInfoDialog = lBuilder.create(); mContextActivity.mDeletingInfoDialog.show(); } }); } @Override public void onProgressDirectory(final int iDirectoryProgress, final int iTotalDirectories, final String iDirectoryName) { mHandler.post(new Runnable() { @Override public void run() { mTextViewDirectory.setText(iDirectoryName); mProgressDirectory.setMax(iTotalDirectories); mProgressDirectory.setProgress(iDirectoryProgress); } }); } @Override public void onProgressSubDirectory(final int iSubDirectoryProgress, final int iTotalSubDirectories, final String iSubDirectoryName) { mHandler.post(new Runnable() { @Override public void run() { mTextViewSubDirectory.setText(iSubDirectoryName); mProgressSubDirectory.setMax(iTotalSubDirectories); mProgressSubDirectory.setProgress(iSubDirectoryProgress); } }); } @Override public void onRightAccessFail(final FTPFile iFTPFile) { super.onRightAccessFail(iFTPFile); mHandler.post(new Runnable() { @Override public void run() { final AlertDialog.Builder lBuilder = new AlertDialog.Builder(mContextActivity); lBuilder.setTitle("Permission error"); // TODO : strings final View lDialogDeleteError = View.inflate(mContextActivity, R.layout.dialog_delete_error, null); final CheckBox lCheckBox = lDialogDeleteError.findViewById(R.id.dialog_delete_error_checkbox); final TextView lTextView = lDialogDeleteError.findViewById(R.id.dialog_delete_error_text); lTextView.setText("Remember this choice : "); // TODO : strings lBuilder.setView(lDialogDeleteError); String lMessage = "\nNot enough permissions to delete this " + (iFTPFile.isDirectory() ? "directory \n" : "file \n") + iFTPFile.getName(); lBuilder.setMessage(lMessage); lBuilder.setCancelable(false); lBuilder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface iDialog, int iWhich) { iDialog.dismiss(); mContextActivity.mFTPServices.setDeletingByPassRightErrors(lCheckBox.isChecked()); mContextActivity.mFTPServices.resumeDeleting(); } }); lBuilder.setNegativeButton("Stop", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface iDialog, int iWhich) { iDialog.dismiss(); stopDeleting(); } }); mContextActivity.mDeletingErrorDialog = lBuilder.create(); mContextActivity.mDeletingErrorDialog.show(); } }); } @Override public void onFinish() { successDelete(); } @Override public void onFail(final FTPFile iFTPFile) { super.onFail(iFTPFile); mHandler.post(new Runnable() { @Override public void run() { final AlertDialog.Builder lBuilder = new AlertDialog.Builder(mContextActivity); lBuilder.setTitle("Delete error"); // TODO : strings final View lDialogDeleteError = View.inflate(mContextActivity, R.layout.dialog_delete_error, null); final CheckBox lCheckBox = lDialogDeleteError.findViewById(R.id.dialog_delete_error_checkbox); final TextView lTextView = lDialogDeleteError.findViewById(R.id.dialog_delete_error_text); lTextView.setText("Remember this choice : "); // TODO : strings lBuilder.setView(lDialogDeleteError); String lMessage = "\nImpossible to delete the " + (iFTPFile.isDirectory() ? "directory \n" : "file \n") + iFTPFile.getName(); lBuilder.setMessage(lMessage); lBuilder.setCancelable(false); lBuilder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface iDialog, int iWhich) { iDialog.dismiss(); mContextActivity.mDeletingErrorDialog = null; if (mContextActivity.mDeletingInfoDialog != null) mContextActivity.mDeletingInfoDialog.show(); mContextActivity.mFTPServices.setDeletingByPassFailErrors(lCheckBox.isChecked()); mContextActivity.mFTPServices.resumeDeleting(); } }); lBuilder.setNegativeButton("Stop", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface iDialog, int iWhich) { iDialog.dismiss(); stopDeleting(); } }); if (mContextActivity.mDeletingInfoDialog != null) mContextActivity.mDeletingInfoDialog.hide(); mContextActivity.mDeletingErrorDialog = lBuilder.create(); mContextActivity.mDeletingErrorDialog.show(); } }); } }); } private void successDelete() { mHandler.sendEmptyMessage(NAVIGATION_ORDER_DISMISS_DIALOGS); mHandler.sendEmptyMessage(NAVIGATION_ORDER_REFRESH_DATA); mHandler.sendEmptyMessage(NAVIGATION_MESSAGE_DELETE_FINISHED); } private void stopDeleting() { mContextActivity.mCurrentAdapter.setSelectionMode(false); mContextActivity.mFTPServices.abortDeleting(); mHandler.sendEmptyMessage(NAVIGATION_ORDER_DISMISS_DIALOGS); mHandler.sendEmptyMessage(NAVIGATION_ORDER_REFRESH_DATA); mHandler.sendEmptyMessage(NAVIGATION_MESSAGE_DELETE_FINISHED); } }
[ "velocitypulse@outlook.fr" ]
velocitypulse@outlook.fr
1438a316719df4c9cb7875290e8be68e35113c9a
b0800ade34ccee8d476f0da92585ada838ef348c
/src/dbms/Delete.java
026b79c5c0f35f5c5ba092b3ecaaed07c7cda3d4
[]
no_license
ziadouf/JDBC
c34bd80c2eeb68b6666f46d1dab5144fbf897274
f4f918a8cbc1641a9104a0bc37e208f3b84f9012
refs/heads/master
2020-04-17T17:15:15.486969
2014-12-06T22:25:56
2014-12-06T22:25:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,640
java
package dbms; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class Delete { public static final String NOT_MATCH_CRITERIA = "no row exists with this criteria"; public static final String Con_Delete = "Row/s deleted"; public String delete(String path , String att , String value){ if(value!=null){ value = value.replaceAll("\'", ""); } boolean flag = false; try { File filepath = new File(path); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); Element root = doc.getDocumentElement(); NodeList staff = doc.getElementsByTagName("row"); for (int j=0; j<staff.getLength(); j++){ Node row = staff.item(j); if (att!=null){ NodeList list = row.getChildNodes(); for (int i =0; i<list.getLength(); i++) { Node node = list.item(i); if (att.equalsIgnoreCase((node.getNodeName())) && value.equals(node.getTextContent())){ flag = true ; root.removeChild(row); j--;//back step index } } } else { root.removeChild(row); j--;//back step index flag=true; } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(filepath); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } if (flag== true) return Con_Delete ; else return NOT_MATCH_CRITERIA; } }
[ "ziadouf93@gmail.com" ]
ziadouf93@gmail.com
ccdd61f610f36e36195bee7db912652e17a59c16
49f9046417b1420603609b2f9d6a890e0c593055
/src/main/java/asst/dbase/SelectorUSPhoneNumber.java
aa099629203e55bc8d01f86236d1154439c84617
[]
no_license
wataylor/biblerefs
512ed2b03253dabbf299f0f0484d46e3d0ac5780
2a75a2e7acc842461a4d7915763cf0297f2191a3
refs/heads/master
2023-01-22T07:10:03.815992
2020-12-05T23:15:02
2020-12-05T23:15:02
288,609,395
0
0
null
null
null
null
UTF-8
Java
false
false
7,532
java
/* @name SelectorUSPhoneNumber.java Copyright (c) 2007 by Advanced Systems and Software Technologies. All Rights Reserved Under revision by: $Locker: $ Change Log: $Log: SelectorUSPhoneNumber.java,v $ Revision 1.1 2007/06/15 18:17:09 asst upload */ package asst.dbase; import javax.servlet.http.HttpServletRequest; import asst.dbase.SelectorFieldPreload; /** * Generate 3 input text fields into which to type Maerican-style * telephone numbers. * @author WEB Development * @version %I%, %G% * @since * * @see <classname> */ public class SelectorUSPhoneNumber extends SelectorFieldPreload { /** Definition of the up and down arrows for each line of a group of * phone numbers. These arrows call a JavaScript function which * moves the selected phone number.*/ public static final String UDRO = "<input type=\"image\" onClick='javascript:phUp(\"__\")' src=\"images/UpArrow.png\"><input type=\"image\" onClick='javascript:phDn(\"__\")' src=\"images/DownArrow.png\">"; boolean wantJavaScript; /** Obligatory constructor.*/ public SelectorUSPhoneNumber() { super(); } /** * Constructor that sets the field name, database table name, and * database column. * @param name The name by which the form field generated by getHTML * is identified; this name has NOTHING to do with the database. * This name is used when attempting to retrieve the current * user-entered value from the form. This name should not contain * spaces if the fields are to be manipulated by JavaScript. If * spaces are simulated by underscores, the method getPrettyName * should be used to retrieve a human-readable name from this field. * @param table The name of the database table in which the field is * stored. This table is expected to be referenced by a * field which is to be passed to TwixtTableAndForm. * @param column The name of the database column within the table * which stores the field value. The column is assumed to store * character data because SQL TIMESTAMP columns are updated as if * they were character constants. The choice is stored as an SQL * time string in JDBC escape format which is yyyy-mm-dd hh:mm:ss * This format is enforced by {@link * asst.dbase.SelectorFieldPreload#SQL_DATE_STRING} */ public SelectorUSPhoneNumber(String name, String table, String column) { super(name, table, column); } /** Read a set of selectors which set a phone number. @param name is the name of the set of selectors, various strings are added to the name to read the request. @param request the servlet request object from which values are extracted.*/ public String ReadPhoneNoFields(String nameP, HttpServletRequest request) { String answer; String ac; String ex; String no; /**/ ac=request.getParameter(nameP+"_ac"); ex=request.getParameter(nameP+"_ex"); no=request.getParameter(nameP+"_no"); if ((ac == null) || ES.equals(ac) || (ex == null) || ES.equals(ex) || (no == null) || ES.equals(no)) { return null; } // Nothing set in form answer = ac + ex + no; // System.out.println(name + " " + ac + " " + ex + " " + no + " " + // begins + " " + answer); return answer; } public StringBuffer makePhoneFields(String phoneNo, String nameP) { StringBuffer sb = new StringBuffer(); String ac; String ex; String no; /**/ try { ac = phoneNo.substring(0, 3); } catch (Exception e) { ac = ES; } try { ex = phoneNo.substring(3, 6); } catch (Exception e) { ex = ES; } try { no = phoneNo.substring(6); } catch (Exception e) { no = ES; } sb.append("<input name=\"" + nameP + "_ac\" size=\"2\" maxlength=\"3\" value=\"" + ac + "\""); if (wantJavaScript) { sb.append(" onKeyPress='return filterNums(event,this,3)' onKeyUp='mayGoOn(event,this,3)'"); } sb.append(this.addParam + "> -\n"); sb.append("<input name=\"" + nameP + "_ex\" size=\"2\" maxlength=\"3\" value=\"" + ex + "\""); if (wantJavaScript) { sb.append(" onKeyPress='return filterNums(event,this,3)' onKeyUp='mayGoOn(event,this,3)'"); } sb.append(this.addParam + "> -\n"); sb.append("<input name=\"" + nameP + "_no\" size=\"3\" maxlength=\"4\" value=\"" + no + "\""); if (wantJavaScript) { sb.append(" onKeyPress='return filterNums(event,this,4)' onKeyUp='mayGoOn(event,this,4)'"); } sb.append(this.addParam + ">\n"); // if (wantJavaScript) { // sb.append(UDRO.replace("__", name)); forces form resubmit somewhy // } return sb; } /** Ask the form to record the current form value which has been entered for its field. If the form returns a null value, the field was not mentioned in the form so the form has no effect on this selector object. If the field returns a different value, however, the dirty bit is set to indicate that the field must be written to the database. There is one exception - if the field has a null value and the form returns an empty string, this is not regarded as a change. @param request from the form wich may have a parameter whose name matches the name of this object, in which case the parameter value replaces the current choice.*/ public void setChoice(HttpServletRequest request) { String aParam; /**/ aParam = this.fieldNamePrefix + this.name; aParam = this.ReadPhoneNoFields(aParam, request); this.setDirtyChoice(aParam); //System.out.println(this.name + " " + aParam + " " + this.choice); } public String getChoiceAsText() { String phoneNo = getChoice(); String ac; String ex; String no; /**/ try { ac = phoneNo.substring(0, 3); } catch (Exception e) { ac = ES; } try { ex = phoneNo.substring(3, 6); } catch (Exception e) { ex = ES; } try { no = phoneNo.substring(6); } catch (Exception e) { no = ES; } return ac + "-" + ex + "-" + no; } /** Express the field in .html without labeling it, using a specified width. */ public StringBuffer getHTMLOnly(int width) { String cho = ES; /**/ if (readOnly) { return new StringBuffer(getChoiceAsText()); } if (this.choice != null) { cho = this.choice; } return this.makePhoneFields(cho, this.fieldNamePrefix + this.name); } /** Express the field as labeled .html. */ public StringBuffer getHTML() { return this.getHTML(0); } /** Express the field as labeled .html. */ public StringBuffer getHTML( int width) { StringBuffer sb; /**/ sb = new StringBuffer(this.getPrettyName() + ": "); if (readOnly) { sb.append(getChoiceAsText()); // Uneditable } else { sb.append(this.getHTMLOnly(width)); } return sb; } /** Test to see if this instance generates code to call Java Script * functions to make sure that only numbers are entered and that the * cursor goes to the next field when a field has enough numbers.*/ public boolean isWantJavaScript() { return wantJavaScript; } /** * Set the variable which determines whether the .html includes * event handlers to verify that only numbers are entered into the * phone number and to move the cursor to the next field when the * right number of numbers have been entered. * @param wantJavaScript */ public void setWantJavaScript(boolean wantJavaScript) { this.wantJavaScript = wantJavaScript; } }
[ "wataylor@alum.mit.edu" ]
wataylor@alum.mit.edu
408932d9aabf1d7f9ef2d58279f113d0536b9ffc
2047f79b878ca3669d60fa571eee8d04ac334384
/src/main/java/com/example/Phase12/sections/Department.java
d2d38198d07af5d0a4dbf999fdf79ce7caf05514
[]
no_license
ahmedelsafty70/system-manages-RESTAPI
5b9a28d750cabf6b06cc8a106d2c7a8af35557be
efbd92944dfa4b515216d8c22aa76c5cb5d69850
refs/heads/main
2023-08-16T09:08:16.718427
2021-09-22T17:29:00
2021-09-22T17:29:00
397,904,922
0
0
null
null
null
null
UTF-8
Java
false
false
557
java
package com.example.Phase12.sections; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.List; @Entity @Table @Getter @Setter @NoArgsConstructor public class Department { @Id @Column(name = "id") private int id; @Column(name = "departmentName") private String name; @JsonIgnore @OneToMany(mappedBy = "department", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private List<Employee> employees; }
[ "ahmedelsafty70@gmail.com" ]
ahmedelsafty70@gmail.com
e103d5f76dcd6066f00244e05222d7d39e636eab
bc544516346a296858d6f38558fcf352c593ee4a
/http/src/main/java/com/ysy/http/IEntity.java
68d82a1c5491b2e416d76d65dff452699217b84f
[]
no_license
yeshiyuan00/ysy_http
d5e669eff27547794e26d4dd3a13d88d7e949b83
d78e63deab4f936ed5dfe3d6272bfa7805132533
refs/heads/master
2021-01-22T07:02:44.086689
2015-09-19T08:55:23
2015-09-19T08:55:23
41,144,406
0
0
null
null
null
null
UTF-8
Java
false
false
227
java
package com.ysy.http; import com.google.gson.stream.JsonReader; /** * Created by Stay on 15/7/15. * Powered by www.stay4it.com */ public interface IEntity { void readFromJson(JsonReader reader) throws AppException; }
[ "yeshiyuan00@gmail.com" ]
yeshiyuan00@gmail.com
ca90e1fe806a1274cf7b095f81f6f266451da403
b9e9f6c119386d58660aecc895d16290a43253f4
/jooq2/src/main/java/com/izhaoyan/jooq2/controller/UpLoadController.java
445c69ae5ee6f9e2dcbac429b2370f90480162dc
[]
no_license
snailbinich/boat
e3694f27d985b08394fea6a2a38e280f3372d136
e676627c7948f16f6817c1345c13a75607acb9f0
refs/heads/master
2021-01-10T03:33:05.818282
2016-01-14T01:07:03
2016-01-14T01:07:03
44,463,747
0
0
null
null
null
null
UTF-8
Java
false
false
4,974
java
package com.izhaoyan.jooq2.controller; import org.apache.tomcat.util.http.fileupload.FileUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by zhaoyan on 15-12-7. */ @Controller public class UpLoadController { private String[] fileNames; private String allowSuffix = "jpg,png,gif,jpeg"; private long allowSize = 2L;//允许文件大小 private String fileName; @RequestMapping("/upload") public String index(){ return "index"; } public void upload(MultipartFile[] files, HttpServletRequest request) throws Exception { String destDir = "/home/zhaoyan"; String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path; try { fileNames = new String[files.length]; int index = 0; for (MultipartFile file : files) { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1); int length = getAllowSuffix().indexOf(suffix); if (length == -1) { throw new Exception("请上传允许格式的文件"); } if (file.getSize() > getAllowSize()) { throw new Exception("您上传的文件大小已经超出范围"); } String realPath = request.getSession().getServletContext().getRealPath("/"); File destFile = new File(realPath + destDir); if (!destFile.exists()) { destFile.mkdirs(); } String fileNameNew = getFileNameNew() + "." + suffix;// File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew); file.transferTo(f); f.createNewFile(); fileNames[index++] = basePath + destDir + fileNameNew; } } catch (Exception e) { throw e; } } @RequestMapping("/uploadHandler") @ResponseBody public ResponseEntity<String> uploadTest(){ return new ResponseEntity<String>("the String ResponseBody with custom status code (403 Forbidden)", HttpStatus.OK); } /** * * <p class="detail"> * 功能:文件上传 * </p> * @author wangsheng * @date 2014年9月25日 * @throws Exception */ @ResponseBody public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception { String destDir = "/home/zhaoyan/"; String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path; try { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1); int length = getAllowSuffix().indexOf(suffix); if (length == -1) { throw new Exception("请上传允许格式的文件"); } // if (file.getSize() > getAllowSize()) { // throw new Exception("您上传的文件大小已经超出范围"); // } String realPath = request.getSession().getServletContext().getRealPath("/"); File destFile = new File(realPath + destDir); if (!destFile.exists()) { destFile.mkdirs(); } String fileNameNew = getFileNameNew() + "." + suffix; File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew); file.transferTo(f); fileName = f.getAbsolutePath()+File.separator+f.getName(); return fileName; } catch (Exception e) { // return "{'code':'400','data':'"+e.getMessage()+"'}"; return "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 102, \"message\": \""+e.getMessage()+"\"}, \"id\" : \"id\"}"; } } /** * * <p class="detail"> * 功能:重新命名文件 * </p> * @author wangsheng * @date 2014年9月25日 * @return */ private String getFileNameNew(){ SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return fmt.format(new Date()); } public String getAllowSuffix() { return allowSuffix; } public long getAllowSize() { return allowSize; } }
[ "zhaoyan@belo-inc.com" ]
zhaoyan@belo-inc.com
6bb8179f272a37ea07c7b0896e57e046aded97e8
f1461dab5257e18a09d96519be6e33c2231b323a
/src/main/java/com/huisam/querydsl/repository/MemberTestRepository.java
646524f1de9f7334c026f5d2c03580280f1c051c
[]
no_license
huisam/QueryDsl
bceca8ce14824012bf7229d4e8053d724b5e354e
b10fac5de2498ed87dd713dfbbcbbf66df60da00
refs/heads/master
2023-02-16T23:19:08.903058
2021-01-07T14:35:37
2021-01-07T14:38:34
262,557,743
1
0
null
null
null
null
UTF-8
Java
false
false
3,065
java
package com.huisam.querydsl.repository; import com.huisam.querydsl.dto.MemberSearchCondition; import com.huisam.querydsl.entity.Member; import com.huisam.querydsl.repository.support.QueryDsl4RepositorySupport; import com.querydsl.core.types.dsl.BooleanExpression; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; import static com.huisam.querydsl.entity.QMember.member; import static com.huisam.querydsl.entity.QTeam.team; import static org.springframework.util.StringUtils.hasText; public class MemberTestRepository extends QueryDsl4RepositorySupport { public MemberTestRepository(Class<?> domainClass) { super(Member.class); } public List<Member> basicSelect() { return select(member) .from(member) .fetch(); } public List<Member> basicSelectFrom() { return selectFrom(member) .fetch(); } public Page<Member> applyPagination(MemberSearchCondition condition, Pageable pageable) { return applyPagination(pageable, query -> query.selectFrom(member) .leftJoin(member.team, team) .where( userNameEq(condition.getUserName()), teamNameEq(condition.getTeamName()), ageGoe(condition.getAgeGoe()), ageLoe(condition.getAgeLoe()) ) ); } public Page<Member> applyPagination2(MemberSearchCondition condition, Pageable pageable) { return applyPagination(pageable, contentQuery -> contentQuery.selectFrom(member) .leftJoin(member.team, team) .where( userNameEq(condition.getUserName()), teamNameEq(condition.getTeamName()), ageGoe(condition.getAgeGoe()), ageLoe(condition.getAgeLoe()) ), countQuery -> countQuery .select(member.id) .from(member) .leftJoin(member.team, team) .where( userNameEq(condition.getUserName()), teamNameEq(condition.getTeamName()), ageGoe(condition.getAgeGoe()), ageLoe(condition.getAgeLoe()) ) ); } private BooleanExpression userNameEq(String userName) { return hasText(userName) ? member.username.eq(userName) : null; } private BooleanExpression teamNameEq(String teamName) { return hasText(teamName) ? team.name.eq(teamName) : null; } private BooleanExpression ageGoe(Integer ageGoe) { return ageGoe != null ? member.age.goe(ageGoe) : null; } private BooleanExpression ageLoe(Integer ageLoe) { return ageLoe != null ? member.age.loe(ageLoe) : null; } }
[ "huisam@naver.com" ]
huisam@naver.com
00a1ee28b29269183319e95651aecb9bbf73e3d9
de1d56ee3b37fdb64f8641f82e66d661369ff5d9
/MyProfile.java
749064b622c28b0035eb12005668a8e326e1664c
[]
no_license
Amaranadhreddy/ChampCash-Development
7c19f2acfa5df77b58b947cc98f76287a6f182b2
1afa3b744dd4f90b06b8b6cbfbb109bc071f5a71
refs/heads/master
2021-01-01T15:52:04.542961
2017-07-19T13:06:02
2017-07-19T13:06:02
97,715,875
0
0
null
null
null
null
UTF-8
Java
false
false
2,934
java
package com.tms.govt.champcash.home.report; import java.io.Serializable; /** * Created by govt on 25-04-2017. */ public class MyProfile implements Serializable { private String profileID; private String user_id; private String user_type; private String name; private String email; private String mobile_num; private String member_date_of_birth; private String profileImg; private String city; private String country; private String state; public MyProfile() { } public MyProfile(String user_id, String user_type, String name, String email, String mobile_num, String member_date_of_birth, String profileImg, String city, String country, String state) { this.user_id = user_id; this.user_type = user_type; this.name = name; this.email = email; this.mobile_num = mobile_num; this.member_date_of_birth = member_date_of_birth; this.profileImg = profileImg; this.city = city; this.country = country; this.state = state; } public String getProfileID() { return profileID; } public void setProfileID(String profileID) { this.profileID = profileID; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getUser_type() { return user_type; } public void setUser_type(String user_type) { this.user_type = user_type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile_num() { return mobile_num; } public void setMobile_num(String mobile_num) { this.mobile_num = mobile_num; } public String getMember_date_of_birth() { return member_date_of_birth; } public void setMember_date_of_birth(String date_of_birth) { this.member_date_of_birth = date_of_birth; } public String getProfileImg() { return profileImg; } public void setProfileImg(String profileImg) { this.profileImg = profileImg; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
[ "noreply@github.com" ]
Amaranadhreddy.noreply@github.com
4fc16aea5b219024f6e71cda6346c96240925f9f
8538dc06ad222a407e8e4d7a7214aac234625817
/proyecto2/src/main/java/es/palmademallorca/imi/proyecto2/controller/IndexController.java
ee0a2f6dcb45f350127b660b797204dc7f0327a5
[]
no_license
bginardp/springcurso
70e6ed161d034e51e0a6e27ecaf2954528b7deba
89a40a5c22f248b1eace5b5df93b1bc075696a57
refs/heads/master
2020-06-17T00:33:20.013016
2018-09-25T15:50:29
2018-09-25T15:50:29
75,055,914
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package es.palmademallorca.imi.proyecto2.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") public String index(){ return "index"; } }
[ "bginardp@gmail.com" ]
bginardp@gmail.com
4d08de7d762901569246fb0fe1437c9be4d08181
9b641c9a7077f442506b37ed8b9f891060309aa5
/ChatApp/ChatApp-LLD/com.sangeetdas/src/main/java/com/sangeetdas/project/chat/OneToOneChat.java
667fe820c85ed769e6cf34a52927dba2dad7ebc7
[]
no_license
sangeetd/System-Designs-LLD
afca4a05e2a5c63b4348adea21cef86d5ba72ccf
3b032b0d1c13e754ab5be037163cdad2560498a2
refs/heads/master
2023-08-06T10:22:49.237432
2021-10-04T14:25:52
2021-10-04T14:25:52
413,451,426
0
0
null
null
null
null
UTF-8
Java
false
false
995
java
package com.sangeetdas.project.chat; import com.sangeetdas.project.messages.Message; import java.util.*; public class OneToOneChat implements IChat{ private ISendingPolicy sendingPolicy; private final List<String> contactee; private final List<Message> localSavedMessages; public OneToOneChat(List<String> contactee) { this.contactee = contactee; this.localSavedMessages = new ArrayList<>(); } public void setSendingPolicy(ISendingPolicy sendingPolicy) { this.sendingPolicy = sendingPolicy; } @Override public void sendMessage(String from, String to, Message message){ //actual sending to other user this.sendingPolicy.sendViaPolicy(from, to, message); //local persistence updateMessage(message); } public void updateMessage(Message message){ this.localSavedMessages.add(message); } public List<Message> showMessages(){ return this.localSavedMessages; } }
[ "imsangeet3@gmail.com" ]
imsangeet3@gmail.com
26b3ca6b3bf2f5a90dadba7b4c5f8d9310dead26
08a1b71a87f3769d244a5fdfec06ae409638d3b7
/src/main/java/com/prevosql/index/io/writer/PlainIndexWriter.java
1b74070c574acae72e52cd9cfd23b2cb46195f4a
[]
no_license
aadilzbhatti/PrevoSQL
c59c707e15a29a672e63830fd2c18cf5c9733cbc
139f58ad2ac832b86b1b5da71bdc5f336b7f19ae
refs/heads/master
2021-12-30T06:43:03.269140
2018-02-07T01:14:36
2018-02-07T01:14:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,184
java
package com.prevosql.index.io.writer; import com.prevosql.index.entry.DataEntry; import com.prevosql.index.entry.RecordId; import com.prevosql.index.node.IndexNode; import com.prevosql.index.node.LeafNode; import com.prevosql.index.node.TreeNode; import org.apache.log4j.Logger; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; class PlainIndexWriter implements IndexWriter { private PrintWriter pw; private static final Logger LOG = Logger.getLogger(PlainIndexWriter.class); public PlainIndexWriter(String tableName, String key) { File f = new File(tableName + "." + key + "-testing"); try { f.createNewFile(); FileWriter fileWriter = new FileWriter(f); pw = new PrintWriter(fileWriter); } catch (IOException e) { LOG.fatal(e); System.err.println("Failed to create index file: " + e.getMessage()); System.exit(1); } } @Override public void serializeIndexNode(IndexNode curr, int currIndexPage) { curr.setAddress(currIndexPage); StringBuilder sb = new StringBuilder("Index node with keys ["); ArrayList<String> keys = new ArrayList<>(); for (int key : curr.getKeys()) { if (key == 0 && keys.size() > 0) { break; } keys.add("" + key); } String s = String.join(", ", keys); sb.append(s); sb.append("] and child addresses ["); ArrayList<String> children = new ArrayList<>(); for (TreeNode child : curr.getChildren()) { if (child == null) { break; } children.add("" + child.getAddress()); } s = String.join(", ", children); sb.append(s); sb.append("]\n"); pw.println(sb); LOG.info("Serialized index node " + curr + " on page " + currIndexPage); pw.flush(); } @Override public void serializeLeafNode(LeafNode curr, int size, int currPage) { curr.setAddress(currPage); StringBuilder sb = new StringBuilder("LeafNode[\n"); for (DataEntry dataEntry : curr.getEntries()) { sb.append("<["); sb.append(dataEntry.getSearchKey()); sb.append(":"); for (RecordId rid : dataEntry.getRecordIds()) { sb.append("(").append(rid.getPageId()).append(",").append(rid.getTupleId()).append(")"); } sb.append("]>\n"); } sb.append("]\n"); pw.println(sb); pw.flush(); LOG.info("Serialized leaf node: " + curr + " with " + size + " data entries on page " + currPage); } @Override public void writeHeaderPage(int order, int numLeafNodes, TreeNode root) { pw.println("Header page info: tree has order " + order + ", a root at address " + root.getAddress() + " and " + numLeafNodes + " leaf nodes." ); pw.flush(); LOG.info("Wrote header page with root at address " + root.getAddress() + ", " + numLeafNodes + " leaf nodes, and order " + order); } }
[ "aadilzbhatti@gmail.com" ]
aadilzbhatti@gmail.com
7ac95a6aeb4bf54349efc90ac471c58280e2bb86
526c3cf66b31dd8dd9728accad977f5c84ed0a11
/src/gui/util/Utils.java
de06aecad324d7c6991b43e39537de4c85d3b07d
[]
no_license
tiagoborgir2/workshop-javafx-jdbc
341f9b597405d432e54b2bec8681b6d3cdb785bf
dd5bbce3431d67d0f5f7e6ec5057cb1b42910234
refs/heads/master
2023-06-25T22:33:58.877546
2021-07-13T18:58:38
2021-07-13T18:58:38
380,015,564
0
0
null
null
null
null
UTF-8
Java
false
false
2,542
java
package gui.util; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import javafx.event.ActionEvent; import javafx.scene.Node; import javafx.scene.control.DatePicker; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.stage.Stage; import javafx.util.StringConverter; public class Utils { public static Stage currentStage(ActionEvent event) { return (Stage) ((Node) event.getSource()).getScene().getWindow(); } public static Integer tryParseToInt(String str) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { return null; } } public static Double tryParseToDouble(String srt) { try { return Double.parseDouble(srt); } catch (NumberFormatException e) { return null; } } public static <T> void formatTableColumnDate(TableColumn<T, Date> tableColumn, String format) { tableColumn.setCellFactory(column -> { TableCell<T, Date> cell = new TableCell<T, Date>() { private SimpleDateFormat sdf = new SimpleDateFormat(format); @Override protected void updateItem(Date item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); } else { setText(sdf.format(item)); } } }; return cell; }); } public static <T> void formatTableColumnDouble(TableColumn<T, Double> tableColumn, int decimalPlaces) { tableColumn.setCellFactory(column -> { TableCell<T, Double> cell = new TableCell<T, Double>() { @Override protected void updateItem(Double item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); } else { Locale.setDefault(Locale.US); setText(String.format("%." + decimalPlaces + "f", item)); } } }; return cell; }); } public static void formatDatePicker(DatePicker datePicker, String format) { datePicker.setConverter(new StringConverter<LocalDate>() { DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(format); { datePicker.setPromptText(format.toLowerCase()); } @Override public String toString(LocalDate date) { if (date != null) { return dateFormatter.format(date); } else { return ""; } } @Override public LocalDate fromString(String string) { if (string != null && !string.isEmpty()) { return LocalDate.parse(string, dateFormatter); } else { return null; } } }); } }
[ "tiago.alcosta@gmail.com" ]
tiago.alcosta@gmail.com
97a83e3f09c3d29a6d9d273221dbec5e4ad1e8df
dcea0a97656538aba0ede704ae1f87daf462c6eb
/LeetCode/connectedComponentsList.java
6edc321e3854df83afb54756db9c44cf43def9ab
[]
no_license
amiteshP/TheZenOfSoulCoding
d2d78043a85f853662387129083b00e4890ff201
b12806d27a0bfae4dea145e21ed8369ff604f90d
refs/heads/master
2021-08-17T09:29:05.329552
2018-10-29T18:52:10
2018-10-29T18:52:10
144,480,594
1
0
null
null
null
null
UTF-8
Java
false
false
816
java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public int numComponents(ListNode head, int[] G) { HashSet<Integer> hSet = new HashSet<>(); if(head == null) return 0; for(int num: G){ hSet.add(num); } int comp = 0; while(head!=null){ if(hSet.contains(head.val)) { if(head.next!=null && hSet.contains(head.next.val)) { comp++; if(head.next.next == null) break; } else if(head.next==null) comp++; } head = head.next; } return comp; } }
[ "ampathak@adobe.com" ]
ampathak@adobe.com
5f6c8d24cf551af98d18cf053c90ffd767a06c10
3508dc7da2944ef5f15f4a7fc69f5b1401f5a476
/src/test/java/com/test1/tests/TestSuccessfulFirstAdminCreateDBCheck.java
76870b96aac8380c4b61eb0c63d99135f42eb5ce
[]
no_license
DTSProject01/DTS1
fc4e1c0146790512d61b6b7487b73f92680612b8
3b4f93b753bf65aac838efcf257e24ff2ab5f143
refs/heads/master
2021-01-09T20:42:39.500339
2016-07-20T17:36:58
2016-07-20T17:36:58
63,799,400
0
0
null
2016-07-20T17:20:55
2016-07-20T17:04:51
HTML
UTF-8
Java
false
false
1,930
java
package com.test1.tests; import org.testng.annotations.Test; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.Test; import org.testng.AssertJUnit; import org.testng.annotations.Test; import com.test1.pages.LogInPage; import org.testng.annotations.BeforeMethod; import java.awt.AWTException; import java.awt.Toolkit; import java.io.IOException; import java.sql.SQLException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; public class TestSuccessfulFirstAdminCreateDBCheck extends TestBase { @Test (dataProvider = "dataProvider") public void testSuccessfulNewAdminUserCreationDBcheck(String username, String password, String nusername, String status, String role, String client, String telenumber, String email, String npassword, String confirmpw, String path, String imgname) throws InterruptedException, IOException, AWTException, ClassNotFoundException, SQLException { //The entry point LogInPage object below can now be removed because its added to TestBase can now inherit this //LogInPage logInPage = new LogInPage(driver); boolean testResult = loginpage.loginAsAdmin(username, password) .ClickManageUsersLink() .AddUser() .CreateNewUser(nusername, status, role, client, telenumber, email, npassword, confirmpw, path, imgname) .clickManageUsersPagelink() .isCreateUserSuccessfulCheckDB(nusername, email); System.out.println(testResult); Assert.assertTrue(testResult, "The account for " + nusername + " has not been successfully created." ); } //AfterMethod is now inherited from TestBase class the commented out below is not required // @AfterMethod // public void afterMethod() // { // driver.close(); // } }
[ "synhlee@yahoo.com" ]
synhlee@yahoo.com
7fe769e25636e81dac26bbdea181d55e7705ec33
ffdb3c49de6f0037842a21f408505dd08d2a2f12
/app/src/main/java/com/ttyooyu/market/core/MainFactory.java
352df1cdcaeb405c82136f126c5e397e4be7d9a8
[]
no_license
jwenzhu/TTYooyu
275c35b23a62d810120801b27059769f64710c01
4c25eef7178a7f4d90f68e47fa0b4a57ec9a608b
refs/heads/master
2020-12-25T14:33:42.228370
2016-11-03T06:42:23
2016-11-03T06:42:23
67,656,508
0
0
null
null
null
null
UTF-8
Java
false
false
582
java
package com.ttyooyu.market.core; /** * Created by Administrator on 2016-08-25. */ public class MainFactory { /** * host url */ public static final String HOST = "www.baidu.com"; public static final String HOST_DOWNLOAD =""; private static TTYooYu mTTYooYu; protected static final Object monitor = new Object(); public static TTYooYu getTTYooYuInstance(){ synchronized (monitor){ if(mTTYooYu ==null){ mTTYooYu = new MainRetrofit().getService(); } return mTTYooYu; } } }
[ "709846645@qq.com" ]
709846645@qq.com
f9638207820c5ad45ad8e404761de08352908abf
a59930c0461f9d4dc4ef7cdca693e3bcc9aeb3c6
/Projeto Final/Etapa1 - CRUD/Livraria/src/com/br/lp2/testeDAO/TestePedidoDAO.java
c847f13a2f04aa7faeda1d3b3c1c5f35c745e24e
[]
no_license
BrunaFerreira/LP2---Projeto1
a446456caaafc2284a488a5fe828c0d1d975a489
18cb2332f7013bb170cdf926f118d13636eb5cb0
refs/heads/master
2021-05-30T00:39:08.695592
2015-10-05T01:30:37
2015-10-05T01:30:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,534
java
/* * 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 com.br.lp2.testeDAO; import com.br.lp2.model.Pedido; import com.br.lp2.model.dao.PedidoDAO; import java.sql.Time; import java.sql.Date; import java.util.List; /** * * @author Bruna */ public class TestePedidoDAO { public static void main(String[] args) { // TODO code application logic here //Criar instancia DAO System.out.println("***CRUD Pedido***"); PedidoDAO PedidoDAO = new PedidoDAO(); // LEITURA DOS PEDIDOS List<Pedido> listaU; // INSERÇÃO DE PEDIDO Pedido ul = new Pedido(); ul.setQntItemPedido(10); ul.setHoraPedido(new Time(31231)); ul.setDataPedido(new Date(2014, 12, 05)); //PedidoDAO.insert(ul); //UPDATE DE UM DE PEDIDO listaU = PedidoDAO.read(); Pedido u2 = listaU.get(listaU.size() - 1); u2.setQntItemPedido(39); u2.setHoraPedido(new Time(988871)); u2.setDataPedido(new Date(2010, 10, 05)); // PedidoDAO.update(u2); //DELETE DE PEDIDO listaU = PedidoDAO.read(); Pedido u3 = listaU.get(listaU.size() - 1); PedidoDAO.delete(u3); listaU = PedidoDAO.read(); for (Pedido Pedido : listaU) { System.out.println(Pedido); } } }
[ "guhdemari@gmail.com" ]
guhdemari@gmail.com
f2f73638321eb1ca473ffd3418818893c2428e3f
9d43474bb7a4d8702425f75d92857fbbbb0ce77d
/src/test/java/test/Main.java
515d16a547585e7d515c4d2693a7c3a222c232b8
[]
no_license
hkweiling/RestApi
4741dc8c7f2f91ade2a3e6adbd7d8a898b4439b1
3ea2daca7aacc0893c2cea992ca7c9055c515a21
refs/heads/master
2021-03-17T06:47:11.997762
2020-03-13T02:59:33
2020-03-13T02:59:33
246,971,716
0
0
null
null
null
null
UTF-8
Java
false
false
649
java
package test; import com.google.gson.reflect.TypeToken; import com.ikonke.api.model.*; import com.ikonke.api.util.HttpUtil; import com.ikonke.api.util.JsonUtil; import javax.xml.ws.Response; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * @description: * @author: * @time: 2020/3/11 14:48 */ public class Main { private static Map<String, String> header() { Map<String, String> header = new HashMap<>(); header.put("appId", "10001248"); header.put("appKey", "13b5d886-100a-4dd6-94d1-b073e60e0e31"); return header; } public static void main(String[] args) { } }
[ "atbd59@163.com" ]
atbd59@163.com
fbef110ece8360272906a45274e5eebeeb5545fd
a07f3a43f0335c0a635090d791f63a57e7fd05a6
/libPolyPicker/src/main/java/nl/changer/polypicker/CameraActivity.java
860f88443314d27e0c7eb038a77848b1cf541e8f
[]
no_license
caioketo/GerenciamentoDeEstudos
549811c929ed38937c9423128f1b3e23a3d00c24
212f373ab65fa0f46a620f8ff336ae044a195073
refs/heads/master
2016-08-06T10:27:33.767879
2015-02-26T20:02:02
2015-02-26T20:02:02
31,386,208
0
0
null
null
null
null
UTF-8
Java
false
false
7,468
java
package nl.changer.polypicker; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.hardware.Camera; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.HashSet; import java.util.Set; import nl.changer.polypicker.model.Image; import nl.changer.polypicker.utils.ImageInternalFetcher; /** * Created by Caio on 20/10/2014. */ public class CameraActivity extends Activity implements Camera.ShutterCallback, Camera.PictureCallback { public static final String EXTRA_IMAGE_URIS = "nl.changer.polypicker.extra.selected_image_uris"; public static final String EXTRA_SELECTION_LIMIT = "nl.changer.polypicker.extra.selection_limit"; private static final String TAG = CameraFragment.class.getSimpleName(); Camera mCamera; ImageButton mTakePictureBtn; private Set<Image> mSelectedImages; private LinearLayout mSelectedImagesContainer; private TextView mSelectedImageEmptyMessage; private Button mCancelButtonView, mDoneButtonView; public ImageInternalFetcher mImageFetcher; private int mMaxSelectionsAllowed = Integer.MAX_VALUE; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.camera_activity); mSelectedImagesContainer = (LinearLayout) findViewById(R.id.selected_photos_container); mSelectedImageEmptyMessage = (TextView)findViewById(R.id.selected_photos_empty); mCancelButtonView = (Button) findViewById(R.id.action_btn_cancel); mDoneButtonView = (Button) findViewById(R.id.action_btn_done); mSelectedImages = new HashSet<Image>(); mImageFetcher = new ImageInternalFetcher(this, 500); mCancelButtonView.setOnClickListener(onFinishGettingImages); mDoneButtonView.setOnClickListener(onFinishGettingImages); mCamera = Camera.open(); CameraPreview preview = new CameraPreview(this, mCamera); ViewGroup previewHolder = (ViewGroup)findViewById(R.id.preview_holder); previewHolder.addView(preview); // take picture even when the preview is clicked. previewHolder.setOnClickListener(mOnTakePictureClicked); mTakePictureBtn = (ImageButton)findViewById(R.id.take_picture); mTakePictureBtn.setOnClickListener(mOnTakePictureClicked); mMaxSelectionsAllowed = getIntent().getIntExtra(EXTRA_SELECTION_LIMIT, Integer.MAX_VALUE); } View.OnClickListener mOnTakePictureClicked = new View.OnClickListener() { @Override public void onClick(View view) { if(mTakePictureBtn.isEnabled()){ mTakePictureBtn.setEnabled(false); if(mCamera != null) { mCamera.takePicture(CameraActivity.this, null, CameraActivity.this); } } } }; @Override public void onPictureTaken(byte[] bytes, Camera camera) { mTakePictureBtn.setEnabled(true); Bitmap picture = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); // rotates the image to portrait Matrix matrix = new Matrix(); matrix.postRotate(90); picture = Bitmap.createBitmap(picture, 0, 0, picture.getWidth(), picture.getHeight(), matrix, true); String path = MediaStore.Images.Media.insertImage(getContentResolver(), picture, "" , ""); Uri contentUri = Uri.parse(path); Image image = getImageFromContentUri(contentUri); addImage(image); mCamera.startPreview(); } public Image getImageFromContentUri(Uri contentUri) { String[] cols = { MediaStore.Images.Media.DATA, MediaStore.Images.ImageColumns.ORIENTATION }; // can post image Cursor cursor = getContentResolver().query(contentUri, cols, null, null, null); cursor.moveToFirst(); Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))); int orientation = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION)); return new Image(uri, orientation); } @Override public void onShutter() { } public boolean addImage(Image image) { if(mSelectedImages.size() == mMaxSelectionsAllowed) { Toast.makeText(this, mMaxSelectionsAllowed + " images selected already", Toast.LENGTH_SHORT).show(); return false; } else { if(mSelectedImages.add(image)) { View rootView = LayoutInflater.from(this).inflate(R.layout.list_item_selected_thumbnail, null); ImageView thumbnail = (ImageView) rootView.findViewById(R.id.selected_photo); rootView.setTag(image.mUri); mImageFetcher.loadImage(image.mUri, thumbnail); mSelectedImagesContainer.addView(rootView, 0); int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics()); thumbnail.setLayoutParams(new FrameLayout.LayoutParams(px, px)); if(mSelectedImages.size() >= 1) { mSelectedImagesContainer.setVisibility(View.VISIBLE); mSelectedImageEmptyMessage.setVisibility(View.GONE); } return true; } } return false; } public boolean removeImage(Image image) { if(mSelectedImages.remove(image)) { for(int i = 0; i < mSelectedImagesContainer.getChildCount(); i++) { View childView = mSelectedImagesContainer.getChildAt(i); if(childView.getTag().equals(image.mUri)){ mSelectedImagesContainer.removeViewAt(i); break; } } if(mSelectedImages.size() == 0) { mSelectedImagesContainer.setVisibility(View.GONE); mSelectedImageEmptyMessage.setVisibility(View.VISIBLE); } return true; } return false; } public boolean containsImage(Image image) { return mSelectedImages.contains(image); } private View.OnClickListener onFinishGettingImages = new View.OnClickListener() { @Override public void onClick(View view) { if(view.getId() == R.id.action_btn_done) { Uri[] uris = new Uri[mSelectedImages.size()]; int i = 0; for(Image img : mSelectedImages) { uris[i++] = Uri.parse("file://" + img.mUri.toString()); } Intent intent = new Intent(); intent.putExtra(EXTRA_IMAGE_URIS, uris); setResult(Activity.RESULT_OK, intent); } else if(view.getId() == R.id.action_btn_cancel) { setResult(Activity.RESULT_CANCELED); } finish(); } }; }
[ "caionmoreno1@gmail.com" ]
caionmoreno1@gmail.com
118488bfdf2d713a405e3ec48c0c564df7e76073
738552249a74511b44ce6ee7c8a861aa3f914845
/ssh0605/src/com/ru/javaExam/processcontrol/SwitchTest.java
762edcb8b044b75081d7fbbe5d5e63c1ce07c24e
[]
no_license
tydldd/ssh_exam
c4c4eb7854c2bfc2d38823c0c5582e611ad5aeac
d1246b25e334308aeb35c4df528ccb2e31d02409
refs/heads/master
2016-09-05T22:48:35.104226
2014-06-15T03:37:51
2014-06-15T03:37:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,007
java
/** * 文件名:switchTest.java * * 版本信息:1.0 * 日期:2013-6-25 * Copyright ru Corporation 2013 版权所有 * */ package com.ru.javaExam.processcontrol; import org.junit.Test; /** * * 项目名称:ssh0605 * 类描述:switch流程控制(switch后面的表达式的5种数据类型:byte、short、int、char、enum) * 创建人:nanchengru * 创建时间:2013-6-25 上午11:39:37 * 修改人:nanchengru * 修改时间:2013-6-25 上午11:39:37 * 修改备注: * 环境: jdk1.7 */ public class SwitchTest { /** * * defaultTest(default分支的潜在条件是:表达式的值和前面分支的值都不相等。也就是说只有在前面的分支没有执行时, * default分支才会执行) * @param * @return * @throws */ @Test public void defaultTest(){ char score = 'c'; switch (score) { case 'a': System.out.println("优秀"); break; case 'b': System.out.println("良好"); break; case 'c': System.out.println("中"); break; case 'd': System.out.println("及格"); break; case 'e': System.out.println("不及格"); break; default: System.out.println("成绩输入错误"); break; } } /** * * breakTest(break作用是跳出当前流程控制(switch),一旦找到对应的分支,程序将一直执行到最后, * 不再与各分支的比较值进行比较。 * 下面程序的执行结果是: * 中 及格 不及格 成绩输入错误) * @param * @return * @throws */ @Test public void breakTest(){ char score = 'c'; switch (score) { case 'a': System.out.println("优秀"); case 'b': System.out.println("良好"); case 'c': System.out.println("中"); case 'd': System.out.println("及格"); case 'e': System.out.println("不及格"); default: System.out.println("成绩输入错误"); } } }
[ "ru2013_1@163.com" ]
ru2013_1@163.com
8c5b8071ab5e15cb479330dbb5d0c224d9b4f421
d071b94ef92b50faaf13a410bf5eaa9351e44ac4
/app/src/main/java/me/mathiasprisfeldt/pacman/Types/Point2D.java
cc69072990fc2c81480770656146f5d8777cf7c0
[]
no_license
mathiasprisfeldt/pacman
0803f6417a2928fd12f060d3249ca19bb086b5c5
7ce31c42398aca650144d7cff04bb5bcb8e95937
refs/heads/master
2023-07-10T08:10:36.774475
2018-10-04T11:33:20
2018-10-04T11:33:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
580
java
package me.mathiasprisfeldt.pacman.Types; public class Point2D { private int _x; private int _y; public int x() { return _x; } public int y() { return _y; } public Point2D(int _x, int _y) { this._x = _x; this._y = _y; } public Point2D add(Point2D other) { return new Point2D( _x + other._x, _y + other._y); } public Point2D subtract(Point2D other) { return new Point2D( _x - other._x, _y - other._y ); } }
[ "contact@mathiasprisfeldt.me" ]
contact@mathiasprisfeldt.me
3a439704902310fabf0ae35c67298c34aa48fcd4
98dc6a2dd4ed7ece34053a777aa1e4af65ec38ee
/Java_Client/src/java_templates/networking/client/utils/ClientUtils.java
91a798e7787a73a65d0c2adfb67d988fa07e4d5d
[]
no_license
ioarg/Java_Client_Server_Template
6473e77b9f68096735b0346b6cee769e50cabff0
eea76ccc0788bd8c563617fcbefea2084b929c09
refs/heads/master
2021-10-21T02:50:06.061161
2018-11-30T20:15:00
2018-11-30T20:15:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,481
java
package java_templates.networking.client.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.Scanner; public class ClientUtils { private int port; private String ip; public ClientUtils(String ip, int port) { this.ip = ip; this.port = port; } public void startClient() { try(Socket clientSocket = new Socket(ip, port)){ clientSocket.setSoTimeout(5000); BufferedReader response = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter message = new PrintWriter(clientSocket.getOutputStream(), true); System.out.println("Start typing your text here. Press ENTER to send"); String sendText; Scanner keyboard = new Scanner(System.in); while(true) { sendText = keyboard.nextLine(); message.println(sendText); if(sendText.equals("exit")) { System.out.println("Client Shutdown ..."); break; } System.out.println("Echo : " + response.readLine()); } keyboard.close(); }catch(SocketTimeoutException e) { System.out.println("Client Error - Socket timeout : " + e.getMessage()); }catch (UnknownHostException e) { System.out.println("Client Error - Unknown host : " + e.getMessage()); } catch (IOException e) { System.out.println("Client Error : " + e.getMessage()); } } }
[ "johnargyroulis@gmail.com" ]
johnargyroulis@gmail.com
a0f111c96c668f4cb6edcfc0ce51200ed147610d
847a173f9b402170733aa92301680707f1599007
/hrms/src/main/java/kodlamaio/hrms/business/concretes/EmploymentTypeManager.java
407bd307d3f622e9e594b45cca2db294e101a5ab
[]
no_license
mert-akkaya/hrms
3ddbfdc024eb945ab666dc6e131df02e6e794433
56b3230ac0b25692c14d2750a01e22ba4b0fb662
refs/heads/master
2023-07-01T16:29:20.506396
2021-08-10T18:24:17
2021-08-10T18:24:17
366,356,196
6
0
null
null
null
null
UTF-8
Java
false
false
901
java
package kodlamaio.hrms.business.concretes; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kodlamaio.hrms.business.abstracts.EmploymentTypeService; import kodlamaio.hrms.core.utilites.results.DataResult; import kodlamaio.hrms.core.utilites.results.SuccessDataResult; import kodlamaio.hrms.dataAccess.abstracts.EmploymentTypeDao; import kodlamaio.hrms.entities.concretes.EmploymentType; @Service public class EmploymentTypeManager implements EmploymentTypeService { private EmploymentTypeDao employmentTypeDao; @Autowired public EmploymentTypeManager(EmploymentTypeDao employmentTypeDao) { this.employmentTypeDao = employmentTypeDao; } @Override public DataResult<List<EmploymentType>> getAll() { return new SuccessDataResult<List<EmploymentType>>(this.employmentTypeDao.findAll()); } }
[ "mertakkaya522@gmail.com" ]
mertakkaya522@gmail.com
5ab51b2b2dd3c61a2e7112a477cdeb063b5e1280
45f213223f8afdcceee98a1a3f6a5e90cfb73687
/jcore-xmi-db-writer/src/test/java/de/julielab/jcore/consumer/xmi/XmiDBWriterMonolithicDocumentTest.java
6f8611d2965349b6883517d51878b686f5f81f9a
[ "BSD-2-Clause" ]
permissive
JULIELab/jcore-base
1b74ad8e70ad59e2179ba58301738ba3bf17ef38
20902abb41b3bc2afd246f2e72068bd7c6fa3a93
refs/heads/master
2023-08-29T02:16:40.302455
2022-12-09T10:38:41
2022-12-09T10:38:41
45,028,592
29
14
BSD-2-Clause
2023-07-07T21:58:41
2015-10-27T08:59:13
Java
UTF-8
Java
false
false
4,560
java
package de.julielab.jcore.consumer.xmi; import de.julielab.costosys.dbconnection.CoStoSysConnection; import de.julielab.costosys.dbconnection.DataBaseConnector; import de.julielab.jcore.db.test.DBTestUtils; import de.julielab.jcore.types.Header; import de.julielab.jcore.types.Sentence; import de.julielab.jcore.types.Token; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.uima.UIMAException; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.cas.impl.XmiCasDeserializer; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.JCasFactory; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import java.io.ByteArrayInputStream; import java.sql.ResultSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.junit.jupiter.api.Assertions.assertTrue; @Testcontainers public class XmiDBWriterMonolithicDocumentTest { @Container public static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:"+DataBaseConnector.POSTGRES_VERSION); private static String costosysConfig; private static DataBaseConnector dbc; @BeforeAll public static void setup() throws ConfigurationException { dbc = DBTestUtils.getDataBaseConnector(postgres); costosysConfig = DBTestUtils.createTestCostosysConfig("medline_2017", 1, postgres); DBTestUtils.createAndSetHiddenConfig("src/test/resources/hiddenConfig.txt", postgres); } @AfterAll public static void shutDown() { dbc.close(); } public static JCas getJCasWithRequiredTypes() throws UIMAException { return JCasFactory.createJCas("de.julielab.jcore.types.jcore-morpho-syntax-types", "de.julielab.jcore.types.jcore-document-meta-pubmed-types", "de.julielab.jcore.types.jcore-document-structure-pubmed-types", "de.julielab.jcore.types.extensions.jcore-document-meta-extension-types", "de.julielab.jcore.types.jcore-xmi-splitter-types"); } @Test public void testXmiDBWriterSplitAnnotations() throws Exception { AnalysisEngine xmiWriter = AnalysisEngineFactory.createEngine("de.julielab.jcore.consumer.xmi.desc.jcore-xmi-db-writer", XMIDBWriter.PARAM_COSTOSYS_CONFIG, costosysConfig, XMIDBWriter.PARAM_STORE_ALL, true, XMIDBWriter.PARAM_STORE_BASE_DOCUMENT, false, XMIDBWriter.PARAM_TABLE_DOCUMENT, "_data.documents", XMIDBWriter.PARAM_DO_GZIP, false, XMIDBWriter.PARAM_UPDATE_MODE, true, XMIDBWriter.PARAM_STORE_RECURSIVELY, false ); JCas jCas = getJCasWithRequiredTypes(); final Header header = new Header(jCas); header.setDocId("789"); header.addToIndexes(); jCas.setDocumentText("This is a sentence. This is another one."); new Sentence(jCas, 0, 19).addToIndexes(); new Sentence(jCas, 20, 40).addToIndexes(); // Of course, these token offsets are wrong, but it doesn't matter to the test new Token(jCas, 0, 19).addToIndexes(); new Token(jCas, 20, 40).addToIndexes(); assertThatCode(() -> xmiWriter.process(jCas)).doesNotThrowAnyException(); jCas.reset(); xmiWriter.collectionProcessComplete(); dbc = DBTestUtils.getDataBaseConnector(postgres); try (CoStoSysConnection costoConn = dbc.obtainOrReserveConnection()) { assertThat(dbc.tableExists("_data.documents")).isTrue(); assertThat(dbc.isEmpty("_data.documents")).isFalse(); final ResultSet rs = costoConn.createStatement().executeQuery("SELECT xmi FROM _data.documents"); assertTrue(rs.next()); final byte[] xmiData = rs.getBytes(1); jCas.reset(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(xmiData), jCas.getCas()); assertThat(JCasUtil.select(jCas, Header.class)).isNotEmpty(); assertThat(JCasUtil.select(jCas, Token.class)).isNotEmpty(); assertThat(JCasUtil.select(jCas, Sentence.class)).isNotEmpty(); } } }
[ "chew@gmx.net" ]
chew@gmx.net
173434a76bbadaeeea82334b2969ddec8a646f06
90d610df1a18d54391760bad15b0f0971814bed3
/src/main/java/com/zam/o2o/service/impl/AreaServiceImpl.java
bc6b6dcb72e6a06882315be87a6ccba0a4930724
[]
no_license
anmaozhang335/HelloSpring
2c2d5e748b6d3a340b2249aa6bf314116d6feba6
f16e2e9f5716b21a0f8d008e594cc80d40770257
refs/heads/master
2020-03-07T21:40:05.673813
2018-04-18T07:45:46
2018-04-18T07:45:46
127,733,102
0
0
null
null
null
null
UTF-8
Java
false
false
2,989
java
package com.zam.o2o.service.impl; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.zam.o2o.cache.JedisUtil; import com.zam.o2o.dao.AreaDao; import com.zam.o2o.entity.Area; import com.zam.o2o.exceptions.AreaOperationException; import com.zam.o2o.service.AreaService; @Service public class AreaServiceImpl implements AreaService{ @Autowired private AreaDao areaDao; @Autowired private JedisUtil.Keys jedisKeys; @Autowired private JedisUtil.Strings jedisStrings; private static Logger logger = LoggerFactory.getLogger(AreaServiceImpl.class); @Override @Transactional public List<Area> getAreaList() { //定义redis的key String key = AREALISTKEY; //定义接收对象 List<Area> areaList = null; //定义jackson数据转换操作类 ObjectMapper mapper = new ObjectMapper(); //判断key是否存在 if (!jedisKeys.exists(key)) { //若不存在,则从数据库里面取出相应数据 areaList = areaDao.queryArea(); //将相关的实体类集合转换成 string,存入redis里面对应的key中 String jsonString; try { jsonString = mapper.writeValueAsString(areaList); } catch (JsonProcessingException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new AreaOperationException(e.getMessage()); } jedisStrings.set(key, jsonString); }else { //若存在,则直接从redis里面取出相应数据 String jsonString = jedisStrings.get(key); JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Area.class); try { areaList = mapper.readValue(jsonString, javaType); } catch (JsonParseException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new AreaOperationException(e.getMessage()); } catch (JsonMappingException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new AreaOperationException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new AreaOperationException(e.getMessage()); } } return areaList; } }
[ "anmao.zhang@pwc.com" ]
anmao.zhang@pwc.com
ff59ee30d913e331b557545af11b188a033f1764
5fe2d38530885c3350db898feb1fef0ae748da37
/src/test/java/com/sam/reactivemongorecipeapplication/services/RecipeServiceIT.java
f8535804aea9e3205b8165cc11bd0f8dce597419
[]
no_license
baskicisamet/reactive-mongo-recipe-application
fe6b248a9bd41f0e2256ac25f5029804fa627789
f6c68c750c5c7198df87a56b2ca8618d850e4ec3
refs/heads/master
2020-04-27T14:19:01.538666
2018-02-03T06:10:44
2018-02-03T06:10:44
174,405,624
0
0
null
null
null
null
UTF-8
Java
false
false
2,001
java
package com.sam.reactivemongorecipeapplication.services; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.sam.reactivemongorecipeapplication.commands.RecipeCommand; import com.sam.reactivemongorecipeapplication.converters.RecipeCommandToRecipe; import com.sam.reactivemongorecipeapplication.converters.RecipeToRecipeCommand; import com.sam.reactivemongorecipeapplication.domain.Recipe; import com.sam.reactivemongorecipeapplication.repositories.RecipeRepository; /** * Created by jt on 6/21/17. */ //@DataMongoTest @RunWith(SpringRunner.class) @SpringBootTest public class RecipeServiceIT { public static final String NEW_DESCRIPTION = "New Description"; @Autowired RecipeService recipeService; @Autowired RecipeRepository recipeRepository; @Autowired RecipeCommandToRecipe recipeCommandToRecipe; @Autowired RecipeToRecipeCommand recipeToRecipeCommand; // @Transactional @Test public void testSaveOfDescription() throws Exception { //given Iterable<Recipe> recipes = recipeRepository.findAll(); Recipe testRecipe = recipes.iterator().next(); RecipeCommand testRecipeCommand = recipeToRecipeCommand.convert(testRecipe); //when testRecipeCommand.setDescription(NEW_DESCRIPTION); RecipeCommand savedRecipeCommand = recipeService.saveRecipeCommand(testRecipeCommand); //then assertEquals(NEW_DESCRIPTION, savedRecipeCommand.getDescription()); assertEquals(testRecipe.getId(), savedRecipeCommand.getId()); assertEquals(testRecipe.getCategories().size(), savedRecipeCommand.getCategories().size()); assertEquals(testRecipe.getIngredients().size(), savedRecipeCommand.getIngredients().size()); } }
[ "baskicisamet@gmail.com" ]
baskicisamet@gmail.com
808ae17b32bd58fd1072dd3016ce03b34bf43e69
740425ec2edb71f8823b0543a1bd5359fa834834
/app/src/main/java/com/example/leoes/studiez/Calendar.java
c7af878b6799c1e1e452b1b17dda40e4db2bc696
[]
no_license
LeoEStevens/StudiEZ
c514a476190a9dd7e5763887c0262c6fb0bbb914
37ecaea2ea7e31acb8fb91718cb45a8e2abe73f3
refs/heads/master
2020-04-19T07:32:19.845975
2019-01-28T22:45:44
2019-01-28T22:45:44
168,050,310
0
0
null
null
null
null
UTF-8
Java
false
false
3,439
java
package com.example.leoes.studiez; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class Calendar extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calendar); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.calendar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_main) { startActivity(new Intent(this, MainActivity.class)); } else if (id == R.id.nav_cal) { startActivity(new Intent(this, Calendar.class)); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
[ "leoestevens@gmail.com" ]
leoestevens@gmail.com
87eea2ccd982916139f83eedc6a341bfccf939b3
dd47902933765e5c862387c3b367abba8ff1f4c6
/maven-webprj/src/main/java/com/zhiyou100/zyVideo/model/UserExample.java
df868ed6eed99b9225cdbacaca0b79559352c056
[]
no_license
FlyingDriver/VideoManagement
dcd8acacd57883115b1aad9a0068af2b89e23d85
928117aa2f29a548713b149acd6b61eb8e308c64
refs/heads/master
2021-01-20T05:58:48.106288
2017-08-31T13:09:53
2017-08-31T13:09:53
101,476,087
0
0
null
null
null
null
UTF-8
Java
false
false
33,997
java
package com.zhiyou100.zyVideo.model; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class UserExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public UserExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } protected void addCriterionForJDBCDate(String condition, Date value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value.getTime()), property); } protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } List<java.sql.Date> dateList = new ArrayList<java.sql.Date>(); Iterator<Date> iter = values.iterator(); while (iter.hasNext()) { dateList.add(new java.sql.Date(iter.next().getTime())); } addCriterion(condition, dateList, property); } protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNickNameIsNull() { addCriterion("nick_name is null"); return (Criteria) this; } public Criteria andNickNameIsNotNull() { addCriterion("nick_name is not null"); return (Criteria) this; } public Criteria andNickNameEqualTo(String value) { addCriterion("nick_name =", value, "nickName"); return (Criteria) this; } public Criteria andNickNameNotEqualTo(String value) { addCriterion("nick_name <>", value, "nickName"); return (Criteria) this; } public Criteria andNickNameGreaterThan(String value) { addCriterion("nick_name >", value, "nickName"); return (Criteria) this; } public Criteria andNickNameGreaterThanOrEqualTo(String value) { addCriterion("nick_name >=", value, "nickName"); return (Criteria) this; } public Criteria andNickNameLessThan(String value) { addCriterion("nick_name <", value, "nickName"); return (Criteria) this; } public Criteria andNickNameLessThanOrEqualTo(String value) { addCriterion("nick_name <=", value, "nickName"); return (Criteria) this; } public Criteria andNickNameLike(String value) { addCriterion("nick_name like", value, "nickName"); return (Criteria) this; } public Criteria andNickNameNotLike(String value) { addCriterion("nick_name not like", value, "nickName"); return (Criteria) this; } public Criteria andNickNameIn(List<String> values) { addCriterion("nick_name in", values, "nickName"); return (Criteria) this; } public Criteria andNickNameNotIn(List<String> values) { addCriterion("nick_name not in", values, "nickName"); return (Criteria) this; } public Criteria andNickNameBetween(String value1, String value2) { addCriterion("nick_name between", value1, value2, "nickName"); return (Criteria) this; } public Criteria andNickNameNotBetween(String value1, String value2) { addCriterion("nick_name not between", value1, value2, "nickName"); return (Criteria) this; } public Criteria andSexIsNull() { addCriterion("sex is null"); return (Criteria) this; } public Criteria andSexIsNotNull() { addCriterion("sex is not null"); return (Criteria) this; } public Criteria andSexEqualTo(Integer value) { addCriterion("sex =", value, "sex"); return (Criteria) this; } public Criteria andSexNotEqualTo(Integer value) { addCriterion("sex <>", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThan(Integer value) { addCriterion("sex >", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThanOrEqualTo(Integer value) { addCriterion("sex >=", value, "sex"); return (Criteria) this; } public Criteria andSexLessThan(Integer value) { addCriterion("sex <", value, "sex"); return (Criteria) this; } public Criteria andSexLessThanOrEqualTo(Integer value) { addCriterion("sex <=", value, "sex"); return (Criteria) this; } public Criteria andSexIn(List<Integer> values) { addCriterion("sex in", values, "sex"); return (Criteria) this; } public Criteria andSexNotIn(List<Integer> values) { addCriterion("sex not in", values, "sex"); return (Criteria) this; } public Criteria andSexBetween(Integer value1, Integer value2) { addCriterion("sex between", value1, value2, "sex"); return (Criteria) this; } public Criteria andSexNotBetween(Integer value1, Integer value2) { addCriterion("sex not between", value1, value2, "sex"); return (Criteria) this; } public Criteria andBirthdayIsNull() { addCriterion("birthday is null"); return (Criteria) this; } public Criteria andBirthdayIsNotNull() { addCriterion("birthday is not null"); return (Criteria) this; } public Criteria andBirthdayEqualTo(Date value) { addCriterionForJDBCDate("birthday =", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotEqualTo(Date value) { addCriterionForJDBCDate("birthday <>", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayGreaterThan(Date value) { addCriterionForJDBCDate("birthday >", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("birthday >=", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayLessThan(Date value) { addCriterionForJDBCDate("birthday <", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("birthday <=", value, "birthday"); return (Criteria) this; } public Criteria andBirthdayIn(List<Date> values) { addCriterionForJDBCDate("birthday in", values, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotIn(List<Date> values) { addCriterionForJDBCDate("birthday not in", values, "birthday"); return (Criteria) this; } public Criteria andBirthdayBetween(Date value1, Date value2) { addCriterionForJDBCDate("birthday between", value1, value2, "birthday"); return (Criteria) this; } public Criteria andBirthdayNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("birthday not between", value1, value2, "birthday"); return (Criteria) this; } public Criteria andEmailIsNull() { addCriterion("email is null"); return (Criteria) this; } public Criteria andEmailIsNotNull() { addCriterion("email is not null"); return (Criteria) this; } public Criteria andEmailEqualTo(String value) { addCriterion("email =", value, "email"); return (Criteria) this; } public Criteria andEmailNotEqualTo(String value) { addCriterion("email <>", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThan(String value) { addCriterion("email >", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThanOrEqualTo(String value) { addCriterion("email >=", value, "email"); return (Criteria) this; } public Criteria andEmailLessThan(String value) { addCriterion("email <", value, "email"); return (Criteria) this; } public Criteria andEmailLessThanOrEqualTo(String value) { addCriterion("email <=", value, "email"); return (Criteria) this; } public Criteria andEmailLike(String value) { addCriterion("email like", value, "email"); return (Criteria) this; } public Criteria andEmailNotLike(String value) { addCriterion("email not like", value, "email"); return (Criteria) this; } public Criteria andEmailIn(List<String> values) { addCriterion("email in", values, "email"); return (Criteria) this; } public Criteria andEmailNotIn(List<String> values) { addCriterion("email not in", values, "email"); return (Criteria) this; } public Criteria andEmailBetween(String value1, String value2) { addCriterion("email between", value1, value2, "email"); return (Criteria) this; } public Criteria andEmailNotBetween(String value1, String value2) { addCriterion("email not between", value1, value2, "email"); return (Criteria) this; } public Criteria andProvinceIsNull() { addCriterion("province is null"); return (Criteria) this; } public Criteria andProvinceIsNotNull() { addCriterion("province is not null"); return (Criteria) this; } public Criteria andProvinceEqualTo(String value) { addCriterion("province =", value, "province"); return (Criteria) this; } public Criteria andProvinceNotEqualTo(String value) { addCriterion("province <>", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThan(String value) { addCriterion("province >", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThanOrEqualTo(String value) { addCriterion("province >=", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThan(String value) { addCriterion("province <", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThanOrEqualTo(String value) { addCriterion("province <=", value, "province"); return (Criteria) this; } public Criteria andProvinceLike(String value) { addCriterion("province like", value, "province"); return (Criteria) this; } public Criteria andProvinceNotLike(String value) { addCriterion("province not like", value, "province"); return (Criteria) this; } public Criteria andProvinceIn(List<String> values) { addCriterion("province in", values, "province"); return (Criteria) this; } public Criteria andProvinceNotIn(List<String> values) { addCriterion("province not in", values, "province"); return (Criteria) this; } public Criteria andProvinceBetween(String value1, String value2) { addCriterion("province between", value1, value2, "province"); return (Criteria) this; } public Criteria andProvinceNotBetween(String value1, String value2) { addCriterion("province not between", value1, value2, "province"); return (Criteria) this; } public Criteria andCityIsNull() { addCriterion("city is null"); return (Criteria) this; } public Criteria andCityIsNotNull() { addCriterion("city is not null"); return (Criteria) this; } public Criteria andCityEqualTo(String value) { addCriterion("city =", value, "city"); return (Criteria) this; } public Criteria andCityNotEqualTo(String value) { addCriterion("city <>", value, "city"); return (Criteria) this; } public Criteria andCityGreaterThan(String value) { addCriterion("city >", value, "city"); return (Criteria) this; } public Criteria andCityGreaterThanOrEqualTo(String value) { addCriterion("city >=", value, "city"); return (Criteria) this; } public Criteria andCityLessThan(String value) { addCriterion("city <", value, "city"); return (Criteria) this; } public Criteria andCityLessThanOrEqualTo(String value) { addCriterion("city <=", value, "city"); return (Criteria) this; } public Criteria andCityLike(String value) { addCriterion("city like", value, "city"); return (Criteria) this; } public Criteria andCityNotLike(String value) { addCriterion("city not like", value, "city"); return (Criteria) this; } public Criteria andCityIn(List<String> values) { addCriterion("city in", values, "city"); return (Criteria) this; } public Criteria andCityNotIn(List<String> values) { addCriterion("city not in", values, "city"); return (Criteria) this; } public Criteria andCityBetween(String value1, String value2) { addCriterion("city between", value1, value2, "city"); return (Criteria) this; } public Criteria andCityNotBetween(String value1, String value2) { addCriterion("city not between", value1, value2, "city"); return (Criteria) this; } public Criteria andHeadUrlIsNull() { addCriterion("head_url is null"); return (Criteria) this; } public Criteria andHeadUrlIsNotNull() { addCriterion("head_url is not null"); return (Criteria) this; } public Criteria andHeadUrlEqualTo(String value) { addCriterion("head_url =", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlNotEqualTo(String value) { addCriterion("head_url <>", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlGreaterThan(String value) { addCriterion("head_url >", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlGreaterThanOrEqualTo(String value) { addCriterion("head_url >=", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlLessThan(String value) { addCriterion("head_url <", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlLessThanOrEqualTo(String value) { addCriterion("head_url <=", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlLike(String value) { addCriterion("head_url like", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlNotLike(String value) { addCriterion("head_url not like", value, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlIn(List<String> values) { addCriterion("head_url in", values, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlNotIn(List<String> values) { addCriterion("head_url not in", values, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlBetween(String value1, String value2) { addCriterion("head_url between", value1, value2, "headUrl"); return (Criteria) this; } public Criteria andHeadUrlNotBetween(String value1, String value2) { addCriterion("head_url not between", value1, value2, "headUrl"); return (Criteria) this; } public Criteria andPasswordIsNull() { addCriterion("password is null"); return (Criteria) this; } public Criteria andPasswordIsNotNull() { addCriterion("password is not null"); return (Criteria) this; } public Criteria andPasswordEqualTo(String value) { addCriterion("password =", value, "password"); return (Criteria) this; } public Criteria andPasswordNotEqualTo(String value) { addCriterion("password <>", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThan(String value) { addCriterion("password >", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThanOrEqualTo(String value) { addCriterion("password >=", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThan(String value) { addCriterion("password <", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThanOrEqualTo(String value) { addCriterion("password <=", value, "password"); return (Criteria) this; } public Criteria andPasswordLike(String value) { addCriterion("password like", value, "password"); return (Criteria) this; } public Criteria andPasswordNotLike(String value) { addCriterion("password not like", value, "password"); return (Criteria) this; } public Criteria andPasswordIn(List<String> values) { addCriterion("password in", values, "password"); return (Criteria) this; } public Criteria andPasswordNotIn(List<String> values) { addCriterion("password not in", values, "password"); return (Criteria) this; } public Criteria andPasswordBetween(String value1, String value2) { addCriterion("password between", value1, value2, "password"); return (Criteria) this; } public Criteria andPasswordNotBetween(String value1, String value2) { addCriterion("password not between", value1, value2, "password"); return (Criteria) this; } public Criteria andInsertTimeIsNull() { addCriterion("insert_time is null"); return (Criteria) this; } public Criteria andInsertTimeIsNotNull() { addCriterion("insert_time is not null"); return (Criteria) this; } public Criteria andInsertTimeEqualTo(Date value) { addCriterion("insert_time =", value, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeNotEqualTo(Date value) { addCriterion("insert_time <>", value, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeGreaterThan(Date value) { addCriterion("insert_time >", value, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeGreaterThanOrEqualTo(Date value) { addCriterion("insert_time >=", value, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeLessThan(Date value) { addCriterion("insert_time <", value, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeLessThanOrEqualTo(Date value) { addCriterion("insert_time <=", value, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeIn(List<Date> values) { addCriterion("insert_time in", values, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeNotIn(List<Date> values) { addCriterion("insert_time not in", values, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeBetween(Date value1, Date value2) { addCriterion("insert_time between", value1, value2, "insertTime"); return (Criteria) this; } public Criteria andInsertTimeNotBetween(Date value1, Date value2) { addCriterion("insert_time not between", value1, value2, "insertTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andCaptchaIsNull() { addCriterion("captcha is null"); return (Criteria) this; } public Criteria andCaptchaIsNotNull() { addCriterion("captcha is not null"); return (Criteria) this; } public Criteria andCaptchaEqualTo(String value) { addCriterion("captcha =", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaNotEqualTo(String value) { addCriterion("captcha <>", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaGreaterThan(String value) { addCriterion("captcha >", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaGreaterThanOrEqualTo(String value) { addCriterion("captcha >=", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaLessThan(String value) { addCriterion("captcha <", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaLessThanOrEqualTo(String value) { addCriterion("captcha <=", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaLike(String value) { addCriterion("captcha like", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaNotLike(String value) { addCriterion("captcha not like", value, "captcha"); return (Criteria) this; } public Criteria andCaptchaIn(List<String> values) { addCriterion("captcha in", values, "captcha"); return (Criteria) this; } public Criteria andCaptchaNotIn(List<String> values) { addCriterion("captcha not in", values, "captcha"); return (Criteria) this; } public Criteria andCaptchaBetween(String value1, String value2) { addCriterion("captcha between", value1, value2, "captcha"); return (Criteria) this; } public Criteria andCaptchaNotBetween(String value1, String value2) { addCriterion("captcha not between", value1, value2, "captcha"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
[ "nycz1994@163.com" ]
nycz1994@163.com
fa963c968240beb2c803241e4eea04290f1c5578
ed7bebd1aa34595b5bde66b9c5e0463f441f099d
/src/main/java/com/morhun/product/policy/dto/ExpensesDto.java
b1b3df5805bc3ea5eba05cbc02b0c7bfade2faad
[]
no_license
ymorhun/product-policy
a1f193a1a8a2a15188bc460f162152e208eef73d
d8aa325cfa4f11a1a64c6cca9867ffac94a7a574
refs/heads/master
2021-05-11T19:51:59.760842
2018-01-14T21:00:22
2018-01-14T21:00:22
117,424,122
0
0
null
null
null
null
UTF-8
Java
false
false
613
java
package com.morhun.product.policy.dto; import java.util.Map; /** * Created by yarki on 28.06.2017. */ public class ExpensesDto { private double reserve; private Map<Integer, Double> productIdToExpenses; public double getReserve() { return reserve; } public void setReserve(double reserve) { this.reserve = reserve; } public Map<Integer, Double> getProductIdToExpenses() { return productIdToExpenses; } public void setProductIdToExpenses(Map<Integer, Double> productIdToExpenses) { this.productIdToExpenses = productIdToExpenses; } }
[ "yaroslav_morhun@epam.com" ]
yaroslav_morhun@epam.com
624999b402206ca622b2394e7a21625eccfb00e9
2621ecdf9c799b316244d802382bc44843a6f7ce
/open-iam-sms-aliyun/src/main/java/com/rnkrsoft/opensource/iam/services/AliyunSmsService.java
dc02f882c9a9b02ece8ef3619e99143be5592b6a
[]
no_license
artoruis/OpenIAM
cf0b879c06b0056893c31fa07fa38d03c278b6c4
efbbfe323af42a48f83c263ec408c5018ab4cf4e
refs/heads/master
2023-04-09T21:28:19.574902
2019-08-29T17:44:50
2019-08-29T17:44:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,415
java
package com.rnkrsoft.opensource.iam.services; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.rnkrsoft.opensource.iam.internal.config.SmsConfig; import com.rnkrsoft.opensource.iam.internal.sms.services.SmsService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.Map; /** * Created by woate on 2019/7/17. */ @Slf4j public class AliyunSmsService implements SmsService { @Autowired SmsConfig smsConfig; final static Gson GSON = new GsonBuilder().serializeNulls().create(); @Override public void sendValidateMessage(String mobileNo, String code) { IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsConfig.getAliyunAccessKeyId(), smsConfig.getAliyunAccessKeySecret()); try { DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com"); } catch (ClientException e) { e.printStackTrace(); } IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest sendSmsRequest = new SendSmsRequest(); sendSmsRequest.setPhoneNumbers(mobileNo); sendSmsRequest.setSignName(smsConfig.getAliyunSignName()); sendSmsRequest.setTemplateCode(smsConfig.getValidateSmsTemplateCode()); Map params = new HashMap(); params.put("code", code); sendSmsRequest.setTemplateParam(GSON.toJson(params)); SendSmsResponse sendSmsResponse = null; try { sendSmsResponse = acsClient.getAcsResponse(sendSmsRequest); } catch (ClientException e) { e.printStackTrace(); } log.info("手机号:{} 发送验证码结果{}:{}", mobileNo, sendSmsResponse.getCode(), sendSmsResponse.getMessage()); } @Override public void sendNoticeMessage(String mobileNo, String message) { IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsConfig.getAliyunAccessKeyId(), smsConfig.getAliyunAccessKeySecret()); try { DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com"); } catch (ClientException e) { e.printStackTrace(); } IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest sendSmsRequest = new SendSmsRequest(); sendSmsRequest.setPhoneNumbers(mobileNo); sendSmsRequest.setSignName(smsConfig.getAliyunSignName()); sendSmsRequest.setTemplateCode(smsConfig.getNoticeSmsTemplateCode()); Map params = new HashMap(); params.put("message", message); sendSmsRequest.setTemplateParam(GSON.toJson(params)); SendSmsResponse sendSmsResponse = null; try { sendSmsResponse = acsClient.getAcsResponse(sendSmsRequest); } catch (ClientException e) { e.printStackTrace(); } log.info("手机号:{} 发送通知结果{}:{}", mobileNo, sendSmsResponse.getCode(), sendSmsResponse.getMessage()); } }
[ "master@qq.com" ]
master@qq.com
dd339ad7d8e82515ae7c3e5758381982ea428268
be093e98761393c91928f9512c4e3a3386d797bb
/git-java/src/main/java/com/bjpowernode/git/Test.java
9bb7faada897562a9c3c7241d9d6080139d71a71
[]
no_license
cc20120914/git-project
729aff52f13252ffaf85a4e310544283f319f505
43fab7dafd6063974d35c7844a795bb4c17883ae
refs/heads/master
2023-01-27T11:54:19.320311
2020-12-12T06:50:31
2020-12-12T06:50:31
320,775,536
0
0
null
null
null
null
UTF-8
Java
false
false
186
java
package com.bjpowernode.git; /** * 2005田超凡 * 2020/12/12 */ public class Test { public static void main(String[] args) { System.out.println("hello world@"); } }
[ "zhangsan@163.com" ]
zhangsan@163.com
fe0c02f1eb2da2926867c69ac0d18355d261fdf2
7da062a314468aebcfee58c6807495d163d54ab5
/app/src/main/java/com/hackerearth/zetafood/ui/adapter/CartAdapter.java
a0889b0fc3a69d8865350196382a204a56fbab8b
[]
no_license
Yadunath/ZetaFood
b3e523d73b72d82925b8105997c2cdd9b6af08f2
9acad54184f448451a5140c2f6f298b72ee67291
refs/heads/main
2023-01-22T12:26:28.592185
2020-12-04T12:53:52
2020-12-04T12:53:52
318,514,867
0
0
null
null
null
null
UTF-8
Java
false
false
2,080
java
package com.hackerearth.zetafood.ui.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.hackerearth.zetafood.R; import com.hackerearth.zetafood.data.local.entity.CartEntity; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> { private List<CartEntity> cartEntities; public CartAdapter(List<CartEntity> cartEntities) { this.cartEntities = cartEntities; } @NonNull @Override public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.cart_layout_item, parent, false); return new CartViewHolder(view); } @Override public void onBindViewHolder(@NonNull CartViewHolder holder, int position) { CartEntity cartEntity = cartEntities.get(position); if (cartEntity !=null){ holder.title.setText(cartEntity.name); holder.type.setText(cartEntity.category); holder.price.setText(cartEntity.price+" $"); Glide.with(holder.itemView.getContext()).load(cartEntity.imageUrl).circleCrop().into(holder.imageView); } } @Override public int getItemCount() { return cartEntities.size(); } public class CartViewHolder extends RecyclerView.ViewHolder { ImageView imageView; TextView title; TextView type; TextView price; public CartViewHolder(@NonNull View itemView) { super(itemView); title = itemView.findViewById(R.id.title); type = itemView.findViewById(R.id.type); price = itemView.findViewById(R.id.price); imageView = itemView.findViewById(R.id.imageView); } } }
[ "developers.idroidz@gmail.com" ]
developers.idroidz@gmail.com
146da7f808cd34582519f79b2eef27a0881a3319
3289413392fe2e1ec3f83d47f1069dca785052ca
/app/src/main/java/edu/msu/liunan/examliunan/HaroldSpinView.java
5dba4e4b5500c0921b23305582be4a762705b6c6
[]
no_license
liunan10/an-example-of-Android-app
062d42269429203f0fb447ac2edaaf4afe045103
03f678192666b78b9a5855cea52e598da5f557ca
refs/heads/master
2021-01-10T08:12:26.882525
2016-01-25T00:04:11
2016-01-25T00:04:11
49,661,897
0
0
null
null
null
null
UTF-8
Java
false
false
7,962
java
package edu.msu.liunan.examliunan; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextPaint; import android.util.AttributeSet; import android.util.Log; import android.view.View; import java.io.Serializable; import java.util.Random; /** * TODO: document your custom view class. */ public class HaroldSpinView extends View { private static class Parameters implements Serializable { /** * spinCount and spinMoney used in textSpin */ private int spinMoney=0; private int spinCount=0; /** * location of the box, 2D array index randomX and randomY */ private int randomX=-5; private int randomY=-5; /** Spin rate in boxes per second */ private double spinRate = START_RATE; /** * current button state * spinning true, start spinning * isStop stop spinning */ private boolean spinning = false; private boolean isSTop=false; } /** * The image bitmap. None initially. */ private Bitmap imageBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.haroldgrid);; /** * Image drawing scale */ private float imageScale = 1; /** * Image left margin in pixels */ private float marginLeft = 0; /** * Image top margin in pixels */ private float marginTop = 0; public static final double START_RATE =2.0; private double SPEEDUP =1.01; /** Time we last called onDraw */ private long lastTime = 0; /** How long a box has been on the screen */ private double duration = 0; private Random rnd = new Random(); private Paint boxPaint; /** Money grid */ private int money[][] = {{1, 5, 100, -1}, {-1, 100, 1, 50}, {5, 50, -1, 20}, {10, 10, -1, 1}}; /** * The current parameters */ private Parameters params = new Parameters(); public HaroldSpinView(Context context) { super(context); init(null, 0); } public HaroldSpinView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public HaroldSpinView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } private void init(AttributeSet attrs, int defStyle) { boxPaint = new Paint(Paint.ANTI_ALIAS_FLAG); boxPaint.setColor(Color.RED); boxPaint.setStrokeWidth(10); boxPaint.setStyle(Paint.Style.STROKE); } /** * Handle a draw event * * @param canvas canvas to draw on. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); /* * Determine the margins and scale to draw the image * centered and scaled to maximum size on any display */ // Get the canvas size float wid = canvas.getWidth(); float hit = canvas.getHeight(); // What would be the scale to draw the where it fits both // horizontally and vertically? float scaleH = wid / imageBitmap.getWidth(); float scaleV = hit / imageBitmap.getHeight(); // Use the lesser of the two imageScale = scaleH < scaleV ? scaleH : scaleV; // What is the scaled image size? float iWid = imageScale * imageBitmap.getWidth(); float iHit = imageScale * imageBitmap.getHeight(); // Determine the top and left margins to center marginLeft = (wid - iWid) / 2; marginTop = (hit - iHit) / 2; /* * Draw the image bitmap */ canvas.save(); canvas.translate(marginLeft, marginTop); canvas.scale(imageScale, imageScale); canvas.drawBitmap(imageBitmap, 0, 0, null); canvas.restore(); if(params.spinning) { long time = System.currentTimeMillis(); double delta = (time - lastTime) * 0.001; lastTime = time; duration += delta; if(duration >= 1.0 / params.spinRate ) { newCell(); params.spinRate *= SPEEDUP; duration = 0; } drawBox(canvas); postInvalidate(); } if (params.isSTop){ drawBox(canvas); } } public void setSpinning(boolean spin){ params.spinning = spin; } public boolean getSpinning(){ return params.spinning; } public void newCell() { // generate two random Integer [0-3] params.randomX = rnd.nextInt(4); params.randomY = rnd.nextInt(4); } public void drawBox(Canvas canvas){ // Compute left corner coordinate float iWid = imageScale * imageBitmap.getWidth(); float iHit = imageScale * imageBitmap.getHeight(); float boxSizeX= iWid/8; float boxSizeY=iHit/8; float boxCenterX=marginLeft+((2*params.randomX+1)*boxSizeX); float boxCenterY=marginTop+((2*params.randomY+1)*boxSizeY); //draw a box starting at left corner coordinates. canvas.save(); canvas.translate(boxCenterX, boxCenterY); canvas.rotate(0); canvas.drawRect(-boxSizeX, -boxSizeY, boxSizeX, boxSizeY, boxPaint); canvas.restore(); } public void setIsStop(boolean stop){ params.isSTop=true; } public boolean getIsStop(){ return params.isSTop; } public void calculateMoney(){ //Log.i("Money[1][0]",String.valueOf(money[1][0])); if (money[params.randomY][params.randomX]==-1){ //Log.i("money["+String.valueOf(randomX)+String.valueOf(randomY),String.valueOf(money[randomX][randomY])); params.spinMoney=0; } else{ params.spinMoney+=money[params.randomY][params.randomX]; } } public void calculateSpinCount(){ if (params.spinning){ params.spinCount++; } } public int getSpinMoney(){ return params.spinMoney; } public int getSpinCount(){ return params.spinCount; } public void setSpinMoney(int currentMoney){ params.spinMoney=currentMoney; } public void setSpinCount(int currentCount){ params.spinCount=currentCount; } public void setSpinRate(double rate){ params.spinRate=rate; } public void setRandomX(int randomX){ params.randomX=randomX; } public void setRandomY(int randomY){ params.randomY=randomY; } public void putToBundle(String key, Bundle bundle){ bundle.putSerializable(key, params); } public void getFromBundle(String key, Bundle bundle){ params = (Parameters)bundle.getSerializable(key); // Ensure the options are all set setSpinMoney(params.spinMoney); setSpinCount(params.spinCount); setSpinning(params.spinning); setIsStop(params.isSTop); setSpinRate(params.spinRate); setRandomX(params.randomX); setRandomY(params.randomY); } public void startNewGame(){ params.spinMoney=0; params.spinCount=0; /** * location of the box, 2D array index randomX and randomY */ params.randomX=-5; params.randomY=-5; /** Spin rate in boxes per second */ params.spinRate = START_RATE; /** * current button state * spinning true, start spinning * isStop stop spinning */ params.spinning = false; params.isSTop=false; } }
[ "nan.liu1987@gmail.com" ]
nan.liu1987@gmail.com
d9eff41b0f49428742526b3875c70b7d94acb0c8
a051ac2d94f54699a45d0e62c211048f0951b17f
/bdaj/src/main/java/big_data_analytics_java/chp1/Test.java
31969bfa4b6d8ccc991efef7f8bed355ba785ad4
[ "MIT" ]
permissive
ilya1245/Big-Data-Analytics-with-Java
6eef96a8a6f72b174bc6b9616861af49b1fd6d38
b9f341a9d5930db7c8a0890a1410cc36d6b186ec
refs/heads/master
2020-04-19T05:13:31.538849
2019-08-08T05:30:19
2019-08-08T05:30:19
167,981,748
0
0
MIT
2019-01-28T15:05:38
2019-01-28T15:05:38
null
UTF-8
Java
false
false
341
java
package big_data_analytics_java.chp1; public class Test { public static void main(String[] args) { System.out.println("Car type -> Abarth"); System.out.println("Car type -> AlfaRomeo"); System.out.println("Car type -> Autobianchi"); System.out.println("Car type -> Bizzarinni"); System.out.println("Car type -> Bugatti"); } }
[ "rajat.me@gmail.com" ]
rajat.me@gmail.com
41948df937c23ffc95446a67b85bc715167e9d8d
5e04564d70699c245e0a5470fac1c81b696b4824
/video-procedure-backend/src/main/java/com/westwell/backend/modules/sys/service/SysLogService.java
f549606d9216509e2836014098947df39985b6fc
[]
no_license
haizeigh/video
7651e64679665ad330ce5fb7f7578a977ee0110e
f49445e508752b1c38ad55d3e337a855b6145488
refs/heads/main
2023-03-27T02:34:43.354180
2021-03-11T03:29:49
2021-03-11T03:29:49
337,028,256
0
0
null
null
null
null
UTF-8
Java
false
false
570
java
/** * Copyright (c) 2016-2019 人人开源 All rights reserved. * * https://www.renren.io * * 版权所有,侵权必究! */ package com.westwell.backend.modules.sys.service; import com.baomidou.mybatisplus.extension.service.IService; import com.westwell.backend.common.utils.PageUtils; import com.westwell.backend.modules.sys.entity.SysLogEntity; import java.util.Map; /** * 系统日志 * * @author Mark sunlightcs@gmail.com */ public interface SysLogService extends IService<SysLogEntity> { PageUtils queryPage(Map<String, Object> params); }
[ "1254126426@qq.com" ]
1254126426@qq.com
6a2f0e79d73daed3670477ad43f7bf966fcdce7f
490b4eb6c9a3e51d8e3bf717e4eeade85ccef77c
/commonlib/src/main/java/com/cryallen/commonlib/utils/ThemeUtils.java
6dd751bc26edea900d1dc9250975a3441a737494
[]
no_license
cr330326/commonhello
76b9fb0982e3348c6b10593c770d3064a8179e3e
606f7d2f0eccac3623a8984ea05cedf0384ef906
refs/heads/master
2021-06-29T15:54:57.874120
2021-03-30T11:20:33
2021-03-30T11:20:33
226,026,279
1
0
null
null
null
null
UTF-8
Java
false
false
3,492
java
package com.cryallen.commonlib.utils; import android.content.Context; import android.content.res.TypedArray; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import com.cryallen.commonlib.R; /** * 作者:杭鹏伟 * 日期:16-7-8 15:15 * 邮箱:424346976@qq.com */ public class ThemeUtils { public static int[][] themeArr = { {R.style.AppThemeLight_Red, R.style.AppThemeDark_Red}, {R.style.AppThemeLight_Pink, R.style.AppThemeDark_Pink}, {R.style.AppThemeLight_Purple, R.style.AppThemeDark_Purple}, {R.style.AppThemeLight_DeepPurple, R.style.AppThemeDark_DeepPurple}, {R.style.AppThemeLight_Indigo, R.style.AppThemeDark_Indigo}, {R.style.AppThemeLight_Blue, R.style.AppThemeDark_Blue}, {R.style.AppThemeLight_LightBlue, R.style.AppThemeDark_LightBlue}, {R.style.AppThemeLight_Cyan, R.style.AppThemeDark_Cyan}, {R.style.AppThemeLight_Teal, R.style.AppThemeDark_Teal}, {R.style.AppThemeLight_Green, R.style.AppThemeDark_Green}, {R.style.AppThemeLight_LightGreen, R.style.AppThemeDark_LightGreen}, {R.style.AppThemeLight_Lime, R.style.AppThemeDark_Lime}, {R.style.AppThemeLight_Yellow, R.style.AppThemeDark_Yellow}, {R.style.AppThemeLight_Amber, R.style.AppThemeDark_Amber}, {R.style.AppThemeLight_Orange, R.style.AppThemeDark_Orange}, {R.style.AppThemeLight_DeepOrange, R.style.AppThemeDark_DeepOrange}, {R.style.AppThemeLight_Brown, R.style.AppThemeDark_Brown}, {R.style.AppThemeLight_Grey, R.style.AppThemeDark_Grey}, {R.style.AppThemeLight_BlueGrey, R.style.AppThemeDark_BlueGrey} }; public static int[][] themeColorArr = { {R.color.md_red_500, R.color.md_red_700}, {R.color.md_pink_500, R.color.md_pink_700}, {R.color.md_purple_500, R.color.md_purple_700}, {R.color.md_deep_purple_500, R.color.md_deep_purple_700}, {R.color.md_indigo_500, R.color.md_indigo_700}, {R.color.md_blue_500, R.color.md_blue_700}, {R.color.md_light_blue_500, R.color.md_light_blue_700}, {R.color.md_cyan_500, R.color.md_cyan_700}, {R.color.md_teal_500, R.color.md_teal_500}, {R.color.md_green_500, R.color.md_green_500}, {R.color.md_light_green_500, R.color.md_light_green_500}, {R.color.md_lime_500, R.color.md_lime_700}, {R.color.md_yellow_500, R.color.md_yellow_700}, {R.color.md_amber_500, R.color.md_amber_700}, {R.color.md_orange_500, R.color.md_orange_700}, {R.color.md_deep_orange_500, R.color.md_deep_orange_700}, {R.color.md_brown_500, R.color.md_brown_700}, {R.color.md_grey_500, R.color.md_grey_700}, {R.color.md_blue_grey_500, R.color.md_blue_grey_700} }; public static int getTheme(Context context) { return context.getResources().getColor(themeColorArr[SpUtils.getThemeIndex(context)][0]); } public static int getThemeColor(@NonNull Context context) { return getThemeAttrColor(context, R.attr.colorPrimary); } public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) { TypedArray a = context.obtainStyledAttributes(null, new int[]{attr}); try { return a.getColor(0, 0); } finally { a.recycle(); } } }
[ "cr330326@gmail.com" ]
cr330326@gmail.com
18ae1321c7ac652d36e01dee9a176625b38c1183
e189c55cbeaa1a5574dd3016473fbf62b2887608
/src/Model/Server/Configurations.java
14cf81eb59b569e1c1aaefc5406c9e1f9496a719
[ "MIT" ]
permissive
MoranChery/ATP2019-Project
656286ba2f103e6ac452e026d921e5ff386f5998
c9fd312626fb515b07f60bad237b83fc5cc984bd
refs/heads/master
2020-05-30T16:09:23.991904
2019-06-10T12:40:08
2019-06-10T12:40:08
189,839,824
0
0
MIT
2019-06-05T10:22:14
2019-06-02T11:47:09
Java
UTF-8
Java
false
false
2,391
java
package Model.Server; import Model.algorithms.mazeGenerators.IMazeGenerator; import Model.algorithms.mazeGenerators.MyMazeGenerator; import Model.algorithms.mazeGenerators.SimpleMazeGenerator; import Model.algorithms.search.BestFirstSearch; import Model.algorithms.search.BreadthFirstSearch; import Model.algorithms.search.DepthFirstSearch; import Model.algorithms.search.ISearchingAlgorithm; import java.io.*; import java.util.Objects; import java.util.Properties; public final class Configurations { private static Properties properties = new Properties(); public synchronized static void runConf() { try { File f = new File("resources/config.properties"); if (!f.exists()) createConf(); InputStream input = new FileInputStream("resources/config.properties"); properties.load(input); } catch(IOException e) { e.printStackTrace(); } } private static void createConf() { OutputStream output; try { output = new FileOutputStream("resources/config.properties"); // set the ProjectProperties value properties.setProperty("MazeGenerator", "MyMazeGenerator"); properties.setProperty("NumberOfThreads", "7"); properties.setProperty("SearchingAlgorithm", "BFS"); // save ProjectProperties to project root folder properties.store(output, null); } catch(IOException io) { io.printStackTrace(); } } static int getNumberOfThreads() { String value = properties.getProperty("NumberOfThreads"); int threadNum = Objects.equals(value, "") ? 10 : Integer.parseInt(value); return threadNum > 0 ? threadNum : 10; } static IMazeGenerator getMazeGenerator() { String value = properties.getProperty("MazeGenerator"); return Objects.equals(value, "SimpleMazeGenerator") ? new SimpleMazeGenerator() : new MyMazeGenerator(); } static ISearchingAlgorithm getSearchingAlgorithm() { String value = properties.getProperty("SearchingAlgorithm"); if (Objects.equals(value, "DepthFirstSearch")) return new DepthFirstSearch(); else if (Objects.equals(value, "BestFirstSearch")) return new BestFirstSearch(); else return new BreadthFirstSearch(); } }
[ "avihaipp@gmail.com" ]
avihaipp@gmail.com
1287e59395b47af408e76fc3286123dcd21dc93b
db6b6d3a1d5fcc343948002723601c9d773307bc
/src/main/java/org/mohansun/dev/adapter/CustomConfigAdapter.java
3b91c854c2b63c9018ea77e7518f413bad06d76c
[]
no_license
mohan-chinnappan-n/aura-apps
d56175c978ae1c349fbd6c2b7bb8397fa27f20be
6dbb6810bf1bdfc07bca66fd82ccf2f74a4e231b
refs/heads/master
2023-07-19T22:39:34.614207
2017-12-27T15:10:48
2017-12-27T15:10:48
115,532,650
0
0
null
2023-07-16T12:19:41
2017-12-27T15:11:57
Java
UTF-8
Java
false
false
395
java
package org.mohansun.dev.adapter; import org.auraframework.annotations.Annotations.ServiceComponent; import org.springframework.context.annotation.Primary; import test.org.auraframework.impl.adapter.ConfigAdapterImpl; @ServiceComponent @Primary public class CustomConfigAdapter extends ConfigAdapterImpl { @Override public String getCSRFToken() { return "helloWorld"; } }
[ "mohan.chinnappan.n@gmail.com" ]
mohan.chinnappan.n@gmail.com
be3f6acca5e98b8b2c112e812b46ef7a6b2e726e
5333823c6d52649910382ad02e3d50476d822020
/WorkDistributor.java
d2e4239e1d138d2969bda6a98ef30576ef5d9d75
[]
no_license
jammat/hojjihoji
809f9bc13625df2e7dbd9492254ca1cdfc169876
b50f5b5d3efe86f4f67d3902cfa1c57bd65d7025
refs/heads/master
2021-01-10T10:34:07.723744
2015-11-30T14:14:27
2015-11-30T14:14:27
47,027,809
0
0
null
null
null
null
UTF-8
Java
false
false
9,112
java
import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; public class WorkDistributor { public static final int PORT = 3126; public static boolean verboseMode = true; public static void main(String[] args) throws Exception { if (args.length == 1 && args[0].equals("verbose")) { verboseMode = true; } DatagramSocket ds = new DatagramSocket(PORT); ds.setSoTimeout(500000); // 500 sekuntia try { while (true) { byte[] byteArea = new byte[256]; DatagramPacket receivedPacket = new DatagramPacket(byteArea, byteArea.length); ds.receive(receivedPacket); if (verboseMode) { System.out.println("Connection from " + receivedPacket.getAddress() + " port " + receivedPacket.getPort()); } // what was received? String message = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); int contactPort = -1; try { contactPort = Integer.parseInt(message.trim()); } catch (NumberFormatException e) { System.err .println("UDP error, message should represent number, message = " + message); } if (contactPort < 1024 || contactPort > 65535) { if (verboseMode) { System.out.println("Errorneous suggestion for port '" + message + "'"); System.out.println("Contact attempt from " + ds.getInetAddress() + " ignored."); } continue; // jump over the rest } new WorkDistributor.WorkDistributionHandler( receivedPacket.getAddress(), contactPort).start(); } // while } catch (InterruptedIOException e) { } } // main static class WorkDistributionHandler extends Thread { public static final int MAXCLIENTS = 10; private final int clientPort; private final InetAddress clientAddress; private final int[] portNumbers = new int[MAXCLIENTS]; private final Socket[] calculators = new Socket[MAXCLIENTS]; private final ObjectOutputStream[] numberStreams = new ObjectOutputStream[MAXCLIENTS]; public WorkDistributionHandler(InetAddress a, int p) { clientPort = p; clientAddress = a; } @Override public void run() { try { if (verboseMode) { System.out.println("Spawning thread ..."); } Thread.sleep(2000); // let the other side set itself up ... Socket s = new Socket(clientAddress, clientPort); s.setSoTimeout(3000); InputStream iS = s.getInputStream(); OutputStream oS = s.getOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(oS); ObjectInputStream oIn = new ObjectInputStream(iS); int clients = (int) (Math.random() * 9) + 2; if (verboseMode) { System.out.println("Writing " + clients + " to " + clientAddress + " at port " + clientPort); } oOut.writeInt(clients); oOut.flush(); boolean aborting = receivePortNumbers(oIn, clients); if (aborting) { if (verboseMode) { System.out.println("Closing connection to " + clientAddress + " at port " + clientPort); } } else { // try to make the socket connection for (int i = 0; i < clients; i++) { if (verboseMode) { System.out.println("Trying to connect to " + portNumbers[i]); } calculators[i] = new Socket(clientAddress, portNumbers[i]); numberStreams[i] = new ObjectOutputStream( calculators[i].getOutputStream()); if (verboseMode) { System.out.println("Connection to " + i + "'th adder created."); } sleep(100); } generateTraffic(numberStreams, clients, oOut, oIn); for (int i = 0; i < clients; i++) { numberStreams[i].close(); calculators[i].close(); } if (verboseMode) { System.out .println("Connections to calculators closing ..."); } } oOut.writeInt(0); oOut.flush(); // ask the other side to close itself oOut.close(); oIn.close(); oS.close(); iS.close(); s.close(); } catch (Exception e) { throw new Error(e.toString()); } if (verboseMode) { System.out.println("... thread done."); } } // run private boolean makeTest(int question, int answer, ObjectOutputStream masterOut, ObjectInputStream masterIn) throws IOException { masterOut.writeInt(question); masterOut.flush(); int answerRead = masterIn.readInt(); if (answerRead == -1) { System.err.println("Client answered with -1 to question " + question + " ... aborting."); // return true; } if (answer != answerRead) { System.err.println("Error in client: wrong answer to query (" + question + "). Expecting " + answer + " got " + answerRead + "."); return true; } return false; } private void generateTraffic(ObjectOutputStream[] streams, int calcs, ObjectOutputStream masterOut, ObjectInputStream masterIn) { int table[] = new int[calcs]; int sum = 0; int lkm = 0; int answer = 0; for (int i = 0; i < calcs; i++) { table[i] = 0; } int biggest = (int) (Math.random() * calcs); try { streams[biggest].writeInt(2); streams[biggest].flush(); sum = 2; lkm = 1; table[biggest] = 2; // test 1 if (verboseMode) { System.out.println("Making test 1 in set 1"); } makeTest(1, sum, masterOut, masterIn); // test 2 if (verboseMode) { System.out.println("Making test 2 in set 1"); } makeTest(2, biggest + 1, masterOut, masterIn); // test 3 if (verboseMode) { System.out.println("Making test 3 in set 1"); } makeTest(3, lkm, masterOut, masterIn); for (int i = 0; i < 9; i++) { for (int j = 0; j < calcs; j++) { int number = (int) (Math.random() * 40) - 20; if (number == 0) { number++; } streams[j].writeInt(number); streams[j].flush(); table[j] += number; lkm++; sum += number; } } for (int j = 0; j < calcs; j++) { streams[j].flush(); } biggest = 0; for (int i = 1; i < calcs; i++) { if (table[i] > table[biggest]) { biggest = i; } } // test 4 if (verboseMode) { System.out.println("Making test 1 in set 2"); } makeTest(1, sum, masterOut, masterIn); // test 5 if (verboseMode) { System.out.println("Making test 2 in set 2"); } makeTest(2, biggest + 1, masterOut, masterIn); System.out.print("Table: "); for (int i = 0; i < calcs; i++) { System.out.print(" " + table[i]); } System.out.println(""); for (int i = 0; i < calcs; i++) { if ((table[biggest] == table[i]) && (i != biggest)) { System.out .println("Tie with expected value " + (i + 1)); } } // test 6 if (verboseMode) { System.out.println("Making test 3 in set 2"); } makeTest(3, lkm, masterOut, masterIn); streams[0].writeInt(0); streams[0].flush(); if (calcs != 1) { streams[calcs - 1].writeInt(0); streams[calcs - 1].flush(); } // test 7 if (verboseMode) { System.out.println("Making test 1 in set 3"); } makeTest(1, sum, masterOut, masterIn); // test 8 if (verboseMode) { System.out.println("Making test 2 in set 3"); } makeTest(2, biggest + 1, masterOut, masterIn); // test 9 if (verboseMode) { System.out.println("Making test 3 in set 3"); } makeTest(3, lkm, masterOut, masterIn); } catch (IOException e) { System.err .println("Received exception while testing ... aborting."); System.err.println("Exception: " + e); return; } } // generateTraffic public boolean receivePortNumbers(ObjectInputStream oIn, int clients) { boolean aborting = false; if (verboseMode) { System.out.println("Receiving port numbers."); } for (int i = 0; i < clients; i++) { int p; if (verboseMode) { System.out.println("Trying to receive " + i + "th port number."); } try { p = oIn.readInt(); } catch (IOException e) { System.out.println(e); if (verboseMode) { System.out .println("Error in reading portnumbers ... aborting."); } aborting = true; break; } if (i == 0 && p == -1) { // abort, the client didn't receive previous message in time if (verboseMode) { System.out .println("Received -1 from client ... aborting."); } aborting = true; break; } if (p < 1024 || p > 65535) { // illegal port number if (verboseMode) { System.out.println("Illegal port " + p + " from client ... aborting."); } aborting = true; break; } portNumbers[i] = p; if (verboseMode) { System.out.println("Received " + i + "'th port number."); } } // for return aborting; } // receivePortNumbers } // class WorkDistributionHandler } // class WorkDistributor
[ "jammat@utu.fi" ]
jammat@utu.fi
d575620dec2d66297e90627048a7ef2fc1571237
a38c717c55358c8321948f7c32141d3ba508c990
/CardApplication/app/src/test/java/com/example/kevo/cardapplication/ExampleUnitTest.java
79febc8ac37e812fda8f176c4bcca58c24966861
[]
no_license
koechkevoh/android
5e01e1ac124cd0400f4276f88c6c18bdfe70f49d
fb511983ca1e215382dbbae5e60bff2feaa93706
refs/heads/master
2020-04-04T13:38:53.497439
2018-11-03T09:30:32
2018-11-03T09:30:32
155,969,749
0
0
null
null
null
null
UTF-8
Java
false
false
393
java
package com.example.kevo.cardapplication; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "kevo@localhost.localdomain" ]
kevo@localhost.localdomain
b4869521707f193e417326d15e8b8e26e2502292
e60bbe411f75861b167962a6b35e68c82bb6b306
/FlagPickerService/src/main/java/com/sid/demo/flagservice/controllers/MetricsController.java
b201ea6d83a4d42a1b14e4ecff24ee4dbfc46671
[]
no_license
sidgupte/FlagPickerService
66a3e43ad88fb11a926ebfd5320c536b86cd84f2
9b6193697f36dab5203eeadb67544ccf3a5c7e51
refs/heads/master
2021-01-01T23:30:45.451824
2020-02-09T23:43:32
2020-02-09T23:43:32
239,390,777
0
0
null
null
null
null
UTF-8
Java
false
false
1,151
java
package com.sid.demo.flagservice.controllers; import javax.validation.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.sid.demo.flagservice.metrics.MetricsCounter; import com.sid.demo.flagservice.service.MetricsService; @RestController public class MetricsController { @Autowired private MetricsService service; @GetMapping("/metrics/continent/{continentName}") public ResponseEntity getMetricsForContinent(@NotEmpty @PathVariable("continentName") String continentName){ return ResponseEntity.status(HttpStatus.OK).body(MetricsCounter.getCounter(continentName)); } @GetMapping("/metrics/country/{countryName}") public ResponseEntity getMetricsForCountry(@NotEmpty @PathVariable("countryName") String countryName){ return ResponseEntity.status(HttpStatus.OK).body(MetricsCounter.getCounter(countryName)); } }
[ "sid.gupte@gmail.com" ]
sid.gupte@gmail.com
d0b4a71576d1c018a1159a7f7507a2c37ffa07ad
47429c52c137a23514e49d02a2e36b249256612a
/rhymecity/src/main/java/com/fly/firefly/ui/object/BaseClass.java
97d2ebcce6b544e80f02910ae4ef12bec2d5cd2c
[ "MIT" ]
permissive
zatyabdullah/temp
44caadd953f62fcc730c484ed351dcec4f64998b
fe0a6a814d4fb8912b90d7d8e0c3803ebd472cb6
refs/heads/master
2021-01-10T01:42:20.716007
2015-11-30T07:26:04
2015-11-30T07:26:04
46,040,181
0
0
null
null
null
null
UTF-8
Java
false
false
472
java
package com.fly.firefly.ui.object; /** * Created by Dell on 11/9/2015. */ public abstract class BaseClass { String username; String signature; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } }
[ "zaty.abdullah@gmail.com" ]
zaty.abdullah@gmail.com
6ae236aa81712bd1f4ac43c166a929b1c94acb9d
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-chimesdkvoice/src/main/java/com/amazonaws/services/chimesdkvoice/model/transform/SpeakerSearchTaskJsonUnmarshaller.java
0ca71f589fafb4bf7403d0316a42bc0e3e82256f
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379135
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
2023-09-13T23:35:28
2010-03-22T23:34:58
null
UTF-8
Java
false
false
4,648
java
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.chimesdkvoice.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.chimesdkvoice.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * SpeakerSearchTask JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SpeakerSearchTaskJsonUnmarshaller implements Unmarshaller<SpeakerSearchTask, JsonUnmarshallerContext> { public SpeakerSearchTask unmarshall(JsonUnmarshallerContext context) throws Exception { SpeakerSearchTask speakerSearchTask = new SpeakerSearchTask(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("SpeakerSearchTaskId", targetDepth)) { context.nextToken(); speakerSearchTask.setSpeakerSearchTaskId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("SpeakerSearchTaskStatus", targetDepth)) { context.nextToken(); speakerSearchTask.setSpeakerSearchTaskStatus(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("CallDetails", targetDepth)) { context.nextToken(); speakerSearchTask.setCallDetails(CallDetailsJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("SpeakerSearchDetails", targetDepth)) { context.nextToken(); speakerSearchTask.setSpeakerSearchDetails(SpeakerSearchDetailsJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("CreatedTimestamp", targetDepth)) { context.nextToken(); speakerSearchTask.setCreatedTimestamp(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context)); } if (context.testExpression("UpdatedTimestamp", targetDepth)) { context.nextToken(); speakerSearchTask.setUpdatedTimestamp(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context)); } if (context.testExpression("StartedTimestamp", targetDepth)) { context.nextToken(); speakerSearchTask.setStartedTimestamp(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context)); } if (context.testExpression("StatusMessage", targetDepth)) { context.nextToken(); speakerSearchTask.setStatusMessage(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return speakerSearchTask; } private static SpeakerSearchTaskJsonUnmarshaller instance; public static SpeakerSearchTaskJsonUnmarshaller getInstance() { if (instance == null) instance = new SpeakerSearchTaskJsonUnmarshaller(); return instance; } }
[ "" ]
0bc2f119abb59f58dc323c140a82c5e2aaf5730b
5ca4e7d678152edb086855e1f94f507fd88cbe55
/Java/07. private vs Protected vs public vs default/src/UnrelatedOutsidePackage.java
a060edd7fca3ffd68c0403684f36b62547ad6a12
[]
no_license
kleytonvieira/complementos-de-programa-o-sti-ise-ualg
0fbc682fc4edaefae75eb7f702930789ad0d8e3f
422b5a3a30b88c0179e25618b8e8293eed3e10ca
refs/heads/master
2023-03-20T16:57:23.435687
2021-03-25T10:05:30
2021-03-25T10:05:30
351,385,878
0
0
null
null
null
null
UTF-8
Java
false
false
647
java
import cp.pack.Mother; public class UnrelatedOutsidePackage { Mother var; UnrelatedOutsidePackage(){ var.publicArg = 1; //var.protectedArg = 1; //The field Mother.protectedArg is not visible //var.privateArg = 1; //The field Mother.privateArg is not visible //var.defaultArg = 1; //The field Mother.defaultArg is not visible var.publicMethod(); //var.protectedMethod();//The method protectedMethod() from the type Mother is not visible //var.privateMethod(); //The method privateMethod() from the type Mother is not visible //var.defaultMethod(); //The method defaultMethod() from the type Mother is not visible } }
[ "pcardoso@ualg.pt" ]
pcardoso@ualg.pt
fa26142e5b39bfd0fe568f4b85bf770d43ff224c
9f226f0efe833dd03502338b60cc8415c51863a3
/core-java/serialization/SerializationDemo/src/Employee.java
e5425b42ec835e05470c91acd988e70cba6de2c6
[]
no_license
williamdocarmo/frameworks
3cd5a304b2a0b383dd510554fd0942be5051c048
562b7bd383ea24fa07bde151bff96cfbb9edcff7
refs/heads/master
2023-07-13T03:33:50.817119
2021-07-28T20:27:13
2021-07-28T20:27:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
957
java
import java.io.Serializable; public class Employee implements Serializable { private String empName; private String address; private String phoneNumber; public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Employee(String empName, String address, String phoneNumber) { super(); this.empName = empName; this.address = address; this.phoneNumber = phoneNumber; } public Employee() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "Employee [empName=" + empName + ", address=" + address + ", phoneNumber=" + phoneNumber + "]"; } }
[ "santanu.bh6@gmail.com" ]
santanu.bh6@gmail.com
735b2c43f7a5814dfab90cd6b77578f39638811b
87fb7c9d7420df24da9bbe257e44daa48c0b7776
/weixin-core/src/main/java/com/runssnail/monolith/weixin/core/message/service/MessageProcessServiceResolverFeactoryBean.java
091ce8d0bfcdb6ccbceaad7717757d9495ccf088
[]
no_license
pf5512/mono-weixin
11f4eed2abaa59a7feef00ba58fb5e2a384b60fb
c28c435e013b7616cf952660f4d6a9c1a32edbf2
refs/heads/master
2021-01-22T00:36:26.766888
2015-01-20T03:51:48
2015-01-20T03:51:48
null
0
0
null
null
null
null
GB18030
Java
false
false
4,211
java
package com.runssnail.monolith.weixin.core.message.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.runssnail.monolith.weixin.core.message.domain.Message; /** * MessageProcessServiceResolver创建工厂 * * @author zhengwei */ @Service("messageProcessServiceResolver") public class MessageProcessServiceResolverFeactoryBean implements FactoryBean<MessageProcessServiceResolver>, InitializingBean, ApplicationContextAware { private final Logger log = Logger.getLogger(getClass()); private MessageProcessServiceResolver messageProcessServiceResolver; private List<MessageProcessService> messageProcessServices; /** * 默认处理器 */ private MessageProcessService defaultMessageProcessService; /** * true时,收集所有MessageProcessService */ private boolean detectAllMessageProcessServices = true; private ApplicationContext applicationContext; @Override public MessageProcessServiceResolver getObject() throws Exception { return messageProcessServiceResolver; } @Override public Class<?> getObjectType() { return MessageProcessServiceResolver.class; } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { // Assert.notEmpty(this.messageProcessServices); // Assert.notNull(this.defaultMessageProcessService); if (this.detectAllMessageProcessServices) { // 自动收集 Map<String, MessageProcessService> matchingBeans = this.applicationContext.getBeansOfType(MessageProcessService.class); this.messageProcessServices = new ArrayList<MessageProcessService>(matchingBeans.values()); } Assert.notEmpty(this.messageProcessServices, "messageProcessServices can not be empty."); // 排序,需要用@Order AnnotationAwareOrderComparator.sort(this.messageProcessServices); DefaultMessageProcessServiceResolver messageProcessServiceResolver = new DefaultMessageProcessServiceResolver(); messageProcessServiceResolver.setMessageProcessServices(this.messageProcessServices); messageProcessServiceResolver.setDefaultMessageProcessService(this.defaultMessageProcessService); this.messageProcessServiceResolver = messageProcessServiceResolver; if (log.isInfoEnabled()) { log.info("init MessageProcessServiceResolver, messageProcessServices=" + messageProcessServices); } } public List<MessageProcessService> getMessageProcessServices() { return messageProcessServices; } public void setMessageProcessServices(List<MessageProcessService> messageProcessServices) { this.messageProcessServices = messageProcessServices; } public MessageProcessService<Message> getDefaultMessageProcessService() { return defaultMessageProcessService; } public void setDefaultMessageProcessService(MessageProcessService<Message> defaultMessageProcessService) { this.defaultMessageProcessService = defaultMessageProcessService; } public boolean isDetectAllMessageProcessServices() { return detectAllMessageProcessServices; } public void setDetectAllMessageProcessServices(boolean detectAllMessageProcessServices) { this.detectAllMessageProcessServices = detectAllMessageProcessServices; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
[ "zheng19851@126.com" ]
zheng19851@126.com
1086db122d4a65878919144785aee3bed4381390
3dbff7d18dfe420ad3b3fa548038be31ed538092
/src/main/java/com/employeedetails/employeeServiceDAOImpl/EmployeeListExtractor.java
3335b2fa4c2d1b6b3257569e3c4323a6a3c6d2d4
[]
no_license
santosh3702/employeeDetails
8b25cb720d60eba2736d2128eb1aa035ff62b071
440e76a1493a134295cb8f3f6afc17b7a803bd04
refs/heads/master
2021-01-21T13:21:18.581462
2016-04-22T15:23:51
2016-04-22T15:23:51
55,942,722
0
0
null
null
null
null
UTF-8
Java
false
false
965
java
package com.employeedetails.employeeServiceDAOImpl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ResultSetExtractor; import com.employeedetails.user.Employee; public class EmployeeListExtractor implements ResultSetExtractor<List<Employee>> { @Override public List<Employee> extractData(ResultSet rs) throws SQLException, DataAccessException { List<Employee> listMarketCouch = new ArrayList<Employee>(); while (rs.next()) { Employee employee = new Employee(); employee.setEmployeeId(rs.getString("employeeid")); employee.setDesignation(rs.getString("designation")); employee.setFirstName(rs.getString("firstname")); employee.setLastName(rs.getString("lastname")); employee.setMobileNo(rs.getString("mobileno")); listMarketCouch.add(employee); } return listMarketCouch; } }
[ "stripathi1@xavient.com" ]
stripathi1@xavient.com
5ca1f49645c420fbec1739c798fe68e46523a1f0
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/11/11_d90c4b024d2aff68a914bd93df157ee23410bb2e/IBPELModuleFacetConstants/11_d90c4b024d2aff68a914bd93df157ee23410bb2e_IBPELModuleFacetConstants_s.java
5f63b61f511451f38d02c7ebe7f172f999b2c3ce
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
1,450
java
/******************************************************************************* * Copyright (c) 2006 University College London Software Systems Engineering * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bruno Wassermann - initial API and implementation *******************************************************************************/ package org.eclipse.bpel.runtimes; /** * * * @author Bruno Wassermann, written Jun 29, 2006 */ public interface IBPELModuleFacetConstants { // module types public final static String BPEL20_MODULE_TYPE = "bpel.module"; //$NON-NLS-1$ // module type versions public final static String BPEL11_MODULE_VERSION = "1.1"; // $NON-NLS-1$ public final static String BPEL20_MODULE_VERSION = "2.0"; // $NON-NLS-1$ // facet template public final static String BPEL20_FACET_TEMPLATE = "template.bpel.core"; //$NON-NLS-1$ // facet public final static String BPEL20_PROJECT_FACET = "bpel.facet.core"; //$NON-NLS-1$ // bpel file extension public final static String BPEL_FILE_EXTENSION = "bpel"; //$NON-NLS-1$ public final static String DOT_BPEL_FILE_EXTENSION = "." + BPEL_FILE_EXTENSION; //$NON-NLS-1$ }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
75759a88c37148d3fae44230b1ad351dc1f90d80
218e0bb8172f0d8be5e704127010360441384f09
/app/src/main/java/com/sn/frenrollment2/MainActivity.java
fe4edbb84a07773570e9ff8279109c5a353c6e38
[]
no_license
amanmahajan2190/HackathonUI
5ebd72053e50786f7f5b610a28b75df285d6408a
fe1014088615dcee87ce66279f616a6a737d6393
refs/heads/master
2021-06-07T20:21:33.682340
2016-12-01T16:13:40
2016-12-01T16:13:40
73,572,787
0
0
null
null
null
null
UTF-8
Java
false
false
11,074
java
package com.sn.frenrollment2; import android.Manifest; import android.annotation.TargetApi; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient; import org.apache.http.HttpEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.json.JSONException; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; import javax.net.ssl.HttpsURLConnection; public class MainActivity extends AppCompatActivity { static final int REQUEST_IMAGE_CAPTURE = 1; static final int REQUEST_TAKE_PHOTO = 1; ImageView mImageView; ImageView takePhoto; String pictureImagePath = ""; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = timeStamp + ".jpg"; File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName; File file = new File(pictureImagePath); Uri outputFileUri = Uri.fromFile(file); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); } } @Override @TargetApi(Build.VERSION_CODES.M) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView = (ImageView) findViewById(R.id.imgUserPhoto); takePhoto =(ImageView) findViewById(R.id.imageTakePhoto); takePhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (shouldShowRequestPermissionRationale( Manifest.permission.READ_EXTERNAL_STORAGE)) { // Explain to the user why we need to read the contacts Log.d("Some problem", "Need usage Accesss"); } requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an // app-defined int constant return; } // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ public Action getIndexApiAction() { Thing object = new Thing.Builder() .setName("Main Page") // TODO: Define a title for the content shown. // TODO: Make sure this auto-generated URL is correct. .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) .build(); return new Action.Builder(Action.TYPE_VIEW) .setObject(object) .setActionStatus(Action.STATUS_TYPE_COMPLETED) .build(); } public void grabImage(ImageView imageView) { File imgFile = new File(pictureImagePath); if (imgFile.exists()) { try { Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); Bitmap new_bitmap = getResizedBitmap(myBitmap, 480, 360); mImageView.setImageBitmap(myBitmap); String image = getBase64Encode(new_bitmap); JSONObject object = new JSONObject(); try { object.put("FileName", "Face.jpg"); object.put("FileData", image); } catch (JSONException e) { e.printStackTrace(); } new SendPostReqAsyncTask(object).execute(); // new SendPostImageReqAsyncTask(pictureImagePath).execute(); } catch (Exception ex) { ex.printStackTrace(); } } } private String getBase64Encode(Bitmap bitmap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); return Base64.encodeToString(byteArray, Base64.DEFAULT); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE /*&& resultCode == RESULT_OK*/) { //... some code to inflate/create/find appropriate ImageView to place grabbed image this.grabImage(mImageView); } } class SendPostReqAsyncTask extends AsyncTask<JSONObject, Void, String> { JSONObject object; String response = ""; private SendPostReqAsyncTask(JSONObject o) { this.object = o; } @Override protected String doInBackground(JSONObject... jsonObjects) { URL url = null; try { url = new URL("http://visageapp.azurewebsites.net/api/image"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(object.toString().length()); // conn.setRequestProperty("content-length",object.g; conn.setRequestProperty("content-type", "application/json"); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(object.toString()); writer.flush(); writer.close(); os.close(); if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; Log.e("Some", response); } JSONObject object = new JSONObject(response); JSONObject value_object = object.getJSONObject("Data"); boolean isIDentical = value_object.getBoolean("isIdentical"); double confidence = value_object.getDouble("confidence"); NumberFormat formatter = new DecimalFormat("#0.00"); confidence =confidence*100; String confidence_val = formatter.format(confidence); String user = value_object.getString("userName"); Intent intent = new Intent(MainActivity.this,ResultActivity.class); intent.putExtra("IsIdentical",isIDentical); intent.putExtra("UserName",user); intent.putExtra("Confidence",confidence_val); startActivity(intent); } else { response = ""; Log.e("Not getting", response); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return response; } } public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // CREATE A MATRIX FOR THE MANIPULATION Matrix matrix = new Matrix(); // RESIZE THE BIT MAP matrix.postScale(scaleWidth, scaleHeight); // "RECREATE" THE NEW BITMAP Bitmap resizedBitmap = Bitmap.createBitmap( bm, 0, 0, width, height, matrix, false); // bm.recycle(); return resizedBitmap; } }
[ "amanmahajan@vmware.com" ]
amanmahajan@vmware.com