repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
erogenousbeef/BeefCore
src/main/java/erogenousbeef/core/multiblock/rectangular/RectangularMultiblockControllerBase.java
4761
package erogenousbeef.core.multiblock.rectangular; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import erogenousbeef.core.common.CoordTriplet; import erogenousbeef.core.multiblock.MultiblockControllerBase; import erogenousbeef.core.multiblock.MultiblockValidationException; public abstract class RectangularMultiblockControllerBase extends MultiblockControllerBase { protected RectangularMultiblockControllerBase(World world) { super(world); } /** * @return True if the machine is "whole" and should be assembled. False otherwise. */ protected void isMachineWhole() throws MultiblockValidationException { if(connectedParts.size() < getMinimumNumberOfBlocksForAssembledMachine()) { throw new MultiblockValidationException("Machine is too small."); } CoordTriplet maximumCoord = getMaximumCoord(); CoordTriplet minimumCoord = getMinimumCoord(); // Quickly check for exceeded dimensions int deltaX = maximumCoord.x - minimumCoord.x + 1; int deltaY = maximumCoord.y - minimumCoord.y + 1; int deltaZ = maximumCoord.z - minimumCoord.z + 1; int maxX = getMaximumXSize(); int maxY = getMaximumYSize(); int maxZ = getMaximumZSize(); int minX = getMinimumXSize(); int minY = getMinimumYSize(); int minZ = getMinimumZSize(); if(maxX > 0 && deltaX > maxX) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the X dimension", maxX)); } if(maxY > 0 && deltaY > maxY) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Y dimension", maxY)); } if(maxZ > 0 && deltaZ > maxZ) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Z dimension", maxZ)); } if(deltaX < minX) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the X dimension", minX)); } if(deltaY < minY) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Y dimension", minY)); } if(deltaZ < minZ) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Z dimension", minZ)); } // Now we run a simple check on each block within that volume. // Any block deviating = NO DEAL SIR TileEntity te; RectangularMultiblockTileEntityBase part; Class<? extends RectangularMultiblockControllerBase> myClass = this.getClass(); for(int x = minimumCoord.x; x <= maximumCoord.x; x++) { for(int y = minimumCoord.y; y <= maximumCoord.y; y++) { for(int z = minimumCoord.z; z <= maximumCoord.z; z++) { // Okay, figure out what sort of block this should be. te = this.worldObj.getTileEntity(x, y, z); if(te instanceof RectangularMultiblockTileEntityBase) { part = (RectangularMultiblockTileEntityBase)te; // Ensure this part should actually be allowed within a cube of this controller's type if(!myClass.equals(part.getMultiblockControllerType())) { throw new MultiblockValidationException(String.format("Part @ %d, %d, %d is incompatible with machines of type %s", x, y, z, myClass.getSimpleName())); } } else { // This is permitted so that we can incorporate certain non-multiblock parts inside interiors part = null; } // Validate block type against both part-level and material-level validators. int extremes = 0; if(x == minimumCoord.x) { extremes++; } if(y == minimumCoord.y) { extremes++; } if(z == minimumCoord.z) { extremes++; } if(x == maximumCoord.x) { extremes++; } if(y == maximumCoord.y) { extremes++; } if(z == maximumCoord.z) { extremes++; } if(extremes >= 2) { if(part != null) { part.isGoodForFrame(); } else { isBlockGoodForFrame(this.worldObj, x, y, z); } } else if(extremes == 1) { if(y == maximumCoord.y) { if(part != null) { part.isGoodForTop(); } else { isBlockGoodForTop(this.worldObj, x, y, z); } } else if(y == minimumCoord.y) { if(part != null) { part.isGoodForBottom(); } else { isBlockGoodForBottom(this.worldObj, x, y, z); } } else { // Side if(part != null) { part.isGoodForSides(); } else { isBlockGoodForSides(this.worldObj, x, y, z); } } } else { if(part != null) { part.isGoodForInterior(); } else { isBlockGoodForInterior(this.worldObj, x, y, z); } } } } } } }
mit
Azure/azure-sdk-for-java
sdk/datalakestore/azure-resourcemanager-datalakestore/src/main/java/com/azure/resourcemanager/datalakestore/fluent/package-info.java
368
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. /** * Package containing the service clients for DataLakeStoreAccountManagementClient. Creates an Azure Data Lake Store * account management client. */ package com.azure.resourcemanager.datalakestore.fluent;
mit
Azure/azure-sdk-for-java
sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/models/SqlPoolTableColumns.java
2386
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.models; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; /** Resource collection API of SqlPoolTableColumns. */ public interface SqlPoolTableColumns { /** * Gets columns in a given table in a SQL pool. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param sqlPoolName SQL pool name. * @param schemaName The name of the schema. * @param tableName The name of the table. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return columns in a given table in a SQL pool. */ PagedIterable<SqlPoolColumn> listByTableName( String resourceGroupName, String workspaceName, String sqlPoolName, String schemaName, String tableName); /** * Gets columns in a given table in a SQL pool. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param sqlPoolName SQL pool name. * @param schemaName The name of the schema. * @param tableName The name of the table. * @param filter An OData filter expression that filters elements in the collection. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return columns in a given table in a SQL pool. */ PagedIterable<SqlPoolColumn> listByTableName( String resourceGroupName, String workspaceName, String sqlPoolName, String schemaName, String tableName, String filter, Context context); }
mit
fvasquezjatar/fermat-unused
WPD/library/api/fermat-wpd-api/src/main/java/com/bitdubai/fermat_wpd_api/layer/wpd_desktop_module/wallet_manager/exceptions/WalletsListFailedToLoadException.java
1108
package com.bitdubai.fermat_wpd_api.layer.wpd_desktop_module.wallet_manager.exceptions; import com.bitdubai.fermat_api.FermatException; /** * Created by eze on 2015.07.19.. */ public class WalletsListFailedToLoadException extends FermatException { /** * This is the constructor that every inherited FermatException must implement * * @param message the short description of the why this exception happened, there is a public static constant called DEFAULT_MESSAGE that can be used here * @param cause the exception that triggered the throwing of the current exception, if there are no other exceptions to be declared here, the cause should be null * @param context a String that provides the values of the variables that could have affected the exception * @param possibleReason an explicative reason of why we believe this exception was most likely thrown */ public WalletsListFailedToLoadException(String message, Exception cause, String context, String possibleReason) { super(message, cause, context, possibleReason); } }
mit
olivergondza/dumpling
core/src/main/java/com/github/olivergondza/dumpling/query/SingleThreadSetQuery.java
5238
/* * The MIT License * * Copyright (c) 2014 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.olivergondza.dumpling.query; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import javax.annotation.Nonnull; import com.github.olivergondza.dumpling.model.ModelObject.Mode; import com.github.olivergondza.dumpling.model.ProcessRuntime; import com.github.olivergondza.dumpling.model.ProcessThread; import com.github.olivergondza.dumpling.model.ThreadSet; /** * Query single {@link ThreadSet}. * * Run query against a subset of runtime threads passed in using * {@link #query(ThreadSet)}. Query can access whore runtime and all its threads * using <tt>initialSet.getProcessRuntime()</tt>. It is up to query implementation * to decide that an "initial set" mean in its context. * * For instance {@link Deadlocks} detect only those deadlocks where at least * one of initial threads are part of the cycle. * * @author ogondza * @see ThreadSet#query(SingleThreadSetQuery) * @see ProcessRuntime#query(SingleThreadSetQuery) */ public interface SingleThreadSetQuery<ResultType extends SingleThreadSetQuery.Result<?, ?, ?>> { /** * Get typed result of the query. */ public @Nonnull < SetType extends ThreadSet<SetType, RuntimeType, ThreadType>, RuntimeType extends ProcessRuntime<RuntimeType, SetType, ThreadType>, ThreadType extends ProcessThread<ThreadType, SetType, RuntimeType> > ResultType query(@Nonnull SetType initialSet); /** * Query result that filter/arrange threads. * * Data holder to uniformly represent query results in both CLI and #toString * when used from groovy. * * Result consists of 3 parts: * - query result description ({@link #printResult(PrintStream)}), * - involved thread listing (optional), * - query result summary ({@link #printSummary(PrintStream)}). * * @author ogondza * @see SingleThreadSetQuery */ public static abstract class Result< SetType extends ThreadSet<SetType, RuntimeType, ThreadType>, RuntimeType extends ProcessRuntime<RuntimeType, SetType, ThreadType>, ThreadType extends ProcessThread<ThreadType, SetType, RuntimeType> > { /** * Show stack traces of involved threads. */ private final boolean showStackTraces; protected Result(boolean showStackTraces) { this.showStackTraces = showStackTraces; } /** * Print query result. */ protected abstract void printResult(@Nonnull PrintStream out); /** * Threads that are involved in result. * * These threads will be listed if <tt>showStackTraces</tt> equal true. */ protected abstract @Nonnull SetType involvedThreads(); /** * Print optional summary for a query. * * To be overriden when there is any summary to report. */ protected void printSummary(@SuppressWarnings("unused") @Nonnull PrintStream out) {} /** * Exit code to report when run from CLI. * * @return By default it is number of involved threads, implementation can * provide custom value. */ public int exitCode() { final SetType involvedThreads = involvedThreads(); return involvedThreads.size(); } @Override public final String toString() { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); printInto(new PrintStream(buffer)); return buffer.toString(); } /** * Print whole query result into stream. */ protected final void printInto(@Nonnull PrintStream out) { printResult(out); out.printf("%n%n"); final ThreadSet<?, ?, ?> involvedThreads = involvedThreads(); if (showStackTraces && !involvedThreads.isEmpty()) { involvedThreads.toString(out, Mode.HUMAN); out.println(); } printSummary(out); } } }
mit
chrisruffalo/cfb-wallpapers
src/main/java/com/github/chrisruffalo/cfb/wallpapers/web/SchoolPageGenerator.java
2137
package com.github.chrisruffalo.cfb.wallpapers.web; import com.github.chrisruffalo.cfb.wallpapers.model.Division; import com.github.chrisruffalo.cfb.wallpapers.model.OutputTarget; import com.github.chrisruffalo.cfb.wallpapers.model.School; import com.github.chrisruffalo.cfb.wallpapers.util.TemplateCreator; import freemarker.template.Template; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p></p> * */ public class SchoolPageGenerator { private final School school; private final Division division; private final String conference; public SchoolPageGenerator(final Division division, final String conference, final School school) { this.division = division; this.conference = conference; this.school = school; } public void generate(final List<OutputTarget> outputTargets, final Path outputPath) { final Path schoolPath = outputPath.resolve(this.division.getId()).resolve(this.conference).resolve(this.school.getId()).normalize().toAbsolutePath(); if(!Files.isDirectory(schoolPath)) { try { Files.createDirectories(schoolPath); } catch (Exception e) { throw new RuntimeException(e); } } final Path htmlPath = schoolPath.resolve(this.school.getId() + ".html"); // create datamodel final Map<String, Object> model = new HashMap<>(); model.put("division", this.division); model.put("conference", this.conference); model.put("school", this.school); model.put("targets", outputTargets); model.put("outputPath", outputPath); // write template out try (final Writer writer = new OutputStreamWriter(Files.newOutputStream(htmlPath))){ final Template template = TemplateCreator.getTemplate("web/school.html.template"); template.process(model, writer); } catch (Exception e) { throw new RuntimeException(e); } } }
mit
nico01f/z-pec
ZimbraServer/src/java/com/zimbra/cs/datasource/imap/LocalFolder.java
6936
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.datasource.imap; import java.util.HashSet; import java.util.Set; import com.zimbra.common.service.ServiceException; import com.zimbra.common.util.Log; import com.zimbra.common.util.ZimbraLog; import com.zimbra.cs.mailbox.Flag; import com.zimbra.cs.mailbox.Folder; import com.zimbra.cs.mailbox.MailItem; import com.zimbra.cs.mailbox.MailServiceException; import com.zimbra.cs.mailbox.Mailbox; import com.zimbra.cs.mailbox.Message; import com.zimbra.cs.mailclient.imap.Flags; import com.zimbra.cs.mailclient.imap.ListData; final class LocalFolder { private final Mailbox mbox; private final String path; private Folder folder; private static final Log LOG = ZimbraLog.datasource; public static LocalFolder fromId(Mailbox mbox, int id) throws ServiceException { try { return new LocalFolder(mbox, mbox.getFolderById(null, id)); } catch (MailServiceException.NoSuchItemException e) { return null; } } public static LocalFolder fromPath(Mailbox mbox, String path) throws ServiceException { try { return new LocalFolder(mbox, mbox.getFolderByPath(null, path)); } catch (MailServiceException.NoSuchItemException e) { return null; } } LocalFolder(Mailbox mbox, String path) { this.mbox = mbox; this.path = path; } LocalFolder(Mailbox mbox, Folder folder) { this.mbox = mbox; this.path = folder.getPath(); this.folder = folder; } public void delete() throws ServiceException { debug("deleting folder"); try { getFolder(); } catch (MailServiceException.NoSuchItemException e) { return; } mbox.delete(null, folder.getId(), folder.getType()); } public void create() throws ServiceException { debug("creating folder"); folder = mbox.createFolder(null, path, new Folder.FolderOptions().setDefaultView(MailItem.Type.MESSAGE)); } public void updateFlags(ListData ld) throws ServiceException { getFolder(); if (folder.getId() < 256) return; // Ignore system folder // debug("Updating flags (remote = %s)", ld.getMailbox()); Flags flags = ld.getFlags(); boolean noinferiors = flags.isNoinferiors() || ld.getDelimiter() == 0; int bits = folder.getFlagBitmask(); if (((bits & Flag.BITMASK_NO_INFERIORS) != 0) != noinferiors) { debug("Setting NO_INFERIORS flag to " + noinferiors); alterTag(Flag.FlagInfo.NO_INFERIORS, noinferiors); } boolean sync = !flags.isNoselect(); if (((bits & Flag.BITMASK_SYNCFOLDER) != 0) != sync) { debug("Setting sync flag to " + sync); alterTag(Flag.FlagInfo.SYNCFOLDER, sync); alterTag(Flag.FlagInfo.SYNC, sync); } if (folder.getDefaultView() != MailItem.Type.MESSAGE) { debug("Setting default view to TYPE_MESSAGE"); mbox.setFolderDefaultView(null, folder.getId(), MailItem.Type.MESSAGE); } } public void alterTag(Flag.FlagInfo finfo, boolean value) throws ServiceException { mbox.alterTag(null, getFolder().getId(), MailItem.Type.FOLDER, finfo, value, null); } public void setMessageFlags(int id, int flagMask) throws ServiceException { mbox.setTags(null, id, MailItem.Type.MESSAGE, flagMask, MailItem.TAG_UNCHANGED); } public boolean exists() throws ServiceException { try { getFolder(); } catch (MailServiceException.NoSuchItemException e) { return false; } return true; } public Message getMessage(int id) throws ServiceException { try { Message msg = mbox.getMessageById(null, id); if (msg.getFolderId() == getFolder().getId()) { return msg; } } catch (MailServiceException.NoSuchItemException e) { } return null; } public void deleteMessage(int id) throws ServiceException { debug("deleting message with id %d", id); try { mbox.delete(null, id, MailItem.Type.UNKNOWN); } catch (MailServiceException.NoSuchItemException e) { debug("message with id %d not found", id); } } public void emptyFolder() throws ServiceException { mbox.emptyFolder(null, getId(), false); } public Set<Integer> getMessageIds() throws ServiceException { return new HashSet<Integer>(mbox.listItemIds(null, MailItem.Type.MESSAGE, folder.getId())); } public Folder getFolder() throws ServiceException { if (folder == null) { folder = mbox.getFolderByPath(null, path); } return folder; } public int getId() throws ServiceException { return getFolder().getId(); } public boolean isInbox() throws ServiceException { return getFolder().getId() == Mailbox.ID_FOLDER_INBOX; } public String getPath() { return folder != null ? folder.getPath() : path; } /* * Returns true if this is one of the known IMAP system folders * (e.g. INBOX, Sent). In this case, if we encounter a remote folder * with the same name then we will not map it to a unique local * folder name. */ public boolean isKnown() { switch (folder.getId()) { case Mailbox.ID_FOLDER_INBOX: case Mailbox.ID_FOLDER_TRASH: case Mailbox.ID_FOLDER_SPAM: case Mailbox.ID_FOLDER_SENT: case Mailbox.ID_FOLDER_DRAFTS: return true; default: return false; } } public boolean isSystem() { return folder.getId() < Mailbox.FIRST_USER_ID; } public void debug(String fmt, Object... args) { if (LOG.isDebugEnabled()) { LOG.debug(errmsg(String.format(fmt, args))); } } public void info(String fmt, Object... args) { LOG.info(errmsg(String.format(fmt, args))); } public void warn(String msg, Throwable e) { LOG.error(errmsg(msg), e); } public void error(String msg, Throwable e) { LOG.error(errmsg(msg), e); } private String errmsg(String s) { return String.format("Local folder '%s': %s", getPath(), s); } }
mit
ciddan/Injector
src/test/java/test/com/communalizer/inject/InjectContainerRegistrationFixture.java
3942
package test.com.communalizer.inject; import com.communalizer.inject.Container; import com.communalizer.inject.InjectContainer; import com.communalizer.inject.kernel.Component; import com.communalizer.inject.kernel.Registration; import com.communalizer.inject.kernel.TypeProvider; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.communalizer.inject.kernel.RegistrationBuilder.registration; import static org.fest.assertions.Assertions.assertThat; public class InjectContainerRegistrationFixture { @Test public void Register_Component_AddsItToRegistry() { // Arrange Container container = getNewInjectContainer(); // Act container.register( registration() .component(new Component<Object, String>() {}) .build() ); // Assert assertThat(container.getRegistry()).isNotNull(); assertThat(container.getRegistry()).isNotEmpty(); } @Test public void Register_Component_AddsItToRegistryWithExpectedKey() { // Arrange String expectedKey = "java.util.List<java.lang.String>"; Container container = getNewInjectContainer(); // Act container.register( registration() .component(new Component<List<String>, ArrayList<String>>() {}) .build() ); // Assert final TypeProvider actual = container.getRegistry().get(expectedKey); assertThat(actual).isNotNull(); } @Test public void Register_NamedComponent_AddsItToRegistryWithExpectedKey() { // Arrange String expectedContainerKey = "java.util.List<java.lang.String>"; String expectedProviderKey = "java.util.List<java.lang.String>-Foo"; Container container = getNewInjectContainer(); // Act Registration r = registration() .component(new Component<List<String>, ArrayList<String>>() {}) .named("Foo") .build(); container.register(r); // Assert TypeProvider<?> provider = container.getRegistry().get(expectedContainerKey); assertThat(provider).isNotNull(); assertThat(provider.getRegistry().size()).isEqualTo(1); assertThat(provider.getRegistry().containsKey(expectedProviderKey)); } @Test(expectedExceptions = RuntimeException.class) public void Register_MultipleComponentsOfSameBaseTypeWithoutNames_Throws() { // Arrange Container container = getNewInjectContainer(); // Act container.register( registration() .component(new Component<Object, String>() {}) .build(), registration() .component(new Component<Object, Integer>() {}) .build() ); } @Test(expectedExceptions = RuntimeException.class) public void Register_MultipleComponentsOfSameBaseAndReferencedTypeWithoutName_Throws() { // Arrange Container container = getNewInjectContainer(); // Act container.register( registration() .component(new Component<Object, String>() {}) .build(), registration() .component(new Component<Object, String>() {}) .build() ); } @Test public void Register_MultipleComponentsOfSameBaseAndReferencedTypeWithDifferingNames_RetainsBothInRegistry() { // Arrange Container container = getNewInjectContainer(); // Act container.<Object>register( registration() .component(new Component<Object, String>() {}) .named("foo") .build(), registration() .component(new Component<Object, String>() {}) .build() ); // Assert Map<String, TypeProvider<?>> containerRegistry = container.getRegistry(); assertThat(containerRegistry.size()).isEqualTo(1); TypeProvider<?> provider = containerRegistry.entrySet().iterator().next().getValue(); assertThat(provider.getRegistry().size()).isEqualTo(2); } private static Container getNewInjectContainer() { return new InjectContainer(); } }
mit
shimohq/react-native-keyboard-view
android/src/main/java/im/shimo/react/keyboard/KeyboardView.java
29437
package im.shimo.react.keyboard; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import androidx.annotation.Nullable; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.webkit.WebView; import android.widget.EditText; import android.widget.PopupWindow; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.ReactShadowNode; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.facebook.yoga.YogaEdge; import com.facebook.yoga.YogaPositionType; import java.util.ArrayList; /** * ContentView is layout to cover the keyboard, * CoverView is layout to fill the rest part on the screen. * <p> * +--------------+ * | | * | | * | cover | * | view | * | | * | | * |--------------| * | (keyboard) | * | content | * | view | * | | * +--------------+ */ public class KeyboardView extends ReactRootAwareViewGroup implements LifecycleEventListener, AdjustResizeWithFullScreen.OnKeyboardStatusListener { private final static String TAG = "KeyboardView"; private final ThemedReactContext mThemedContext; private final UIManagerModule mNativeModule; private @Nullable volatile KeyboardCoverView mCoverView; private @Nullable volatile KeyboardContentView mContentView; private int navigationBarHeight; private int statusBarHeight; private RCTEventEmitter mEventEmitter; private int mKeyboardPlaceholderHeight; private float mScale = DisplayMetricsHolder.getScreenDisplayMetrics().density; private boolean mContentVisible = true; private boolean mHideWhenKeyboardIsDismissed = true; private volatile int mChildCount; /** * 光标焦点 */ private View mEditFocusView; /** * 是否为初始化 */ private volatile boolean initWhenAttached; private PopupWindow mContentViewPopupWindow; private int mMinContentViewHeight = 256; private boolean mKeyboardShownStatus; private int mUseBottom; private int mUseRight; private ValueAnimator translationSlide; // whether keyboard is shown private boolean mKeyboardShown = false; private volatile int mVisibility = -1; private int mOrientation = -1; private boolean isOrientationChange; public enum Events { EVENT_SHOW("onKeyboardShow"), EVENT_HIDE("onKeyboardHide"); private final String mName; Events(final String name) { mName = name; } @Override public String toString() { return mName; } } public KeyboardView(final ThemedReactContext context, int navigationBarHeight, int statusBarHeight) { super(context); this.mThemedContext = context; this.mNativeModule = mThemedContext.getNativeModule(UIManagerModule.class); this.navigationBarHeight = navigationBarHeight; this.statusBarHeight = statusBarHeight; mEventEmitter = context.getJSModule(RCTEventEmitter.class); context.addLifecycleEventListener(this); mContentViewPopupWindow = new PopupWindow(); mContentViewPopupWindow.setAnimationStyle(R.style.DialogAnimationSlide); mContentViewPopupWindow.setClippingEnabled(false); mContentViewPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT); mContentViewPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); mContentViewPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { mContentViewPopupWindow.setAttachedInDecor(true); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) { //点击PopupWindow最外层布局以及点击返回键PopupWindow不会消失 mContentViewPopupWindow.setBackgroundDrawable(null); } else { mContentViewPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } } @Override public void addView(View child, int index) { final ViewGroup view = getReactRootView(); if (view == null) { if (child instanceof KeyboardCoverView) { mCoverView = (KeyboardCoverView) child; } else if (child instanceof KeyboardContentView) { mContentView = (KeyboardContentView) child; } initWhenAttached = true; } else { if (child instanceof KeyboardCoverView) { if (mCoverView != null) { removeView(mCoverView); } mCoverView = (KeyboardCoverView) child; view.addView(mCoverView); mChildCount++; } else if (child instanceof KeyboardContentView) { if (mContentView != null) { removeView(mContentView); } mContentView = (KeyboardContentView) child; mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } } if (KeyboardViewManager.DEBUG) { Log.e(TAG, "child = [" + child + "], index = [" + index + "]" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onAttachedToWindow,mOrientation=" + mOrientation); } if (mOrientation == -1) { mOrientation = getResources().getConfiguration().orientation; } AdjustResizeWithFullScreen.assistRegisterActivity(mThemedContext.getCurrentActivity(), statusBarHeight, navigationBarHeight, this); if (initWhenAttached) { initWhenAttached = false; final ViewGroup view = getReactRootView(); if (mCoverView != null) { if (mHideWhenKeyboardIsDismissed || (mContentView != null && mContentView.isShown())) { mCoverView.setVisibility(GONE); } else { keepCoverViewOnScreenFrom(AdjustResizeWithFullScreen.getUseBottom(), 0); mCoverView.setVisibility(VISIBLE); } view.addView(mCoverView); mChildCount++; } if (mContentView != null) { mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } } } public void setHideWhenKeyboardIsDismissed(boolean hideWhenKeyboardIsDismissed) { mHideWhenKeyboardIsDismissed = hideWhenKeyboardIsDismissed; } public void setKeyboardPlaceholderHeight(int keyboardPlaceholderHeight) { if (AdjustResizeWithFullScreen.getKeyboardHeight() == 0) { mKeyboardPlaceholderHeight = (int) (keyboardPlaceholderHeight * mScale); } if (mContentView != null && mCoverView != null) { if (keyboardPlaceholderHeight > 0 && !mKeyboardShown) { //显露面板,并发送事件 final int height = AdjustResizeWithFullScreen.getKeyboardHeight(); final int useBottom = mCoverView.getBottom(); if (height != 0) { keepCoverViewOnScreenFrom(useBottom - height, height); } else { keepCoverViewOnScreenFrom(useBottom - mKeyboardPlaceholderHeight, mKeyboardPlaceholderHeight); } receiveEvent(Events.EVENT_SHOW); } } else if (mCoverView != null && !mContentVisible && !mHideWhenKeyboardIsDismissed && keyboardPlaceholderHeight == 0) { keepCoverViewOnScreenFrom(AdjustResizeWithFullScreen.getUseBottom(), 0); mCoverView.setVisibility(VISIBLE); } } public void setContentVisible(boolean contentVisible) { mContentVisible = contentVisible; if (contentVisible) { if (mCoverView == null) return; mCoverView.setVisibility(VISIBLE); keepCoverViewOnScreenFrom(mPreCoverHeight, mPreCoverBottom); } else { if (mEditFocusView != null) { if (mEditFocusView.isFocused()) { if (!mKeyboardShown) { if (mCoverView != null) { mCoverView.setVisibility(GONE); //设置到屏幕外 keepCoverViewOnScreenFrom(mPreCoverHeight, AdjustResizeWithFullScreen.getUseBottom()); if (mContentView != null) { //删除 removeContentView(); } } } } else { mKeyboardShown = true; onKeyboardClosed(); } } else { if (!mKeyboardShown) { if (mCoverView != null) { mCoverView.setVisibility(GONE); //设置到屏幕外 keepCoverViewOnScreenFrom(mPreCoverHeight, AdjustResizeWithFullScreen.getUseBottom()); if (mContentView != null) { //删除 removeContentView(); } } } } } } @Override public void onKeyboardOpened() { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardOpened" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardShown=" + mKeyboardShown + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } if (mKeyboardShown) return; mKeyboardShown = true; if (mEditFocusView == null) { View view = mThemedContext.getCurrentActivity().getWindow().getDecorView().findFocus(); if (view instanceof EditText || view instanceof WebView) { mEditFocusView = view; } } if (mContentView != null && mContentView.isShown()) { receiveEvent(Events.EVENT_HIDE); } if (mCoverView != null) { mCoverView.setVisibility(VISIBLE); receiveEvent(Events.EVENT_SHOW); } } @Override public void onKeyboardClosed() { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardClosed" + ",mHideWhenKeyboardIsDismissed=" + mHideWhenKeyboardIsDismissed + ",mContentVisible=" + mContentVisible + ",mKeyboardShown=" + mKeyboardShown + ",mKeyboardPlaceholderHeight=" + mKeyboardPlaceholderHeight ); } if (!mKeyboardShown) return; mKeyboardShown = false; if (mContentView != null) { if (mContentVisible) { } else { if (mKeyboardPlaceholderHeight == 0) { receiveEvent(Events.EVENT_HIDE); } } } else { receiveEvent(Events.EVENT_HIDE); } if (mCoverView != null) { if (mEditFocusView != null && mEditFocusView.isFocused()) { if (mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(GONE); mContentViewPopupWindow.dismiss(); } else { if (mContentView == null) { if (mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(GONE); } else { mCoverView.setVisibility(VISIBLE); } } else { mCoverView.setVisibility(VISIBLE); } } } else { if (!mHideWhenKeyboardIsDismissed) { mCoverView.setVisibility(VISIBLE); } else { mCoverView.setVisibility(GONE); } } } } @Override public boolean onKeyboardResize(int heightOfLayout, int bottom) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onKeyboardResize,heightOfLayout=" + heightOfLayout); Log.e(TAG, "onKeyboardResize,mCoverView.isShown()=" + mCoverView.isShown()); } if (mCoverView != null && AdjustResizeWithFullScreen.isInit()) { if (mCoverView.isShown()) { int diff = AdjustResizeWithFullScreen.getWindowBottom() - heightOfLayout; if (mContentVisible && diff <= navigationBarHeight + statusBarHeight) { int coverViewBottom = mCoverView.getBottom(); if (!AdjustResizeWithFullScreen.isFullscreen() && coverViewBottom + AdjustResizeWithFullScreen.getKeyboardHeight() == AdjustResizeWithFullScreen.getWindowBottom()) { coverViewBottom -= diff; } keepCoverViewOnScreenFrom(coverViewBottom, bottom); return true; } else { keepCoverViewOnScreenFrom(heightOfLayout, bottom); return true; } } if (mKeyboardShown) { keepCoverViewOnScreenFrom(heightOfLayout, bottom); } } return true; } @Override public void addChildrenForAccessibility(ArrayList<View> outChildren) { // Explicitly override this to prevent accessibility events being passed down to children // Those will be handled by the mHostView which lives in the PopupWindow } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // Explicitly override this to prevent accessibility events being passed down to children // Those will be handled by the mHostView which lives in the PopupWindow return false; } @Override public void onHostResume() { } @Override public void onHostPause() { } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (mVisibility != visibility) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "onWindowVisibilityChanged,mVisibility=" + mVisibility + ",visibility=" + visibility + ",mUseBottom=" + mUseBottom + ",mKeyboardShownStatus=" + mKeyboardShownStatus); } if (visibility == VISIBLE) { if (mUseBottom == 0 && !mKeyboardShownStatus) { //没有变化,无需进入逻辑 return; } int orientation = getResources().getConfiguration().orientation; final boolean isOchanged = isOrientationChange = mOrientation != orientation; if (isOchanged) { mOrientation = orientation; mKeyboardShownStatus = false; mVisibility = visibility; return; } if (mKeyboardShownStatus) { mKeyboardShownStatus = false; if (mEditFocusView != null) { mEditFocusView.setFocusable(true); mEditFocusView.requestFocus(); } } else { if (mCoverView == null || !mCoverView.isShown() || mPreCoverHeight == 0) { mVisibility = visibility; return; } int diff = mUseBottom - AdjustResizeWithFullScreen.getUseBottom(); int diffR = mUseRight - getRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); boolean isChanged = diff != 0 || diffR != 0 || isOchanged; if (isChanged) { keepCoverViewOnScreenFrom(mPreCoverHeight - diff, 0); } else { keepCoverViewOnScreenFrom(mPreCoverHeight, 0); } } mVisibility = visibility; } else if (visibility == GONE) { if (mEditFocusView != null && (KeyboardUtil.isKeyboardActive(mEditFocusView)) || mKeyboardShown) { mKeyboardShownStatus = true; } else { if (mCoverView != null) { mUseBottom = AdjustResizeWithFullScreen.getUseBottom(); mUseRight = getRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); } } mVisibility = visibility; } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); receiveEvent(Events.EVENT_HIDE); onDropInstance(); } @Override public void onHostDestroy() { ((ReactContext) getContext()).removeLifecycleEventListener(this); onDropInstance(); } public void onDropInstance() { if (mCoverView != null) { removeView(mCoverView); } if (mContentView != null) { removeView(mContentView); } AdjustResizeWithFullScreen.assistUnRegister(); // mContentView = null; // mCoverView = null; mEditFocusView = null; // mContentViewPopupWindow.dismiss(); mContentViewPopupWindow.setContentView(null); mVisibility = -1; mKeyboardShown = mKeyboardShownStatus = false; mOrientation = -1; mContentVisible = false; mKeyboardPlaceholderHeight = 0; if (translationSlide != null) { translationSlide = null; } } @Override public void removeView(final View child) { if (child == null) return; ViewParent viewParent = child.getParent(); if (viewParent != null) { if (KeyboardViewManager.DEBUG) { Log.e(TAG, "removeView,child=" + child); } if (child.equals(mCoverView)) { removeCoverView(child, (ViewGroup) viewParent); } else { removeContentView(); } child.setVisibility(GONE); } } private void removeCoverView(View child, ViewGroup viewParent) { mCoverView = null; viewParent.removeView(child); mChildCount--; if (!mContentVisible) { receiveEvent(Events.EVENT_HIDE); } mPreCoverBottom = mPreCoverHeight = mPreCoverWidth = 0; } private void removeContentView() { mContentViewPopupWindow.dismiss(); ViewGroup parent = (ViewGroup) mContentView.getParent(); if (parent != null) { parent.removeView(mContentView); } mContentView = null; receiveEvent(Events.EVENT_HIDE); mPreContentWidth = mPreContentHeight = mPreContentTop = 0; } @Override public void removeViewAt(int index) { if (index == 0 && mContentView != null) { removeView(mContentView); } else { removeView(mCoverView); } } @Override public int getChildCount() { return mChildCount; } @Override public View getChildAt(int index) { if (index == 0 && mContentView != null) { return mContentView; } else { return mCoverView; } } private void receiveEvent(Events event) { WritableMap map = Arguments.createMap(); map.putBoolean("keyboardShown", mKeyboardShown); mEventEmitter.receiveEvent(getId(), event.toString(), map); } //防止多次重绘界面 private int mPreCoverHeight = 0; private int mPreCoverBottom = 0; private int mPreCoverWidth = 0; /** * 确定CoverView的位置,以及随着coverView变化而变化的contentView的位置 */ private void keepCoverViewOnScreenFrom(final int height, final int bottom) { if (mCoverView != null) { ((ReactContext) getContext()).runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { final int useRight = getReactRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); //maybe its null in this thread if (!isOrientationChange && mPreCoverBottom == bottom && mPreCoverHeight == height && mPreCoverWidth == useRight || mCoverView == null) { postContentView(); return; } if (KeyboardViewManager.DEBUG) { Log.e(TAG, "keepCoverViewOnScreenFrom,height" + height + ",bottom=" + bottom + ",useRight=" + useRight); } mPreCoverBottom = bottom; mPreCoverHeight = height; mPreCoverWidth = useRight; try { ReactShadowNode coverShadowNode = mNativeModule.getUIImplementation().resolveShadowNode(mCoverView.getId()); if (bottom >= 0) { coverShadowNode.setPosition(YogaEdge.BOTTOM.intValue(), bottom); } coverShadowNode.setPosition(YogaEdge.TOP.intValue(), 0); coverShadowNode.setPositionType(YogaPositionType.ABSOLUTE); if (height > -1) { coverShadowNode.setStyleHeight(height); mNativeModule.updateNodeSize(mCoverView.getId(), useRight, height); } mNativeModule.getUIImplementation().dispatchViewUpdates(-1);//这句话相当于全局更新 postContentView(); } catch (Exception e) { e.printStackTrace(); } } private void postContentView() { post(new Runnable() { @Override public void run() { if (mContentVisible) { if (height > -1) { keepContentViewOnScreenFrom(height); } else { try { final int coverBottom = mCoverView == null ? -99 : mCoverView.getBottom(); if (coverBottom == -99) return; keepContentViewOnScreenFrom(coverBottom); } catch (Exception e) { //maybe its null in this thread e.printStackTrace(); } } } } }); } }); if (mPreCoverBottom == bottom && mPreCoverHeight == height) { return; } if (translationSlide != null) { if (translationSlide.isRunning() || translationSlide.isStarted()) { translationSlide.cancel(); } } translationSlide = ObjectAnimator.ofFloat(mCoverView, "alpha", 0, 1); translationSlide.start(); } } //防止多次重绘界面 private int mPreContentHeight = 0; private int mPreContentTop = 0; private int mPreContentWidth = 0; /** * 将面板固定在某高度,一般是mCoverView的bottom 或者是屏幕以外 * * @param top */ private void keepContentViewOnScreenFrom(int top) { if (mContentView != null) { if (mContentViewPopupWindow.getContentView() == null) { mContentViewPopupWindow.setContentView(mContentView); mContentViewPopupWindow.setWidth(AdjustResizeWithFullScreen.getUseRight()); } if (mKeyboardShown) { if (top != AdjustResizeWithFullScreen.getUseBottom()) { top = AdjustResizeWithFullScreen.getUseBottom(); } } final int tempHeight = getContentViewHeight(top); final int useRight = getReactRootView().getWidth();//AdjustResizeWithFullScreen.getUseRight(); if (KeyboardViewManager.DEBUG) { Log.e(TAG, "keepContentViewOnScreenFrom,height" + tempHeight + ",top=" + top + ",useRight=" + useRight); } ((ReactContext) getContext()).runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { if (mContentView != null) { //maybe its null in this thread mNativeModule.updateNodeSize(mContentView.getId(), useRight, tempHeight); } } }); if (mContentViewPopupWindow.isShowing()) { boolean isOrientChanged = isOrientationChange; if (!isOrientChanged) { isOrientChanged = mOrientation == getResources().getConfiguration().orientation; } if (!isOrientChanged && mPreContentHeight == tempHeight && mPreContentTop == top && mPreContentWidth == useRight) { return; } if (isOrientChanged) { isOrientationChange = false; mOrientation = getResources().getConfiguration().orientation; } mContentViewPopupWindow.update(AdjustResizeWithFullScreen.getUseLeft(), top, useRight, tempHeight); } else { if (mContentViewPopupWindow.getHeight() != tempHeight) { mContentViewPopupWindow.setHeight(tempHeight); } if (mContentViewPopupWindow.getWidth() != useRight) { mContentViewPopupWindow.setWidth(useRight); } try { final View decorView = AdjustResizeWithFullScreen.getDecorView(); if(decorView!=null) { mContentViewPopupWindow.showAtLocation(decorView, Gravity.NO_GRAVITY, AdjustResizeWithFullScreen.getUseLeft(), top); } } catch (Exception e) { //mybe its non in asynchronization e.printStackTrace(); } } mPreContentHeight = tempHeight; mPreContentTop = top; mPreContentWidth = useRight; } } private int getContentViewHeight(int top) { int realKeyboardHeight = AdjustResizeWithFullScreen.getRemainingHeight(top); int keyboardHeight = AdjustResizeWithFullScreen.getKeyboardHeight(); if (realKeyboardHeight == 0 || realKeyboardHeight < keyboardHeight) { realKeyboardHeight = keyboardHeight; if (realKeyboardHeight == 0) { if (mKeyboardPlaceholderHeight != 0) { realKeyboardHeight = mKeyboardPlaceholderHeight; } else { realKeyboardHeight = mMinContentViewHeight; } } } return realKeyboardHeight; } }
mit
napcs/qedserver
jetty/contrib/cometd/server/src/main/java/org/mortbay/cometd/BayeuxService.java
16404
// ======================================================================== // Copyright 2008 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // 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.mortbay.cometd; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.cometd.Bayeux; import org.cometd.Channel; import org.cometd.Client; import org.cometd.Listener; import org.cometd.Message; import org.cometd.MessageListener; import org.mortbay.component.LifeCycle; import org.mortbay.log.Log; import org.mortbay.thread.QueuedThreadPool; import org.mortbay.thread.ThreadPool; /* ------------------------------------------------------------ */ /** * Abstract Bayeux Service class. This is a base class to assist with the * creation of server side @ link Bayeux} clients that provide services to * remote Bayeux clients. The class provides a Bayeux {@link Client} and * {@link Listener} together with convenience methods to map subscriptions to * methods on the derived class and to send responses to those methods. * * <p> * If a {@link #setThreadPool(ThreadPool)} is set, then messages are handled in * their own threads. This is desirable if the handling of a message can take * considerable time and it is desired not to hold up the delivering thread * (typically a HTTP request handling thread). * * <p> * If the BayeuxService is constructed asynchronously (the default), then * messages are delivered unsynchronized and multiple simultaneous calls to * handling methods may occur. * * <p> * If the BayeuxService is constructed as a synchronous service, then message * delivery is synchronized on the internal {@link Client} instances used and * only a single call will be made to the handler method (unless a thread pool * is used). * * @see MessageListener * @author gregw */ public abstract class BayeuxService { private String _name; private Bayeux _bayeux; private Client _client; private Map<String,Method> _methods=new ConcurrentHashMap<String,Method>(); private ThreadPool _threadPool; private MessageListener _listener; private boolean _seeOwn=false; /* ------------------------------------------------------------ */ /** * Instantiate the service. Typically the derived constructor will call @ * #subscribe(String, String)} to map subscriptions to methods. * * @param bayeux * The bayeux instance. * @param name * The name of the service (used as client ID prefix). */ public BayeuxService(Bayeux bayeux, String name) { this(bayeux,name,0,false); } /* ------------------------------------------------------------ */ /** * Instantiate the service. Typically the derived constructor will call @ * #subscribe(String, String)} to map subscriptions to methods. * * @param bayeux * The bayeux instance. * @param name * The name of the service (used as client ID prefix). * @param maxThreads * The size of a ThreadPool to create to handle messages. */ public BayeuxService(Bayeux bayeux, String name, int maxThreads) { this(bayeux,name,maxThreads,false); } /* ------------------------------------------------------------ */ /** * Instantiate the service. Typically the derived constructor will call @ * #subscribe(String, String)} to map subscriptions to methods. * * @param bayeux * The bayeux instance. * @param name * The name of the service (used as client ID prefix). * @param maxThreads * The size of a ThreadPool to create to handle messages. * @param synchronous * True if message delivery will be synchronized on the client. */ public BayeuxService(Bayeux bayeux, String name, int maxThreads, boolean synchronous) { if (maxThreads > 0) setThreadPool(new QueuedThreadPool(maxThreads)); _name=name; _bayeux=bayeux; _client=_bayeux.newClient(name); _listener=(synchronous)?new SyncListen():new AsyncListen(); _client.addListener(_listener); } /* ------------------------------------------------------------ */ public Bayeux getBayeux() { return _bayeux; } /* ------------------------------------------------------------ */ public Client getClient() { return _client; } /* ------------------------------------------------------------ */ public ThreadPool getThreadPool() { return _threadPool; } /* ------------------------------------------------------------ */ /** * Set the threadpool. If the {@link ThreadPool} is a {@link LifeCycle}, * then it is started by this method. * * @param pool */ public void setThreadPool(ThreadPool pool) { try { if (pool instanceof LifeCycle) if (!((LifeCycle)pool).isStarted()) ((LifeCycle)pool).start(); } catch(Exception e) { throw new IllegalStateException(e); } _threadPool=pool; } /* ------------------------------------------------------------ */ public boolean isSeeOwnPublishes() { return _seeOwn; } /* ------------------------------------------------------------ */ public void setSeeOwnPublishes(boolean own) { _seeOwn=own; } /* ------------------------------------------------------------ */ /** * Subscribe to a channel. Subscribe to channel and map a method to handle * received messages. The method must have a unique name and one of the * following signatures: * <ul> * <li><code>myMethod(Client fromClient,Object data)</code></li> * <li><code>myMethod(Client fromClient,Object data,String id)</code></li> * <li> * <code>myMethod(Client fromClient,String channel,Object data,String id)</code> * </li> * </li> * * The data parameter can be typed if the type of the data object published * by the client is known (typically Map<String,Object>). If the type of the * data parameter is {@link Message} then the message object itself is * passed rather than just the data. * <p> * Typically a service will subscribe to a channel in the "/service/**" * space which is not a broadcast channel. Messages published to these * channels are only delivered to server side clients like this service. * * <p> * Any object returned by a mapped subscription method is delivered to the * calling client and not broadcast. If the method returns void or null, * then no response is sent. A mapped subscription method may also call * {@link #send(Client, String, Object, String)} to deliver a response * message(s) to different clients and/or channels. It may also publish * methods via the normal {@link Bayeux} API. * <p> * * * @param channelId * The channel to subscribe to * @param methodName * The name of the method on this object to call when messages * are recieved. */ protected void subscribe(String channelId, String methodName) { Method method=null; Class<?> c=this.getClass(); while(c != null && c != Object.class) { Method[] methods=c.getDeclaredMethods(); for (int i=methods.length; i-- > 0;) { if (methodName.equals(methods[i].getName())) { if (method != null) throw new IllegalArgumentException("Multiple methods called '" + methodName + "'"); method=methods[i]; } } c=c.getSuperclass(); } if (method == null) throw new NoSuchMethodError(methodName); int params=method.getParameterTypes().length; if (params < 2 || params > 4) throw new IllegalArgumentException("Method '" + methodName + "' does not have 2or3 parameters"); if (!Client.class.isAssignableFrom(method.getParameterTypes()[0])) throw new IllegalArgumentException("Method '" + methodName + "' does not have Client as first parameter"); Channel channel=_bayeux.getChannel(channelId,true); if (((ChannelImpl)channel).getChannelId().isWild()) { final Method m=method; Client wild_client=_bayeux.newClient(_name + "-wild"); wild_client.addListener(_listener instanceof MessageListener.Asynchronous?new AsyncWildListen(wild_client,m):new SyncWildListen(wild_client,m)); channel.subscribe(wild_client); } else { _methods.put(channelId,method); channel.subscribe(_client); } } /* ------------------------------------------------------------ */ /** * Send data to a individual client. The data passed is sent to the client * as the "data" member of a message with the given channel and id. The * message is not published on the channel and is thus not broadcast to all * channel subscribers. However to the target client, the message appears as * if it was broadcast. * <p> * Typcially this method is only required if a service method sends * response(s) to channels other than the subscribed channel. If the * response is to be sent to the subscribed channel, then the data can * simply be returned from the subscription method. * * @param toClient * The target client * @param onChannel * The channel the message is for * @param data * The data of the message * @param id * The id of the message (or null for a random id). */ protected void send(Client toClient, String onChannel, Object data, String id) { toClient.deliver(getClient(),onChannel,data,id); } /* ------------------------------------------------------------ */ /** * Handle Exception. This method is called when a mapped subscription method * throws and exception while handling a message. * * @param fromClient The remote client * @param toClient The client associated with this BayeuxService * @param msg The message * @param th The exception thrown by the mapped subscription method */ protected void exception(Client fromClient, Client toClient, Map<String,Object> msg, Throwable th) { System.err.println(msg); th.printStackTrace(); } /* ------------------------------------------------------------ */ private void invoke(final Method method, final Client fromClient, final Client toClient, final Message msg) { if (_threadPool == null) { doInvoke(method,fromClient,toClient,msg); } else { ((MessageImpl)msg).incRef(); _threadPool.dispatch(new Runnable() { public void run() { asyncDoInvoke(method, fromClient, toClient, msg); } }); } } protected void asyncDoInvoke(Method method, Client fromClient, Client toClient, Message msg) { try { doInvoke(method,fromClient,toClient,msg); } finally { ((MessageImpl)msg).decRef(); } } private void doInvoke(Method method, Client fromClient, Client toClient, Message msg) { String channel=(String)msg.get(Bayeux.CHANNEL_FIELD); Object data=msg.get(Bayeux.DATA_FIELD); String id=msg.getId(); if (method != null) { try { Class<?>[] args=method.getParameterTypes(); Object arg; if (args.length == 4) arg=Message.class.isAssignableFrom(args[2])?msg:data; else arg=Message.class.isAssignableFrom(args[1])?msg:data; Object reply=null; switch(method.getParameterTypes().length) { case 2: reply=method.invoke(this,fromClient,arg); break; case 3: reply=method.invoke(this,fromClient,arg,id); break; case 4: reply=method.invoke(this,fromClient,channel,arg,id); break; } if (reply != null) send(fromClient,channel,reply,id); } catch(Exception e) { Log.debug("method",method); exception(fromClient,toClient,msg,e); } catch(Error e) { Log.debug("method",method); exception(fromClient,toClient,msg,e); } } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class AsyncListen implements MessageListener, MessageListener.Asynchronous { public void deliver(Client fromClient, Client toClient, Message msg) { if (!_seeOwn && fromClient == getClient()) return; String channel=(String)msg.get(Bayeux.CHANNEL_FIELD); Method method=_methods.get(channel); invoke(method,fromClient,toClient,msg); } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class SyncListen implements MessageListener, MessageListener.Synchronous { public void deliver(Client fromClient, Client toClient, Message msg) { if (!_seeOwn && fromClient == getClient()) return; String channel=(String)msg.get(Bayeux.CHANNEL_FIELD); Method method=_methods.get(channel); invoke(method,fromClient,toClient,msg); } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class SyncWildListen implements MessageListener, MessageListener.Synchronous { Client _client; Method _method; public SyncWildListen(Client client, Method method) { _client=client; _method=method; } public void deliver(Client fromClient, Client toClient, Message msg) { if (!_seeOwn && (fromClient == _client || fromClient == getClient())) return; invoke(_method,fromClient,toClient,msg); } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class AsyncWildListen implements MessageListener, MessageListener.Asynchronous { Client _client; Method _method; public AsyncWildListen(Client client, Method method) { _client=client; _method=method; } public void deliver(Client fromClient, Client toClient, Message msg) { if (!_seeOwn && (fromClient == _client || fromClient == getClient())) return; invoke(_method,fromClient,toClient,msg); } } }
mit
awvalenti/corridapatrimonial
src/com/github/awvalenti/corridapatrimonial/servidor/entradasaida/EntradaSaidaServidor.java
1736
package com.github.awvalenti.corridapatrimonial.servidor.entradasaida; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.github.awvalenti.corridapatrimonial.servidor.entradasaida.comandos.ProcessadorComandosCifrados; import com.github.awvalenti.corridapatrimonial.servidor.entradasaida.criptografia.GeradorChaves; import com.github.awvalenti.corridapatrimonial.servidor.entradasaida.mensagens.MensagemJogadorEntrou; import com.github.awvalenti.corridapatrimonial.servidor.entradasaida.mensagens.MensagemResultanteExecucaoComando; import com.github.awvalenti.corridapatrimonial.util.LeitorEscritor; public class EntradaSaidaServidor { private final ProcessadorComandosCifrados processadorComandosCifrados; private final GeradorChaves geradorChaves; public EntradaSaidaServidor(ProcessadorComandosCifrados processadorComandosCifrados, GeradorChaves geradorChaves) { this.processadorComandosCifrados = processadorComandosCifrados; this.geradorChaves = geradorChaves; } public void realizar(String idCliente, InputStream doCliente, OutputStream paraCliente) throws IOException { Integer chaveBuscada = geradorChaves.buscarChave(idCliente); if (chaveBuscada == null) { chaveBuscada = 0; } MensagemResultanteExecucaoComando mensagemResultante = processadorComandosCifrados.processarLinhaComandoCifrada( LeitorEscritor.lerLinha(doCliente), chaveBuscada); // XXX Feio if (mensagemResultante.indicaQueJogadorEntrou()) { Integer chaveGeradaAgora = geradorChaves.gerarChave(idCliente); ((MensagemJogadorEntrou) mensagemResultante).setChaveCriptografica(chaveGeradaAgora); } LeitorEscritor.escreverLinha(paraCliente, mensagemResultante.getTexto()); } }
mit
Cabezudo/JSONLib
src/test/java/net/cabezudo/json/values/JSONValueTest.java
2627
package net.cabezudo.json.values; import net.cabezudo.json.exceptions.JSONConversionException; import org.junit.Test; /** * @author <a href="http://cabezudo.net">Esteban Cabezudo</a> * @version 0.9, 05/09/2017 */ public class JSONValueTest { @Test(expected = JSONConversionException.class) public void testToArray() { JSONValue jsonValue = JSONBoolean.TRUE; jsonValue.toArray(); } @Test(expected = JSONConversionException.class) public void testToBigDecimal() { JSONValue jsonValue = new JSONObject(); jsonValue.toBigDecimal(); } @Test(expected = JSONConversionException.class) public void testToBigInteger() { JSONValue jsonValue = new JSONObject(); jsonValue.toBigInteger(); } @Test(expected = JSONConversionException.class) public void testToBoolean() { JSONValue jsonValue = new JSONObject(); jsonValue.toBoolean(); } @Test(expected = JSONConversionException.class) public void testToByte() { JSONValue jsonValue = new JSONObject(); jsonValue.toByte(); } @Test(expected = JSONConversionException.class) public void testToByteArray() { JSONValue jsonValue = new JSONObject(); jsonValue.toByteArray(); } @Test(expected = JSONConversionException.class) public void testToCalendar() { JSONValue jsonValue = new JSONObject(); jsonValue.toCalendar(); } @Test(expected = JSONConversionException.class) public void testToCharacter() { JSONValue jsonValue = new JSONObject(); jsonValue.toCharacter(); } @Test(expected = JSONConversionException.class) public void testToDouble() { JSONValue jsonValue = new JSONObject(); jsonValue.toDouble(); } @Test(expected = JSONConversionException.class) public void testToFloat() { JSONValue jsonValue = new JSONObject(); jsonValue.toFloat(); } @Test(expected = JSONConversionException.class) public void testToInteger() { JSONValue jsonValue = new JSONObject(); jsonValue.toInteger(); } @Test(expected = JSONConversionException.class) public void testToJSONString() { JSONValue jsonValue = new JSONObject(); jsonValue.toJSONString(); } @Test(expected = JSONConversionException.class) public void testToList() { JSONValue jsonValue = new JSONObject(); jsonValue.toList(); } @Test(expected = JSONConversionException.class) public void testToLong() { JSONValue jsonValue = new JSONObject(); jsonValue.toLong(); } @Test(expected = JSONConversionException.class) public void testToStringArray() { JSONValue jsonValue = new JSONObject(); jsonValue.toStringArray(); } }
mit
DziNeIT/dzlib
src/main/java/pw/ollie/dzlib/stream/BiCollector.java
2489
/* * This file is part of dzlib, licensed under the MIT License (MIT). * * Copyright (c) 2014-2019 Oliver Stanley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pw.ollie.dzlib.stream; import java.util.function.Function; import java.util.stream.Collector; /** * See https://github.com/google/mug/blob/master/core/src/main/java/com/google/mu/util/stream/BiCollector.java * <p> * Logically, a {@code BiCollector} collects "pairs of things", just as a {@link Collector} collects * "things". * <p> * {@code BiCollector} is usually passed to {@link BiStream#collect}. For example, to collect the * input pairs to a {@code ConcurrentMap}: * <pre>{@code * ConcurrentMap<String, Integer> map = BiStream.of("a", 1).collect(Collectors::toConcurrentMap); * }</pre> * <p> * In addition, {@code BiCollector} can be used to directly collect a stream of "pair-wise" data * structures. * * @param <K> the key type * @param <V> the value type * @param <R> the result type */ @FunctionalInterface public interface BiCollector<K, V, R> { /** * Returns a {@code Collector} that will first bisect the input elements using {@code toKey} and * {@code toValue} and subsequently collect the bisected parts through this {@code BiCollector}. * * @param <E> used to abstract away the underlying pair/entry type used by {@link BiStream}. */ <E> Collector<E, ?, R> bisecting(Function<E, K> toKey, Function<E, V> toValue); }
mit
ruseman/csc112
codes/src/Codes.java
1981
import java.util.Scanner; import jsjf.LinkedQueue; import jsjf.QueueADT; /** * Codes.java<br> * Mar 25, 2015 * @author Tim Miller */ public class Codes { /** * Encode and decode a message using a key of values stored in * a queue. */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); String again; do { int[] key; int keysize; Integer keyValue; String encoded = "", decoded = "", message = ""; System.out.println("Please enter a message: "); message = scan.nextLine(); System.out.println("Please enter the length of the key"); keysize = scan.nextInt(); key = new int[keysize]; for (int index = 0; index < keysize; index++) { System.out.println("Please enter key index " + (index + 1) + ": "); key[index] = scan.nextInt(); } System.out.println("\nOriginal Message: \n" + message + "\n"); final QueueADT<Integer> encodingQueue = new LinkedQueue<Integer>(); final QueueADT<Integer> decodingQueue = new LinkedQueue<Integer>(); // load key queues for (final int element : key) { encodingQueue.enqueue(element); decodingQueue.enqueue(element); } // encode message for (int index = 0; index < message.length(); index++) { keyValue = encodingQueue.dequeue(); encoded += (char) (message.charAt(index) + keyValue); encodingQueue.enqueue(keyValue); } System.out.println("Encoded Message:\n" + encoded + "\n"); // decode message for (int index = 0; index < encoded.length(); index++) { keyValue = decodingQueue.dequeue(); decoded += (char) (encoded.charAt(index) - keyValue); decodingQueue.enqueue(keyValue); } System.out.println("Decoded Message:\n" + decoded); scan = new Scanner(System.in); System.out .println("Go again? (Enter 'Y' to run again, enter any other character to exit)"); again = scan.nextLine(); } while (again.equalsIgnoreCase("Y")); scan.close(); } }
mit
spacerovka/jShop
src/main/java/shop/main/data/DAO/OptionGroupDAO.java
988
package shop.main.data.DAO; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import shop.main.data.entity.OptionGroup; public interface OptionGroupDAO extends JpaRepository<OptionGroup, Long> { List<OptionGroup> findAll(); Page<OptionGroup> findByOptionGroupNameContaining(String name, Pageable pageable); Page<OptionGroup> findAll(Pageable pageable); long count(); @Query("SELECT item FROM OptionGroup item where (:name is NULL OR item.optionGroupName LIKE :name) ORDER BY item.id") Page<OptionGroup> findByName(@Param("name") String name, Pageable pageable); @Query("SELECT count(*) FROM OptionGroup item where (:name is NULL OR item.optionGroupName LIKE :name) ORDER BY item.id") long countByName(@Param("name") String name); }
mit
nico01f/z-pec
ZimbraSoap/src/java/com/zimbra/soap/mail/type/ConversationHitInfo.java
2702
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.mail.type; import com.google.common.base.Objects; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import com.zimbra.common.soap.MailConstants; import com.zimbra.soap.type.SearchHit; @XmlAccessorType(XmlAccessType.NONE) public class ConversationHitInfo extends ConversationSummary implements SearchHit { /** * @zm-api-field-tag sort-field * @zm-api-field-description Sort field value */ @XmlAttribute(name=MailConstants.A_SORT_FIELD /* sf */, required=false) private String sortField; /** * @zm-api-field-description Hits */ @XmlElement(name=MailConstants.E_MSG /* m */, required=false) private List<ConversationMsgHitInfo> messageHits = Lists.newArrayList(); public ConversationHitInfo() { this((String) null); } public ConversationHitInfo(String id) { super(id); } public void setSortField(String sortField) { this.sortField = sortField; } public void setMessageHits(Iterable <ConversationMsgHitInfo> messageHits) { this.messageHits.clear(); if (messageHits != null) { Iterables.addAll(this.messageHits,messageHits); } } public ConversationHitInfo addMessageHit(ConversationMsgHitInfo messageHit) { this.messageHits.add(messageHit); return this; } public String getSortField() { return sortField; } public List<ConversationMsgHitInfo> getMessageHits() { return Collections.unmodifiableList(messageHits); } public Objects.ToStringHelper addToStringInfo(Objects.ToStringHelper helper) { helper = super.addToStringInfo(helper); return helper .add("sortField", sortField) .add("messageHits", messageHits); } @Override public String toString() { return addToStringInfo(Objects.toStringHelper(this)).toString(); } }
mit
SpongePowered/Sponge
src/main/java/org/spongepowered/common/profile/SpongeProfileProperty.java
4047
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.profile; import com.mojang.authlib.properties.Property; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.Queries; import org.spongepowered.api.profile.property.ProfileProperty; import java.util.Objects; import java.util.Optional; import java.util.StringJoiner; public final class SpongeProfileProperty implements ProfileProperty { private final String name; private final String value; private final @Nullable String signature; public SpongeProfileProperty(final Property property) { this(property.getName(), property.getValue(), property.getSignature()); } public SpongeProfileProperty(final String name, final String value, final @Nullable String signature) { this.name = name; this.value = value; this.signature = signature; } @Override public int contentVersion() { return 1; } @Override @NonNull public DataContainer toContainer() { final DataContainer container = DataContainer.createNew() .set(Queries.CONTENT_VERSION, this.contentVersion()) .set(Queries.PROPERTY_NAME, this.name) .set(Queries.PROPERTY_VALUE, this.value); if (this.signature != null) { container.set(Queries.PROPERTY_SIGNATURE, this.signature); } return container; } @Override @NonNull public String name() { return this.name; } @Override @NonNull public String value() { return this.value; } @Override @NonNull public Optional<String> signature() { return Optional.ofNullable(this.signature); } public Property asProperty() { return new Property(this.name, this.value, this.signature); } @Override public int hashCode() { return Objects.hash(this.name, this.value, this.signature); } @Override public boolean equals(final Object obj) { if (!(obj instanceof SpongeProfileProperty)) { return false; } final SpongeProfileProperty other = (SpongeProfileProperty) obj; return other.name().equals(this.name) && other.value().equals(this.value) && Objects.equals(other.signature, this.signature); } @Override public String toString() { return new StringJoiner(", ", Property.class.getSimpleName() + "[", "]") .add("name='" + this.name + "'") .add("value='" + this.value + "'") .add("signature='" + this.signature + "'") .toString(); } }
mit
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/traverser/SqlgTraverser.java
3240
package org.umlg.sqlg.structure.traverser; import org.apache.tinkerpop.gremlin.process.traversal.Step; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.traverser.B_LP_NL_O_P_S_SE_SL_Traverser; import java.util.HashSet; /** * @author Pieter Martin (https://github.com/pietermartin) * Date: 2017/05/01 */ public class SqlgTraverser<T> extends B_LP_NL_O_P_S_SE_SL_Traverser<T> implements ISqlgTraverser { private long startElementIndex; private final boolean requiresSack; private boolean requiresOneBulk; SqlgTraverser(T t, Step<T, ?> step, long initialBulk, boolean requiresSack, boolean requiresOneBulk) { super(t, step, initialBulk); this.requiresSack = requiresSack; this.requiresOneBulk = requiresOneBulk; } public void setStartElementIndex(long startElementIndex) { this.startElementIndex = startElementIndex; } public long getStartElementIndex() { return this.startElementIndex; } @Override public void resetLoops() { if (!this.nestedLoops.isEmpty()) { this.nestedLoops.pop(); } } // @Override // public <R> Traverser.Admin<R> split(final R r, final Step<T, R> step) { // final SqlgTraverser<R> clone = (SqlgTraverser<R>) super.split(r, step); // clone.path = clone.path.clone().extend(r, step.getLabels()); // return clone; // } // // @Override // public Traverser.Admin<T> split() { // final SqlgTraverser<T> clone = (SqlgTraverser<T>) super.split(); // clone.path = clone.path.clone(); // return clone; // } @Override public void merge(final Traverser.Admin<?> other) { if (this.requiresOneBulk) { //O_Traverser if (!other.getTags().isEmpty()) { if (this.tags == null) this.tags = new HashSet<>(); this.tags.addAll(other.getTags()); } //skip the B_O_Traverser //B_O_Traverser //this.bulk = this.bulk + other.bulk(); //B_O_S_SE_SL_Traverser if (null != this.sack && null != this.sideEffects.getSackMerger()) this.sack = this.sideEffects.getSackMerger().apply(this.sack, other.sack()); } else { super.merge(other); } } @Override public int hashCode() { if (this.requiresSack) { return this.t.hashCode() + this.future.hashCode() + this.loops; } else { return super.hashCode(); } } @Override public boolean equals(final Object object) { if (this.requiresSack) { return (object instanceof SqlgTraverser) && ((SqlgTraverser) object).t.equals(this.t) && ((SqlgTraverser) object).future.equals(this.future) && ((SqlgTraverser) object).loops == this.loops && (null == this.sack || null != this.sideEffects.getSackMerger()); } else { return super.equals(object); } } public void setRequiresOneBulk(boolean requiresOneBulk) { this.requiresOneBulk = requiresOneBulk; } }
mit
SmiletolifeTian/Android_Tian_Project_Chabaike
src/com/tian/project/chabaike/adapter/ItemInfoAdapter.java
2641
package com.tian.project.chabaike.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.loopj.android.image.SmartImageView; import com.tian.project.chabaike.R; import com.tian.project.chabaike.entity.ItemInfo; import com.tian.project.chabaike.entity.ItemInfoData; public class ItemInfoAdapter extends BaseAdapter { private Context context; private ItemInfo itemInfo; public ItemInfoAdapter(Context context, ItemInfo itemInfo) { this.context = context; this.itemInfo = itemInfo; } @Override public int getCount() { if (itemInfo != null && itemInfo.getData() != null && itemInfo.getData().size() > 0) { return itemInfo.getData().size(); } return 0; } @Override public Object getItem(int position) { if (itemInfo != null && itemInfo.getData() != null && itemInfo.getData().size() > 0) { return itemInfo.getData().get(position); } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate( R.layout.list_view_item_head_line, parent, false); viewHolder = new ViewHolder(); viewHolder.imgIcon = (SmartImageView) convertView .findViewById(R.id.img_icon); viewHolder.txCreateTime = (TextView) convertView .findViewById(R.id.tx_create_time); viewHolder.txNickname = (TextView) convertView .findViewById(R.id.tx_nickname); viewHolder.txSource = (TextView) convertView .findViewById(R.id.tx_source); viewHolder.txTitle = (TextView) convertView .findViewById(R.id.tx_title); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } ItemInfoData data = (ItemInfoData) getItem(position); if (data != null) { if (data.getWap_thumb().length() > 0) { viewHolder.imgIcon.setImageUrl(data.getWap_thumb()); } viewHolder.txCreateTime.setText(data.getCreate_time()); viewHolder.txNickname.setText(data.getNickname()); viewHolder.txSource.setText(data.getSource()); viewHolder.txTitle.setText(data.getTitle()); } return convertView; } class ViewHolder { public SmartImageView imgIcon; public TextView txTitle; public TextView txSource; public TextView txNickname; public TextView txCreateTime; } }
mit
shaunmahony/seqcode
src/edu/psu/compbio/seqcode/gse/deepseq/utilities/ReadLoader.java
2451
package edu.psu.compbio.seqcode.gse.deepseq.utilities; import java.util.List; import java.util.TreeMap; import edu.psu.compbio.seqcode.gse.datasets.general.Region; import edu.psu.compbio.seqcode.gse.datasets.species.Genome; import edu.psu.compbio.seqcode.gse.deepseq.ExtReadHit; import edu.psu.compbio.seqcode.gse.deepseq.ReadHit; import edu.psu.compbio.seqcode.gse.projects.readdb.PairedHit; /** * Loads reads. Where those reads are sourced from is implementation-specific. * This class contains methods that are required regardless of the source of the reads. For example, loading reads according to a region. * * @author shaun * */ public abstract class ReadLoader { protected Genome gen; protected double totalHits; protected double totalWeight; protected double totalForWeight=-1,totalRevWeight=-1; protected int readLength; protected boolean pairedEnd = false; //What to do with this flag is left to the subclass public ReadLoader(Genome g, int rLen){ gen=g; readLength=rLen; totalHits=0; totalWeight=0; } //Accessors public Genome getGenome(){return(gen);} public int getReadLen(){return readLength;} public double getHitCount(){return(totalHits);} public double getTotalWeight(){return(totalWeight);} public double getStrandedWeight(char strand){ //System.out.print(strand+" strand hits: "); if(strand=='+'){ if(totalForWeight<=-1) totalForWeight=countStrandedWeight(strand); totalRevWeight=totalWeight-totalForWeight; // System.out.print((int)totalForWeight+"\n"); return(totalForWeight); }else{ if(totalRevWeight<=-1) totalRevWeight=countStrandedWeight(strand); totalForWeight=totalWeight-totalRevWeight; // System.out.print((int)totalRevWeight+"\n"); return(totalRevWeight); } } //Abstract methods protected abstract double countHits(); protected abstract double countStrandedWeight(char strand); public abstract List<ReadHit> loadHits(Region r); public abstract List<ExtReadHit> loadExtHits(Region r, int startShift, int fivePrimeExt, int threePrimeExt); public abstract List<ReadHit> loadPairs(Region r); public abstract List<PairedHit> loadPairsAsPairs(Region r); public abstract int countHits (Region r); public abstract double sumWeights (Region r); public abstract void cleanup(); public abstract void setGenome(Genome g); public void setPairedEnd(boolean pe){pairedEnd=pe;} }
mit
blevandowski-lv/graphql-java
src/test/groovy/graphql/validation/SpecValidationSchema.java
8528
package graphql.validation; import graphql.Scalars; import graphql.TypeResolutionEnvironment; import graphql.schema.FieldDataFetcher; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLEnumType; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLInterfaceType; import graphql.schema.GraphQLNonNull; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLType; import graphql.schema.GraphQLUnionType; import graphql.schema.TypeResolver; import graphql.validation.SpecValidationSchemaPojos.Alien; import graphql.validation.SpecValidationSchemaPojos.Cat; import graphql.validation.SpecValidationSchemaPojos.Dog; import graphql.validation.SpecValidationSchemaPojos.Human; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Sample schema used in the spec for validation examples * http://facebook.github.io/graphql/#sec-Validation * @author dwinsor * */ public class SpecValidationSchema { public static final GraphQLEnumType dogCommand = GraphQLEnumType.newEnum() .name("DogCommand") .value("SIT") .value("DOWN") .value("HEEL") .build(); public static final GraphQLEnumType catCommand = GraphQLEnumType.newEnum() .name("CatCommand") .value("JUMP") .build(); public static final GraphQLInterfaceType sentient = GraphQLInterfaceType.newInterface() .name("Sentient") .field(new GraphQLFieldDefinition( "name", null, new GraphQLNonNull(Scalars.GraphQLString), new FieldDataFetcher("name"), Collections.emptyList(), null)) .typeResolver(new TypeResolver() { @Override public GraphQLObjectType getType(TypeResolutionEnvironment env) { if (env.getObject() instanceof Human) return human; if (env.getObject() instanceof Alien) return alien; return null; }}) .build(); public static final GraphQLInterfaceType pet = GraphQLInterfaceType.newInterface() .name("Pet") .field(new GraphQLFieldDefinition( "name", null, new GraphQLNonNull(Scalars.GraphQLString), new FieldDataFetcher("name"), Collections.emptyList(), null)) .typeResolver(new TypeResolver() { @Override public GraphQLObjectType getType(TypeResolutionEnvironment env) { if (env.getObject() instanceof Dog) return dog; if (env.getObject() instanceof Cat) return cat; return null; }}) .build(); public static final GraphQLObjectType human = GraphQLObjectType.newObject() .name("Human") .field(new GraphQLFieldDefinition( "name", null, new GraphQLNonNull(Scalars.GraphQLString), new FieldDataFetcher("name"), Collections.emptyList(), null)) .withInterface(SpecValidationSchema.sentient) .build(); public static final GraphQLObjectType alien = GraphQLObjectType.newObject() .name("Alien") .field(new GraphQLFieldDefinition( "name", null, new GraphQLNonNull(Scalars.GraphQLString), new FieldDataFetcher("name"), Collections.emptyList(), null)) .field(new GraphQLFieldDefinition( "homePlanet", null, Scalars.GraphQLString, new FieldDataFetcher("homePlanet"), Collections.emptyList(), null)) .withInterface(SpecValidationSchema.sentient) .build(); public static final GraphQLArgument dogCommandArg = GraphQLArgument.newArgument() .name("dogCommand") .type(new GraphQLNonNull(dogCommand)) .build(); public static final GraphQLArgument atOtherHomesArg = GraphQLArgument.newArgument() .name("atOtherHomes") .type(Scalars.GraphQLBoolean) .build(); public static final GraphQLArgument catCommandArg = GraphQLArgument.newArgument() .name("catCommand") .type(new GraphQLNonNull(catCommand)) .build(); public static final GraphQLObjectType dog = GraphQLObjectType.newObject() .name("Dog") .field(new GraphQLFieldDefinition( "name", null, new GraphQLNonNull(Scalars.GraphQLString), new FieldDataFetcher("name"), Collections.emptyList(), null)) .field(new GraphQLFieldDefinition( "nickname", null, Scalars.GraphQLString, new FieldDataFetcher("nickname"), Collections.emptyList(), null)) .field(new GraphQLFieldDefinition( "barkVolume", null, Scalars.GraphQLInt, new FieldDataFetcher("barkVolume"), Collections.emptyList(), null)) .field(new GraphQLFieldDefinition( "doesKnowCommand", null, new GraphQLNonNull(Scalars.GraphQLBoolean), new FieldDataFetcher("doesKnowCommand"), Arrays.asList(dogCommandArg), null)) .field(new GraphQLFieldDefinition( "isHousetrained", null, Scalars.GraphQLBoolean, new FieldDataFetcher("isHousetrained"), Arrays.asList(atOtherHomesArg), null)) .field(new GraphQLFieldDefinition( "owner", null, human, new FieldDataFetcher("owner"), Collections.emptyList(), null)) .withInterface(SpecValidationSchema.pet) .build(); public static final GraphQLObjectType cat = GraphQLObjectType.newObject() .name("Cat") .field(new GraphQLFieldDefinition( "name", null, new GraphQLNonNull(Scalars.GraphQLString), new FieldDataFetcher("name"), Collections.emptyList(), null)) .field(new GraphQLFieldDefinition( "nickname", null, Scalars.GraphQLString, new FieldDataFetcher("nickname"), Collections.emptyList(), null)) .field(new GraphQLFieldDefinition( "meowVolume", null, Scalars.GraphQLInt, new FieldDataFetcher("meowVolume"), Collections.emptyList(), null)) .field(new GraphQLFieldDefinition( "doesKnowCommand", null, new GraphQLNonNull(Scalars.GraphQLBoolean), new FieldDataFetcher("doesKnowCommand"), Arrays.asList(catCommandArg), null)) .withInterface(SpecValidationSchema.pet) .build(); public static final GraphQLUnionType catOrDog = GraphQLUnionType.newUnionType() .name("CatOrDog") .possibleTypes(cat, dog) .typeResolver(env -> { if (env.getObject() instanceof Cat) return cat; if (env.getObject() instanceof Dog) return dog; return null; }) .build(); public static final GraphQLUnionType dogOrHuman = GraphQLUnionType.newUnionType() .name("DogOrHuman") .possibleTypes(dog, human) .typeResolver(env -> { if (env.getObject() instanceof Human) return human; if (env.getObject() instanceof Dog) return dog; return null; }) .build(); public static final GraphQLUnionType humanOrAlien = GraphQLUnionType.newUnionType() .name("HumanOrAlien") .possibleTypes(human, alien) .typeResolver(env -> { if (env.getObject() instanceof Human) return human; if (env.getObject() instanceof Alien) return alien; return null; }) .build(); public static final GraphQLObjectType queryRoot = GraphQLObjectType.newObject() .name("QueryRoot") .field(new GraphQLFieldDefinition( "dog", null, dog, new FieldDataFetcher("dog"), Collections.emptyList(), null)) .build(); @SuppressWarnings("serial") public static final Set<GraphQLType> specValidationDictionary = new HashSet<GraphQLType>() {{ add(dogCommand); add(catCommand); add(sentient); add(pet); add(human); add(alien); add(dog); add(cat); add(catOrDog); add(dogOrHuman); add(humanOrAlien); }}; public static final GraphQLSchema specValidationSchema = GraphQLSchema.newSchema() .query(queryRoot) .build(specValidationDictionary); }
mit
myid999/javademo
core/src/main/java/demo/java/v2c04db/QueryDB/QueryDB.java
8563
package demo.java.v2c04db.QueryDB; import java.sql.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; /** * This program demonstrates several complex database queries. * @version 1.23 2007-06-28 * @author Cay Horstmann */ public class QueryDB { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new QueryDBFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * This frame displays combo boxes for query parameters, a text area for command results, and * buttons to launch a query and an update. */ class QueryDBFrame extends JFrame { public QueryDBFrame() { setTitle("QueryDB"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setLayout(new GridBagLayout()); authors = new JComboBox(); authors.setEditable(false); authors.addItem("Any"); publishers = new JComboBox(); publishers.setEditable(false); publishers.addItem("Any"); result = new JTextArea(4, 50); result.setEditable(false); priceChange = new JTextField(8); priceChange.setText("-5.00"); try { conn = getConnection(); Statement stat = conn.createStatement(); String query = "SELECT Name FROM Authors"; ResultSet rs = stat.executeQuery(query); while (rs.next()) authors.addItem(rs.getString(1)); rs.close(); query = "SELECT Name FROM Publishers"; rs = stat.executeQuery(query); while (rs.next()) publishers.addItem(rs.getString(1)); rs.close(); stat.close(); } catch (SQLException e) { for (Throwable t : e) result.append(t.getMessage()); } catch (IOException e) { result.setText("" + e); } // we use the GBC convenience class of Core Java Volume 1 Chapter 9 add(authors, new GBC(0, 0, 2, 1)); add(publishers, new GBC(2, 0, 2, 1)); JButton queryButton = new JButton("Query"); queryButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { executeQuery(); } }); add(queryButton, new GBC(0, 1, 1, 1).setInsets(3)); JButton changeButton = new JButton("Change prices"); changeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { changePrices(); } }); add(changeButton, new GBC(2, 1, 1, 1).setInsets(3)); add(priceChange, new GBC(3, 1, 1, 1).setFill(GBC.HORIZONTAL)); add(new JScrollPane(result), new GBC(0, 2, 4, 1).setFill(GBC.BOTH).setWeight(100, 100)); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { try { if (conn != null) conn.close(); } catch (SQLException e) { for (Throwable t : e) t.printStackTrace(); } } }); } /** * Executes the selected query. */ private void executeQuery() { ResultSet rs = null; try { String author = (String) authors.getSelectedItem(); String publisher = (String) publishers.getSelectedItem(); if (!author.equals("Any") && !publisher.equals("Any")) { if (authorPublisherQueryStmt == null) authorPublisherQueryStmt = conn .prepareStatement(authorPublisherQuery); authorPublisherQueryStmt.setString(1, author); authorPublisherQueryStmt.setString(2, publisher); rs = authorPublisherQueryStmt.executeQuery(); } else if (!author.equals("Any") && publisher.equals("Any")) { if (authorQueryStmt == null) authorQueryStmt = conn.prepareStatement(authorQuery); authorQueryStmt.setString(1, author); rs = authorQueryStmt.executeQuery(); } else if (author.equals("Any") && !publisher.equals("Any")) { if (publisherQueryStmt == null) publisherQueryStmt = conn .prepareStatement(publisherQuery); publisherQueryStmt.setString(1, publisher); rs = publisherQueryStmt.executeQuery(); } else { if (allQueryStmt == null) allQueryStmt = conn.prepareStatement(allQuery); rs = allQueryStmt.executeQuery(); } result.setText(""); while (rs.next()) { result.append(rs.getString(1)); result.append(", "); result.append(rs.getString(2)); result.append("\n"); } rs.close(); } catch (SQLException e) { for (Throwable t : e) result.append(t.getMessage()); } } /** * Executes an update statement to change prices. */ public void changePrices() { String publisher = (String) publishers.getSelectedItem(); if (publisher.equals("Any")) { result.setText("I am sorry, but I cannot do that."); return; } try { if (priceUpdateStmt == null) priceUpdateStmt = conn.prepareStatement(priceUpdate); priceUpdateStmt.setString(1, priceChange.getText()); priceUpdateStmt.setString(2, publisher); int r = priceUpdateStmt.executeUpdate(); result.setText(r + " records updated."); } catch (SQLException e) { for (Throwable t : e) result.append(t.getMessage()); } } /** * Gets a connection from the properties specified in the file database.properties * @return the database connection */ public static Connection getConnection() throws SQLException, IOException { Properties props = new Properties(); FileInputStream in = new FileInputStream("database.properties"); props.load(in); in.close(); String drivers = props.getProperty("jdbc.drivers"); if (drivers != null) System.setProperty("jdbc.drivers", drivers); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); return DriverManager.getConnection(url, username, password); } public static final int DEFAULT_WIDTH = 400; public static final int DEFAULT_HEIGHT = 400; private JComboBox authors; private JComboBox publishers; private JTextField priceChange; private JTextArea result; private Connection conn; private PreparedStatement authorQueryStmt; private PreparedStatement authorPublisherQueryStmt; private PreparedStatement publisherQueryStmt; private PreparedStatement allQueryStmt; private PreparedStatement priceUpdateStmt; private static final String authorPublisherQuery = "SELECT Books.Price, Books.Title FROM Books, BooksAuthors, Authors, Publishers" + " WHERE Authors.Author_Id = BooksAuthors.Author_Id AND BooksAuthors.ISBN = Books.ISBN" + " AND Books.Publisher_Id = Publishers.Publisher_Id AND Authors.Name = ?" + " AND Publishers.Name = ?"; private static final String authorQuery = "SELECT Books.Price, Books.Title FROM Books, BooksAuthors, Authors" + " WHERE Authors.Author_Id = BooksAuthors.Author_Id AND BooksAuthors.ISBN = Books.ISBN" + " AND Authors.Name = ?"; private static final String publisherQuery = "SELECT Books.Price, Books.Title FROM Books, Publishers" + " WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = ?"; private static final String allQuery = "SELECT Books.Price, Books.Title FROM Books"; private static final String priceUpdate = "UPDATE Books " + "SET Price = Price + ? " + " WHERE Books.Publisher_Id = (SELECT Publisher_Id FROM Publishers WHERE Name = ?)"; }
mit
cobr123/VirtaMarketAnalyzer
src/main/java/ru/VirtaMarketAnalyzer/data/TechReport.java
1439
package ru.VirtaMarketAnalyzer.data; import com.google.gson.annotations.SerializedName; /** * Created by cobr123 on 05.05.2017. */ final public class TechReport { @SerializedName("unit_type_id") final private String unitTypeID; @SerializedName("unit_type_symbol") final private String unitTypeSymbol; @SerializedName("unit_type_name") final private String unitTypeName; @SerializedName("level") final private int level; @SerializedName("price") final private double price; @SerializedName("status") final private int status; public TechReport( final String unitTypeID , final String unitTypeSymbol , final String unitTypeName , final int level , final double price , final int status ) { this.unitTypeID = unitTypeID; this.unitTypeSymbol = unitTypeSymbol; this.unitTypeName = unitTypeName; this.level = level; this.price = price; this.status = status; } public String getUnitTypeID() { return unitTypeID; } public String getUnitTypeSymbol() { return unitTypeSymbol; } public String getUnitTypeName() { return unitTypeName; } public int getLevel() { return level; } public double getPrice() { return price; } public int getStatus() { return status; } }
mit
johanpoirier/beacon-notifier
app/src/main/java/com/jops/android/beaconnotifier/receiver/BootReceiver.java
830
package com.jops.android.beaconnotifier.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.jops.android.beaconnotifier.EstimoteConfig; import com.jops.android.beaconnotifier.service.ScanService_; import org.androidannotations.annotations.EReceiver; @EReceiver public class BootReceiver extends BroadcastReceiver { public BootReceiver() { } @Override public void onReceive(Context context, Intent intent) { EstimoteConfig.log(context, "BootReceiver: " + intent.getAction()); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { EstimoteConfig.log(context, "BootReceiver: requesting ScanService start"); context.startService(new Intent(context, ScanService_.class)); } } }
mit
jensborch/kontentsu
api/src/main/java/dk/kontentsu/api/exposure/ExternalFileExposure.java
4393
/* * The MIT License * * Copyright 2016 Jens Borch Christiansen. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dk.kontentsu.api.exposure; import java.time.ZonedDateTime; import javax.annotation.security.PermitAll; import javax.ejb.Stateless; import javax.inject.Inject; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import dk.kontentsu.api.exposure.model.ErrorRepresentation; import dk.kontentsu.model.ExternalFile; import dk.kontentsu.repository.ExternalFileRepository; import dk.kontentsu.util.DateTimeFormat; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** * Exposure for getting files the CDN. * * @author Jens Borch Christiansen */ @Path("/files") @Stateless @PermitAll @Api(tags = {"files"}) public class ExternalFileExposure { @Inject private ExternalFileRepository repo; @GET @Path("/{uri:.*}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get content as on the CDN", notes = "The accept header must match the mime type of the content at the given URI") @ApiResponses(value = { @ApiResponse(code = 200, message = "The content uploaded to the CDN"), @ApiResponse(code = 404, message = "No content found at URI", response = ErrorRepresentation.class), @ApiResponse(code = 406, message = "Accept header does not match resource mime type", response = ErrorRepresentation.class)}) public Response get( @ApiParam(value = "URI to content on the CDN", required = true) @PathParam("uri") @NotNull @Size(min = 3) final String uri, @ApiParam(value = "Accept header defining the content type to retrieve", required = false) @HeaderParam(HttpHeaders.ACCEPT) final String acceptHeader, @ApiParam(value = "Timestamp in UTC format defining at what point in time to get content from", required = false) @QueryParam("at") @DateTimeFormat(DateTimeFormat.Format.UTC) final String at) { ZonedDateTime time = (at == null) ? null : ZonedDateTime.parse(at); ExternalFile result = repo.getByUri(uri, time); return getResponse(result, acceptHeader); } private Response getResponse(final ExternalFile file, final String acceptHeader) { if (file.getMimeType().matchesHeader(acceptHeader)) { Response.ResponseBuilder builder = Response .status(Response.Status.OK) .entity(file.getContent().getDataAsBinaryStream()) .type(file.getMimeType().toMediaType()); file.getContent().getEncoding().ifPresent(e -> builder.encoding(e.toString())); return builder.build(); } else { throw new MimeTypeMismatchException("Accept header " + acceptHeader + " does not match resource mime type " + file.getMimeType()); } } }
mit
Dauth/cs3219-JMS
hornetq-2.4.0.Final/examples/jms/transactional/src/main/java/org/hornetq/jms/example/TransactionalExample.java
4936
/* * Copyright 2009 Red Hat, Inc. * Red Hat 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.hornetq.jms.example; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.InitialContext; import org.hornetq.common.example.HornetQExample; /** * A simple JMS example that sends and consume message transactionally. * * @author <a href="hgao@redhat.com">Howard Gao</a> */ public class TransactionalExample extends HornetQExample { public static void main(final String[] args) { new TransactionalExample().run(args); } @Override public boolean runExample() throws Exception { Connection connection = null; InitialContext initialContext = null; try { // Step 1. Create an initial context to perform the JNDI lookup. initialContext = getContext(0); // Step 2. Look-up the JMS topic Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue"); // Step 3. Look-up the JMS connection factory ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory"); // Step 4. Create a JMS connection connection = cf.createConnection(); // Step 5. Start the connection connection.start(); // Step 6. Create a transactional JMS session Session session = connection.createSession(true, Session.SESSION_TRANSACTED); // Step 7. Create a JMS message producer MessageProducer messageProducer = session.createProducer(queue); // Step 8. Create a message consumer MessageConsumer messageConsumer = session.createConsumer(queue); // Step 9. Create 2 text messages TextMessage message1 = session.createTextMessage("This is a text message1"); TextMessage message2 = session.createTextMessage("This is a text message2"); // Step 10. Send the text messages to the queue messageProducer.send(message1); messageProducer.send(message2); System.out.println("Sent message: " + message1.getText()); System.out.println("Sent message: " + message2.getText()); // Step 11. Receive the message, it will return null as the transaction is not committed. TextMessage receivedMessage = (TextMessage)messageConsumer.receive(5000); System.out.println("Message received before send commit: " + receivedMessage); // Step 12. Commit the session session.commit(); // Step 13. Receive the messages again receivedMessage = (TextMessage)messageConsumer.receive(5000); System.out.println("Message received after send commit: " + receivedMessage.getText()); // Step 14. Roll back the session, this will cause the received message canceled and redelivered again. session.rollback(); // Step 15. Receive the message again, we will get two messages receivedMessage = (TextMessage)messageConsumer.receive(5000); System.out.println("Message1 received after receive rollback: " + receivedMessage.getText()); receivedMessage = (TextMessage)messageConsumer.receive(5000); System.out.println("Message2 received after receive rollback: " + receivedMessage.getText()); receivedMessage = (TextMessage)messageConsumer.receive(5000); System.out.println("Message3 received after receive rollback: " + receivedMessage); // Step 16. Commit the session session.commit(); // Step 17. Receive the message again. Nothing should be received. receivedMessage = (TextMessage)messageConsumer.receive(5000); if (receivedMessage != null) { // This was not supposed to happen return false; } System.out.println("Message received after receive commit: " + receivedMessage); return true; } finally { if (connection != null) { // Step 18. Be sure to close our JMS resources! connection.close(); } if (initialContext != null) { // Step 19. Also close initial context! initialContext.close(); } } } }
mit
javawolfpack/CSCI567---Workspace
FragmentExample/src/csci567/FragmentExample/MyFragment.java
1749
package csci567.FragmentExample; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; public class MyFragment extends Fragment implements OnClickListener{ public static final String TAG = "myfrag"; private GetFragNumber gfn; private Button changefrag; private TextView text; private int fragnumber = 0; private Fragmentmanageractivity fragmanager = null; static MyFragment newInstance() { MyFragment frag = new MyFragment(); return frag; } public interface GetFragNumber { public int getData(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try{ gfn = (GetFragNumber) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement GetFragNumber"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setRetainInstance(true); View result = inflater.inflate(R.layout.my_fragment, container, false); fragnumber = gfn.getData(); changefrag = (Button) result.findViewById(R.id.button); changefrag.setOnClickListener(this); text = (TextView) result.findViewById(R.id.text); text.setText(Integer.toString(fragnumber)); // Inflate the layout for this fragment return result; } @Override public void onClick(View v) { fragmanager = (Fragmentmanageractivity) getActivity(); int id = v.getId(); if (id == R.id.button){ if(fragmanager != null) fragmanager.addFragment(); } } }
mit
Theyssen/LinguAdde
src/main/java/linguadde/replacer/XmlReplacer.java
1654
package linguadde.replacer; import linguadde.exception.KeyNotFoundException; import linguadde.exception.NoTranslationException; import linguadde.model.LangData; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class XmlReplacer implements Replacer { @Override public String replace(LangData data, String string) { Matcher matcher = Pattern.compile("source-language=\"" + data.getKeyLang() + "\"").matcher(string); if (!matcher.find()) { System.out.println("Could not find key language as source language!"); return string; } matcher.usePattern(Pattern.compile("target-language=\"(.*?)\"")); matcher.find(); String targetLang = matcher.group(1); int targetLangId = data.getValueLangs().indexOf(targetLang); matcher.usePattern(Pattern.compile("((\\s*?)<source>(.*?)</source>)(\\s*?<target>.*?</target>)?")); StringBuffer sb = new StringBuffer(); while (matcher.find()) { List<String> translations = data.getTranslations(matcher.group(3)); if (translations != null) { if (translations.size() > targetLangId) { matcher.appendReplacement(sb, String.format("$1$2<target>%s</target>", translations.get(targetLangId))); } else { new NoTranslationException(String.format("%s: %s", targetLang, matcher.group(3))); } } else { new KeyNotFoundException(matcher.group(3)); } } matcher.appendTail(sb); return sb.toString(); } }
mit
effine/shopping
src/main/java/cn/effine/lab/jedis/TestJedis.java
2185
/** * @author effine * @date 2015年1月31日 下午4:53:57 */ package cn.effine.lab.jedis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import java.util.Set; public class TestJedis { private static final Logger logger = LoggerFactory.getLogger(TestJedis.class); private static String extranetHost = "127.0.0.1"; private static int extranetPort = 6379; // 测试 @Deprecated public static void main(String[] args) { TestJedis test = new TestJedis(); logger.info("----------开始调用jedis基本使用方法"); test.baseJedis(); logger.info("----------开始调用jedis使用池方法"); test.poolJedis(); logger.info("----------全部方法调用完成"); } public static Jedis getRedis() { JedisShardInfo info = new JedisShardInfo(extranetHost, extranetPort); return new Jedis(info); } /** * jedis的基本使用(jedis非线程安全) */ public void baseJedis() { Jedis j = TestJedis.getRedis(); j.set("hello", "world"); String output = j.get("hello"); System.out.println("jedis基本使用: " + output); } /** * jedis使用池 */ public void poolJedis() { @SuppressWarnings("resource") JedisPool pool = new JedisPool(new JedisPoolConfig(), extranetHost); Jedis jedis = pool.getResource(); jedis.auth("yunlu123"); try { // 开始使用 jedis.set("foo", "bar"); String foobar = jedis.get("foo"); System.out.println("jedis使用池:" + foobar); jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); Set<String> sose = jedis.zrange("sose", 0, -1); } finally { if (null != jedis) { // 使用完后,将连接放回连接池 jedis.close(); } } // 应用退出时,关闭连接池 pool.destroy(); } }
mit
endercrest/UWaterloo-API
src/main/java/com/endercrest/uwaterlooapi/events/models/Event.java
578
package com.endercrest.uwaterlooapi.events.models; import com.google.gson.annotations.SerializedName; /** * Created by Thomas Cordua-von Specht on 12/1/2016. */ public class Event extends EventBase { private String site; @SerializedName("site_name") private String siteName; public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } }
mit
ellifellner/Towan
src/at/fh/swenga/controller/TowanController.java
3723
package at.fh.swenga.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import at.fh.swenga.dao.UserRepository; import at.fh.swenga.game.data.Boot; import at.fh.swenga.game.data.Player; import at.fh.swenga.model.UserModel; @Controller public class TowanController { @Autowired UserRepository userRepository; @RequestMapping(value = { "/", "index" }) public String showWelcome(Model model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); model.addAttribute("currUsername", auth.getName()); return "index"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin() { return "login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String doLogin() { return "home"; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String doLogout(HttpServletRequest request) { HttpSession session = request.getSession(); session.invalidate(); return "index"; } @RequestMapping(value = "/home") public String showHome() { return "home"; } @RequestMapping(value = "/profile") public String showProfile(Model model) { // Get user from DB UserModel user = null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); List<UserModel> userList = userRepository.findByUsername(auth.getName()); user = userList.get(0); // Update DB user.setTotal_enemies_slain(user.getTotal_enemies_slain() + Player.Enemies_slain); user.setTotal_waves_completed(user.getTotal_waves_completed() + Player.Waves_completed); user.setTotal_towers_built(user.getTotal_towers_built() + Player.Towers_built); user.setPlaytime(user.getPlaytime() + Player.Playtime); // Read from DB model.addAttribute("currUsername", auth.getName()); model.addAttribute("playtime", user.getPlaytime()); model.addAttribute("total_enemies_slain", user.getTotal_enemies_slain()); model.addAttribute("towers_build", user.getTotal_towers_built()); model.addAttribute("waves_completed", user.getTotal_waves_completed()); userRepository.save(user); // Reset Player stats Player.Enemies_slain = 0; Player.Waves_completed = 0; Player.Towers_built = 0; Player.Playtime = 0; return "profile"; } @RequestMapping(value = "/game", method = RequestMethod.GET) public String showGame() { return "game"; } @RequestMapping(value = "/towanGame") public String startGame() { new Boot(); return "towanGame"; } @RequestMapping(value = "/settings") public String showSettings() { return "settings"; } @RequestMapping(value = "/impressum") public String showAbout() { return "impressum"; } @RequestMapping(value = "/forgottenpwd") public String showForgottenPwd() { return "forgottenpwd"; } @ExceptionHandler(Exception.class) public String handleAllException(Exception ex) { ex.printStackTrace(); return "error"; } }
mit
divotkey/cogaen3-java
Cogaen Core/src/org/cogaen/core/ServiceException.java
2699
/* ----------------------------------------------------------------------------- Cogaen - Component-based Game Engine V3 ----------------------------------------------------------------------------- This software is developed by the Cogaen Development Team. Please have a look at our project home page for further details: http://www.cogaen.org - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Copyright (c) 2010-2012 Roman Divotkey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ package org.cogaen.core; /** * A {@code ServiceException} is thrown to indicate that the attempt * to start a service has failed. */ public class ServiceException extends Exception { private static final long serialVersionUID = 6195244931574767661L; /** * Creates a new {@code ServiceException} with no detail message. */ public ServiceException() { // intentionally left empty } /** * Creates a new {@code ServiceException} with specified detail message. * @param message the detail message */ public ServiceException(String message) { super(message); } /** * Creates a new {@code ServiceException} with specified cause. * @param cause the cause */ public ServiceException(Throwable cause) { super(cause); } /** * Creates a new {@code ServiceException} with specified detail message * and cause. * @param message the detail message * @param cause the cause */ public ServiceException(String message, Throwable cause) { super(message, cause); } }
mit
bartsch-dev/jabref
src/test/java/org/jabref/model/entry/MonthUtilTest.java
4316
package org.jabref.model.entry; import org.junit.Assert; import org.junit.Test; public class MonthUtilTest { @Test public void testToMonthNumber() { Assert.assertEquals(0, MonthUtil.getMonth("jan").index); Assert.assertEquals(1, MonthUtil.getMonth("feb").index); Assert.assertEquals(2, MonthUtil.getMonth("mar").index); Assert.assertEquals(3, MonthUtil.getMonth("apr").index); Assert.assertEquals(4, MonthUtil.getMonth("may").index); Assert.assertEquals(5, MonthUtil.getMonth("jun").index); Assert.assertEquals(6, MonthUtil.getMonth("jul").index); Assert.assertEquals(7, MonthUtil.getMonth("aug").index); Assert.assertEquals(8, MonthUtil.getMonth("sep").index); Assert.assertEquals(9, MonthUtil.getMonth("oct").index); Assert.assertEquals(10, MonthUtil.getMonth("nov").index); Assert.assertEquals(11, MonthUtil.getMonth("dec").index); Assert.assertEquals(0, MonthUtil.getMonth("#jan#").index); Assert.assertEquals(1, MonthUtil.getMonth("#feb#").index); Assert.assertEquals(2, MonthUtil.getMonth("#mar#").index); Assert.assertEquals(3, MonthUtil.getMonth("#apr#").index); Assert.assertEquals(4, MonthUtil.getMonth("#may#").index); Assert.assertEquals(5, MonthUtil.getMonth("#jun#").index); Assert.assertEquals(6, MonthUtil.getMonth("#jul#").index); Assert.assertEquals(7, MonthUtil.getMonth("#aug#").index); Assert.assertEquals(8, MonthUtil.getMonth("#sep#").index); Assert.assertEquals(9, MonthUtil.getMonth("#oct#").index); Assert.assertEquals(10, MonthUtil.getMonth("#nov#").index); Assert.assertEquals(11, MonthUtil.getMonth("#dec#").index); Assert.assertEquals(0, MonthUtil.getMonth("January").index); Assert.assertEquals(1, MonthUtil.getMonth("February").index); Assert.assertEquals(2, MonthUtil.getMonth("March").index); Assert.assertEquals(3, MonthUtil.getMonth("April").index); Assert.assertEquals(4, MonthUtil.getMonth("May").index); Assert.assertEquals(5, MonthUtil.getMonth("June").index); Assert.assertEquals(6, MonthUtil.getMonth("July").index); Assert.assertEquals(7, MonthUtil.getMonth("August").index); Assert.assertEquals(8, MonthUtil.getMonth("September").index); Assert.assertEquals(9, MonthUtil.getMonth("October").index); Assert.assertEquals(10, MonthUtil.getMonth("November").index); Assert.assertEquals(11, MonthUtil.getMonth("December").index); Assert.assertEquals(0, MonthUtil.getMonth("01").index); Assert.assertEquals(1, MonthUtil.getMonth("02").index); Assert.assertEquals(2, MonthUtil.getMonth("03").index); Assert.assertEquals(3, MonthUtil.getMonth("04").index); Assert.assertEquals(4, MonthUtil.getMonth("05").index); Assert.assertEquals(5, MonthUtil.getMonth("06").index); Assert.assertEquals(6, MonthUtil.getMonth("07").index); Assert.assertEquals(7, MonthUtil.getMonth("08").index); Assert.assertEquals(8, MonthUtil.getMonth("09").index); Assert.assertEquals(9, MonthUtil.getMonth("10").index); Assert.assertEquals(0, MonthUtil.getMonth("1").index); Assert.assertEquals(1, MonthUtil.getMonth("2").index); Assert.assertEquals(2, MonthUtil.getMonth("3").index); Assert.assertEquals(3, MonthUtil.getMonth("4").index); Assert.assertEquals(4, MonthUtil.getMonth("5").index); Assert.assertEquals(5, MonthUtil.getMonth("6").index); Assert.assertEquals(6, MonthUtil.getMonth("7").index); Assert.assertEquals(7, MonthUtil.getMonth("8").index); Assert.assertEquals(8, MonthUtil.getMonth("9").index); Assert.assertEquals(10, MonthUtil.getMonth("11").index); Assert.assertEquals(11, MonthUtil.getMonth("12").index); Assert.assertEquals(-1, MonthUtil.getMonth(";lkjasdf").index); Assert.assertEquals(-1, MonthUtil.getMonth("3.2").index); Assert.assertEquals(-1, MonthUtil.getMonth("#test#").index); Assert.assertEquals(-1, MonthUtil.getMonth("").index); Assert.assertFalse(MonthUtil.getMonth("8,").isValid()); Assert.assertTrue(MonthUtil.getMonth("jan").isValid()); } }
mit
jjflyx/zybs
src/com/hits/useragentutil/Application.java
5787
/* * Copyright (c) 2008-2014, Harald Walker (bitwalker.eu) and contributing developers * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the * following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of bitwalker nor the names of its * contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.hits.useragentutil; /** * Enum constants for internet applications like web-application and rich * internet application. * * @author harald * */ public enum Application { HOTMAIL(Manufacturer.MICROSOFT, 1, "Windows Live Hotmail", new String[] { "mail.live.com", "hotmail.msn" }, ApplicationType.WEBMAIL), GMAIL( Manufacturer.GOOGLE, 5, "Gmail", new String[] { "mail.google.com" }, ApplicationType.WEBMAIL), YAHOO_MAIL( Manufacturer.YAHOO, 10, "Yahoo Mail", new String[] { "mail.yahoo.com" }, ApplicationType.WEBMAIL), COMPUSERVE( Manufacturer.COMPUSERVE, 20, "Compuserve", new String[] { "csmail.compuserve.com" }, ApplicationType.WEBMAIL), AOL_WEBMAIL( Manufacturer.AOL, 30, "AOL webmail", new String[] { "webmail.aol.com" }, ApplicationType.WEBMAIL), /** * MobileMe webmail client by Apple. Previously known as .mac. */ MOBILEME( Manufacturer.APPLE, 40, "MobileMe", new String[] { "www.me.com" }, ApplicationType.WEBMAIL), /** * Mail.com * Mail.com provides consumers with web-based e-mail services */ MAIL_COM( Manufacturer.MMC, 50, "Mail.com", new String[] { ".mail.com" }, ApplicationType.WEBMAIL), /** * Popular open source webmail client. Often installed by providers or privately. */ HORDE( Manufacturer.OTHER, 50, "horde", new String[] { "horde" }, ApplicationType.WEBMAIL), OTHER_WEBMAIL(Manufacturer.OTHER, 60, "Other webmail client", new String[] { "webmail", "webemail" }, ApplicationType.WEBMAIL), UNKNOWN(Manufacturer.OTHER, 0, "Unknown", new String[0], ApplicationType.UNKNOWN); private final short id; private final String name; private final String[] aliases; private final ApplicationType applicationType; private final Manufacturer manufacturer; private Application(Manufacturer manufacturer, int versionId, String name, String[] aliases, ApplicationType applicationType) { this.id = (short) ((manufacturer.getId() << 8) + (byte) versionId); this.name = name; this.aliases = Utils.toLowerCase(aliases); this.applicationType = applicationType; this.manufacturer = manufacturer; } public short getId() { return id; } public String getName() { return name; } /** * @return the applicationType */ public ApplicationType getApplicationType() { return applicationType; } /** * @return the manufacturer */ public Manufacturer getManufacturer() { return manufacturer; } /* * Checks if the given referrer string matches to the application. Only * checks for one specific application. */ public boolean isInReferrerString(String referrerString) { final String referrerStringLowercase = referrerString.toLowerCase(); return isInReferrerStringLowercase(referrerStringLowercase); } private boolean isInReferrerStringLowercase(final String referrerStringLowercase) { return Utils.contains(referrerStringLowercase, aliases); } /* * Iterates over all Application to compare the signature with the referrer * string. If no match can be found Application.UNKNOWN will be returned. */ public static Application parseReferrerString(String referrerString) { // skip the empty and "-" referrer if (referrerString != null && referrerString.length() > 1) { String referrerStringLowercase = referrerString.toLowerCase(); for (Application applicationInList : Application.values()) { if (applicationInList.isInReferrerStringLowercase(referrerStringLowercase)) return applicationInList; } } return Application.UNKNOWN; } /** * Returns the enum constant of this type with the specified id. Throws * IllegalArgumentException if the value does not exist. * * @param id * @return */ public static Application valueOf(short id) { for (Application application : Application.values()) { if (application.getId() == id) return application; } // same behavior as standard valueOf(string) method throw new IllegalArgumentException("No enum const for id " + id); } }
mit
daisuke-nomura/RxKii
rxkii/src/main/java/com/kyaracter/rxkii/RxKiiEvent.java
688
package com.kyaracter.rxkii; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import com.kii.cloud.analytics.KiiEvent; import java.util.concurrent.Callable; import io.reactivex.Completable; public class RxKiiEvent { @CheckResult @NonNull public static Completable pushAsCompletable(@NonNull final KiiEvent kiiEvent) { return Completable .fromCallable(new Callable<Completable>() { @Override public Completable call() throws Exception { kiiEvent.push(); return null; } }); } }
mit
hx863975383/com-bjtu-gits-admin
com-bjtu-gits-domain/src/main/java/com/bjtu/gits/domain/bean/User.java
2394
package com.bjtu.gits.domain.bean; import java.util.Date; public class User { private Long id; private String account; private String password; private String name; private String nickname; private String email; private Long userTypeId; private String phone; private String avatar; private Boolean status; private Date createdTime; private Date updatedTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account == null ? null : account.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname == null ? null : nickname.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Long getUserTypeId() { return userTypeId; } public void setUserTypeId(Long userTypeId) { this.userTypeId = userTypeId; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar == null ? null : avatar.trim(); } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } public Date getUpdatedTime() { return updatedTime; } public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } }
mit
VDuda/SyncRunner-Pub
src/API/amazon/mws/xml/JAXB/OrderFulfillment.java
15789
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.03 at 03:15:27 PM EDT // package API.amazon.mws.xml.JAXB; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element ref="{}AmazonOrderID"/> * &lt;element ref="{}MerchantOrderID"/> * &lt;/choice> * &lt;element name="MerchantFulfillmentID" type="{}IDNumber" minOccurs="0"/> * &lt;element name="FulfillmentDate" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;element name="FulfillmentData" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element ref="{}CarrierCode"/> * &lt;element name="CarrierName" type="{}String"/> * &lt;/choice> * &lt;element name="ShippingMethod" type="{}String" minOccurs="0"/> * &lt;element name="ShipperTrackingNumber" type="{}String" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="Item" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element ref="{}AmazonOrderItemCode"/> * &lt;element ref="{}MerchantOrderItemID"/> * &lt;/choice> * &lt;element name="MerchantFulfillmentItemID" type="{}IDNumber" minOccurs="0"/> * &lt;element name="Quantity" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "amazonOrderID", "merchantOrderID", "merchantFulfillmentID", "fulfillmentDate", "fulfillmentData", "item" }) @XmlRootElement(name = "OrderFulfillment") public class OrderFulfillment { @XmlElement(name = "AmazonOrderID") protected String amazonOrderID; @XmlElement(name = "MerchantOrderID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String merchantOrderID; @XmlElement(name = "MerchantFulfillmentID") protected BigInteger merchantFulfillmentID; @XmlElement(name = "FulfillmentDate", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar fulfillmentDate; @XmlElement(name = "FulfillmentData") protected OrderFulfillment.FulfillmentData fulfillmentData; @XmlElement(name = "Item") protected List<OrderFulfillment.Item> item; /** * Gets the value of the amazonOrderID property. * * @return * possible object is * {@link String } * */ public String getAmazonOrderID() { return amazonOrderID; } /** * Sets the value of the amazonOrderID property. * * @param value * allowed object is * {@link String } * */ public void setAmazonOrderID(String value) { this.amazonOrderID = value; } /** * Gets the value of the merchantOrderID property. * * @return * possible object is * {@link String } * */ public String getMerchantOrderID() { return merchantOrderID; } /** * Sets the value of the merchantOrderID property. * * @param value * allowed object is * {@link String } * */ public void setMerchantOrderID(String value) { this.merchantOrderID = value; } /** * Gets the value of the merchantFulfillmentID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getMerchantFulfillmentID() { return merchantFulfillmentID; } /** * Sets the value of the merchantFulfillmentID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setMerchantFulfillmentID(BigInteger value) { this.merchantFulfillmentID = value; } /** * Gets the value of the fulfillmentDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getFulfillmentDate() { return fulfillmentDate; } /** * Sets the value of the fulfillmentDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setFulfillmentDate(XMLGregorianCalendar value) { this.fulfillmentDate = value; } /** * Gets the value of the fulfillmentData property. * * @return * possible object is * {@link OrderFulfillment.FulfillmentData } * */ public OrderFulfillment.FulfillmentData getFulfillmentData() { return fulfillmentData; } /** * Sets the value of the fulfillmentData property. * * @param value * allowed object is * {@link OrderFulfillment.FulfillmentData } * */ public void setFulfillmentData(OrderFulfillment.FulfillmentData value) { this.fulfillmentData = value; } /** * Gets the value of the item property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the item property. * * <p> * For example, to add a new item, do as follows: * <pre> * getItem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OrderFulfillment.Item } * * */ public List<OrderFulfillment.Item> getItem() { if (item == null) { item = new ArrayList<OrderFulfillment.Item>(); } return this.item; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element ref="{}CarrierCode"/> * &lt;element name="CarrierName" type="{}String"/> * &lt;/choice> * &lt;element name="ShippingMethod" type="{}String" minOccurs="0"/> * &lt;element name="ShipperTrackingNumber" type="{}String" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "carrierCode", "carrierName", "shippingMethod", "shipperTrackingNumber" }) public static class FulfillmentData { @XmlElement(name = "CarrierCode") protected String carrierCode; @XmlElement(name = "CarrierName") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String carrierName; @XmlElement(name = "ShippingMethod") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String shippingMethod; @XmlElement(name = "ShipperTrackingNumber") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String shipperTrackingNumber; /** * Gets the value of the carrierCode property. * * @return * possible object is * {@link String } * */ public String getCarrierCode() { return carrierCode; } /** * Sets the value of the carrierCode property. * * @param value * allowed object is * {@link String } * */ public void setCarrierCode(String value) { this.carrierCode = value; } /** * Gets the value of the carrierName property. * * @return * possible object is * {@link String } * */ public String getCarrierName() { return carrierName; } /** * Sets the value of the carrierName property. * * @param value * allowed object is * {@link String } * */ public void setCarrierName(String value) { this.carrierName = value; } /** * Gets the value of the shippingMethod property. * * @return * possible object is * {@link String } * */ public String getShippingMethod() { return shippingMethod; } /** * Sets the value of the shippingMethod property. * * @param value * allowed object is * {@link String } * */ public void setShippingMethod(String value) { this.shippingMethod = value; } /** * Gets the value of the shipperTrackingNumber property. * * @return * possible object is * {@link String } * */ public String getShipperTrackingNumber() { return shipperTrackingNumber; } /** * Sets the value of the shipperTrackingNumber property. * * @param value * allowed object is * {@link String } * */ public void setShipperTrackingNumber(String value) { this.shipperTrackingNumber = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice> * &lt;element ref="{}AmazonOrderItemCode"/> * &lt;element ref="{}MerchantOrderItemID"/> * &lt;/choice> * &lt;element name="MerchantFulfillmentItemID" type="{}IDNumber" minOccurs="0"/> * &lt;element name="Quantity" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "amazonOrderItemCode", "merchantOrderItemID", "merchantFulfillmentItemID", "quantity" }) public static class Item { @XmlElement(name = "AmazonOrderItemCode") protected String amazonOrderItemCode; @XmlElement(name = "MerchantOrderItemID") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String merchantOrderItemID; @XmlElement(name = "MerchantFulfillmentItemID") protected BigInteger merchantFulfillmentItemID; @XmlElement(name = "Quantity") @XmlSchemaType(name = "positiveInteger") protected BigInteger quantity; /** * Gets the value of the amazonOrderItemCode property. * * @return * possible object is * {@link String } * */ public String getAmazonOrderItemCode() { return amazonOrderItemCode; } /** * Sets the value of the amazonOrderItemCode property. * * @param value * allowed object is * {@link String } * */ public void setAmazonOrderItemCode(String value) { this.amazonOrderItemCode = value; } /** * Gets the value of the merchantOrderItemID property. * * @return * possible object is * {@link String } * */ public String getMerchantOrderItemID() { return merchantOrderItemID; } /** * Sets the value of the merchantOrderItemID property. * * @param value * allowed object is * {@link String } * */ public void setMerchantOrderItemID(String value) { this.merchantOrderItemID = value; } /** * Gets the value of the merchantFulfillmentItemID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getMerchantFulfillmentItemID() { return merchantFulfillmentItemID; } /** * Sets the value of the merchantFulfillmentItemID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setMerchantFulfillmentItemID(BigInteger value) { this.merchantFulfillmentItemID = value; } /** * Gets the value of the quantity property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getQuantity() { return quantity; } /** * Sets the value of the quantity property. * * @param value * allowed object is * {@link BigInteger } * */ public void setQuantity(BigInteger value) { this.quantity = value; } } }
mit
dmpe/OOPaPrechod
src/ubung2001Aufgabe/Main.java
291
package ubung2001Aufgabe; public class Main { /** * @param args */ public static void main(String[] args) { Kirche a = new Kirche(50, 60); Disko b = new Disko (100); System.out.println(a.unterhaltungswer()); System.out.println(b.unterhaltungswer()); } }
mit
spockNinja/GhostGrader
src/objects/GhostStudent.java
1048
package objects; import java.util.Comparator; /** * Creates a 'ghost student' to help obfuscate real student grades * * @author Jesse W Milburn * @date 01 October, 2013 */ public class GhostStudent { private String pseudoName; /** * Constructs a ghost/fake student * * @param pn The false name assigned */ public GhostStudent(String pn) { pseudoName = pn; } /** * Fetches the false name assigned * * @return Name of the fake/ghost student */ public String getPseudoName() { return pseudoName; } /** * Allows for comparison/sorting based on the Students' PseudoNames * Simply pass this into Collections.sort() as the comparator */ public static Comparator<GhostStudent> PseudoNameComparator = new Comparator<GhostStudent>() { public int compare(GhostStudent s1, GhostStudent s2) { String psName1 = s1.getPseudoName().toUpperCase(); String psName2 = s2.getPseudoName().toUpperCase(); return psName1.compareTo(psName2); }; }; }
mit
alvachien/aclearning
languages_and_platforms/java/thinkinjava/00_lib/gui/GridLayout1.java
414
//: gui/GridLayout1.java // Demonstrates GridLayout. import javax.swing.*; import java.awt.*; import static net.mindview.util.SwingConsole.*; public class GridLayout1 extends JFrame { public GridLayout1() { setLayout(new GridLayout(7,3)); for(int i = 0; i < 20; i++) add(new JButton("Button " + i)); } public static void main(String[] args) { run(new GridLayout1(), 300, 300); } } ///:~
mit
Azure/azure-sdk-for-java
sdk/databoxedge/azure-resourcemanager-databoxedge/src/main/java/com/azure/resourcemanager/databoxedge/models/StorageAccounts.java
7071
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.databoxedge.models; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; /** Resource collection API of StorageAccounts. */ public interface StorageAccounts { /** * Lists all the storage accounts in a Data Box Edge/Data Box Gateway device. * * @param deviceName The device name. * @param resourceGroupName The resource group name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return collection of all the Storage Accounts on the Data Box Edge/Gateway device. */ PagedIterable<StorageAccount> listByDataBoxEdgeDevice(String deviceName, String resourceGroupName); /** * Lists all the storage accounts in a Data Box Edge/Data Box Gateway device. * * @param deviceName The device name. * @param resourceGroupName The resource group name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return collection of all the Storage Accounts on the Data Box Edge/Gateway device. */ PagedIterable<StorageAccount> listByDataBoxEdgeDevice(String deviceName, String resourceGroupName, Context context); /** * Gets a StorageAccount by name. * * @param deviceName The device name. * @param storageAccountName The storage account name. * @param resourceGroupName The resource group name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a StorageAccount by name. */ StorageAccount get(String deviceName, String storageAccountName, String resourceGroupName); /** * Gets a StorageAccount by name. * * @param deviceName The device name. * @param storageAccountName The storage account name. * @param resourceGroupName The resource group name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a StorageAccount by name. */ Response<StorageAccount> getWithResponse( String deviceName, String storageAccountName, String resourceGroupName, Context context); /** * Deletes the StorageAccount on the Data Box Edge/Data Box Gateway device. * * @param deviceName The device name. * @param storageAccountName The StorageAccount name. * @param resourceGroupName The resource group name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ void delete(String deviceName, String storageAccountName, String resourceGroupName); /** * Deletes the StorageAccount on the Data Box Edge/Data Box Gateway device. * * @param deviceName The device name. * @param storageAccountName The StorageAccount name. * @param resourceGroupName The resource group name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ void delete(String deviceName, String storageAccountName, String resourceGroupName, Context context); /** * Gets a StorageAccount by name. * * @param id the resource ID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a StorageAccount by name. */ StorageAccount getById(String id); /** * Gets a StorageAccount by name. * * @param id the resource ID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a StorageAccount by name. */ Response<StorageAccount> getByIdWithResponse(String id, Context context); /** * Deletes the StorageAccount on the Data Box Edge/Data Box Gateway device. * * @param id the resource ID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ void deleteById(String id); /** * Deletes the StorageAccount on the Data Box Edge/Data Box Gateway device. * * @param id the resource ID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ void deleteByIdWithResponse(String id, Context context); /** * Begins definition for a new StorageAccount resource. * * @param name resource name. * @return the first stage of the new StorageAccount definition. */ StorageAccount.DefinitionStages.Blank define(String name); }
mit
ArturoL-ES/jm2
api/src/main/java/com/arturo/jm2api/user/role/UserRole.java
2021
package com.arturo.jm2api.user.role; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.arturo.jm2api.user.User; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity @Table(name = "user_roles") public class UserRole implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", unique = true, nullable = false) private Integer id; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "username", nullable = false) @JsonBackReference private User user; @Column(name = "role", nullable = false, length = 45) private String role; public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } public String getRole() { return this.role; } public void setRole(String role) { this.role = role; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserRole)) return false; UserRole userRole = (UserRole) o; if (getId() != null ? !getId().equals(userRole.getId()) : userRole.getId() != null) return false; if (getUser() != null ? !getUser().equals(userRole.getUser()) : userRole.getUser() != null) return false; return getRole() != null ? getRole().equals(userRole.getRole()) : userRole.getRole() == null; } @Override public int hashCode() { int result = getId() != null ? getId().hashCode() : 0; result = 31 * result + (getUser() != null ? getUser().hashCode() : 0); result = 31 * result + (getRole() != null ? getRole().hashCode() : 0); return result; } }
mit
TechShroom/UnplannedDescent
ap/src/main/java/com/techshroom/unplanned/ap/ecs/plan/EntityPlan.java
1399
/* * This file is part of unplanned-descent, licensed under the MIT License (MIT). * * Copyright (c) TechShroom Studios <https://techshroom.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.techshroom.unplanned.ap.ecs.plan; /** * Marker for the class template of an entity plan. */ public @interface EntityPlan { }
mit
WeirdLionStudios/ProcWorld
src/wls/venio/procworld/ProcWorldMain.java
2999
package wls.venio.procworld; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Properties; import java.util.Random; import wls.venio.procworld.world.World; public class ProcWorldMain{ public static int worldWidth; public static int worldHeight; public static double scale; public static double seed; public static int numCities; public static int numNations; public static double minDistance; public static double allyProb; public static double enemyProb; public static double seaLevel; public static int lightDir; public static float shadowThickness; public static void main(String[] args){ ProcWorldMain main=new ProcWorldMain(); //Load config try{ main.loadConfig(); } catch(IOException e){ System.err.println("Unable to load config properly!"); System.exit(1); } if(seed==-1){ Random rand=new Random(); rand.setSeed(System.currentTimeMillis()); seed=rand.nextDouble()*1000; } System.out.println("seed="+seed); if(numCities<=numNations){ System.out.println("WTF!"); System.exit(0); } //Init world and generate World world=new World(numCities, numNations, allyProb, enemyProb, lightDir, shadowThickness, seaLevel, seed, minDistance); System.out.println("Starting world generation..."); world.generateWorld(worldWidth, worldHeight, scale); System.out.println("World generated!"); //Init graphics @SuppressWarnings("unused") GraphicRender render=new GraphicRender(worldWidth, worldHeight, world.geoMap); } /** * Load config file * @throws IOException */ private void loadConfig() throws IOException{ Properties prop = new Properties(); String propFileName = "procworld_config.properties"; InputStream inputStream =getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null){ prop.load(inputStream); } else{ throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } worldWidth=Integer.parseInt(prop.getProperty("world_width")); worldHeight=Integer.parseInt(prop.getProperty("world_height")); seed=Double.parseDouble(prop.getProperty("seed")); scale=Double.parseDouble(prop.getProperty("scale")); numCities=Integer.parseInt(prop.getProperty("num_cities")); numNations=Integer.parseInt(prop.getProperty("num_nations")); allyProb=Double.parseDouble(prop.getProperty("ally_prob")); enemyProb=Double.parseDouble(prop.getProperty("enemy_prob")); seaLevel=Double.parseDouble(prop.getProperty("sea_level")); lightDir=Integer.parseInt(prop.getProperty("light_dir")); shadowThickness=Float.parseFloat(prop.getProperty("shadow_thick")); minDistance=Float.parseFloat(prop.getProperty("min_point_distance")); } }
mit
ivelin1936/Studing-SoftUni-
Databases Frameworks - Hibernate & Spring Data - март 2018/Exercise Hibernate Code First - Entity Relations/P04 Hospital Database + console based user interface/src/main/java/service/commands/ICommandExecutor.java
246
package service.commands; import java.util.List; public interface ICommandExecutor<E, K> { E findById(Class<E> entityClass, K primaryKey); void remove(E entity); List<E> findAll(Class<E> entityClass); void save(E entity); }
mit
Chase-M/Slogo
src/command/TowardsCommand.java
891
package command; import java.util.List; import actor.Turtle; import parser.Node; import workspace.Workspace; public class TowardsCommand extends Command { public TowardsCommand (String s) { super(s, 2); } @Override public double execute (List<Node> inputs, Workspace workspace) throws Exception { double pointX = inputs.get(0).evaluate(workspace); double pointY = inputs.get(1).evaluate(workspace); double ans = 0; for (Turtle turtle : workspace.getActiveTurtles()) { double curX = turtle.getX(); double curY = turtle.getY(); double deltaX = pointX - curX; double deltaY = pointY - curY; double radians = Math.atan2(deltaY, deltaX); turtle.updatePosition(curX, curY, radians); ans = Math.toDegrees(radians); } return ans; } }
mit
valepresente/prop-e
prop-e/src/main/java/prop/engine/processors/observers/ExecuteOperationsObserver.java
357
package prop.engine.processors.observers; import prop.engine.PatchMessage; import prop.engine.PropOperation; import prop.engine.processors.PropProcessorObserver; import prop.engine.processors.ResultStatus; public interface ExecuteOperationsObserver extends PropProcessorObserver { ResultStatus execute(PatchMessage message, PropOperation operation); }
mit
kaetzacoatl/MusiXs-Bot
MusiXs-Bot/src/de/jojo/mb/KeyStore.java
150
package de.jojo.mb; public interface KeyStore { String proxer(); String youtube(); String username(); String password(); }
mit
roybailey/research-kafka
src/main/java/me/roybailey/springboot/kafka/KafkaSampleConsumer.java
784
package me.roybailey.springboot.kafka; import lombok.extern.slf4j.Slf4j; import org.springframework.kafka.annotation.KafkaListener; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; @Slf4j public class KafkaSampleConsumer { private LinkedBlockingQueue<String> events = new LinkedBlockingQueue<>(); @KafkaListener(topics = "helloworld.t") public void receiveMessage(String message) { log.info("received message='{}'", message); events.offer(message); } public String getMessage(int seconds) throws InterruptedException { log.info("polling for event"); String result = events.poll(seconds, TimeUnit.SECONDS); log.info("obtained event='{}'", result); return result; } }
mit
ykoziy/Design-Patterns-in-Java
Command/ComandDriver.java
768
/* * Command pattern encapsulates a request as an object. */ public class ComandDriver { public static void main(String[] args) { Player player = new Player(); //various commands as objects Command fire = new Fire(player); Command jump = new Jump(player); Command moveRight = new MoveRight(player); Action action = new Action(); char c = 'f'; switch(c) { case 'd': action.doAction(moveRight); break; case 'w': action.doAction(jump); break; case 'f': action.doAction(fire); break; default: } } }
mit
cliffano/swaggy-jenkins
clients/jaxrs-cxf-extended/generated/src/gen/java/org/openapitools/model/FavoriteImpl.java
2602
package org.openapitools.model; import org.openapitools.model.FavoriteImpllinks; import org.openapitools.model.PipelineImpl; import javax.validation.constraints.*; import javax.validation.Valid; import io.swagger.annotations.ApiModelProperty; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; public class FavoriteImpl { @ApiModelProperty(value = "") private String propertyClass; @ApiModelProperty(value = "") @Valid private FavoriteImpllinks links; @ApiModelProperty(value = "") @Valid private PipelineImpl item; /** * Get propertyClass * @return propertyClass */ @JsonProperty("_class") public String getPropertyClass() { return propertyClass; } /** * Sets the <code>propertyClass</code> property. */ public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } /** * Sets the <code>propertyClass</code> property. */ public FavoriteImpl propertyClass(String propertyClass) { this.propertyClass = propertyClass; return this; } /** * Get links * @return links */ @JsonProperty("_links") public FavoriteImpllinks getLinks() { return links; } /** * Sets the <code>links</code> property. */ public void setLinks(FavoriteImpllinks links) { this.links = links; } /** * Sets the <code>links</code> property. */ public FavoriteImpl links(FavoriteImpllinks links) { this.links = links; return this; } /** * Get item * @return item */ @JsonProperty("item") public PipelineImpl getItem() { return item; } /** * Sets the <code>item</code> property. */ public void setItem(PipelineImpl item) { this.item = item; } /** * Sets the <code>item</code> property. */ public FavoriteImpl item(PipelineImpl item) { this.item = item; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class FavoriteImpl {\n"); sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append(" links: ").append(toIndentedString(links)).append("\n"); sb.append(" item: ").append(toIndentedString(item)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private static String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
mit
eeveorg/GMSI
script/LRterminals/WordReturn.java
192
/* * Decompiled with CFR 0_119. */ package script.LRterminals; import script.Token; public class WordReturn extends Token { public WordReturn(Token old) { super(old); } }
mit
karim/adila
database/src/main/java/adila/db/shw2dm340s_shw2dm340s.java
241
// This file is automatically generated. package adila.db; /* * Samsung Galaxy M Style * * DEVICE: SHW-M340S * MODEL: SHW-M340S */ final class shw2dm340s_shw2dm340s { public static final String DATA = "Samsung|Galaxy M Style|"; }
mit
JabRef/jabref
src/test/java/org/jabref/model/groups/SearchGroupTest.java
2188
package org.jabref.model.groups; import java.util.EnumSet; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.search.rules.SearchRules; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class SearchGroupTest { @Test public void containsFindsWordWithRegularExpression() { SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "anyfield=rev*", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); BibEntry entry = new BibEntry(); entry.addKeyword("review", ','); assertTrue(group.contains(entry)); } @Test public void containsDoesNotFindsWordWithInvalidRegularExpression() { SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "anyfield=*rev*", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); BibEntry entry = new BibEntry(); entry.addKeyword("review", ','); assertFalse(group.contains(entry)); } @Test public void notQueryWorksWithLeftPartOfQuery() { SearchGroup groupToBeClassified = new SearchGroup("to-be-classified", GroupHierarchyType.INDEPENDENT, "NOT(groups=alpha) AND NOT(groups=beta)", EnumSet.noneOf(SearchRules.SearchFlags.class)); BibEntry alphaEntry = new BibEntry() .withCitationKey("alpha") .withField(StandardField.GROUPS, "alpha"); assertFalse(groupToBeClassified.contains(alphaEntry)); } @Test public void notQueryWorksWithLRightPartOfQuery() { SearchGroup groupToBeClassified = new SearchGroup("to-be-classified", GroupHierarchyType.INDEPENDENT, "NOT(groups=alpha) AND NOT(groups=beta)", EnumSet.noneOf(SearchRules.SearchFlags.class)); BibEntry betaEntry = new BibEntry() .withCitationKey("beta") .withField(StandardField.GROUPS, "beta"); assertFalse(groupToBeClassified.contains(betaEntry)); } }
mit
ftsuda82/tads4-lojinha-2016
lojinha-common/src/main/java/br/senac/tads/dsw/lojinha/common/entity/Produto.java
6483
/* * The MIT License * * Copyright 2016 Fernando. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package br.senac.tads.dsw.lojinha.common.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Fernando */ @Entity @Table(name = "TB_PRODUTO") @NamedQueries({ @NamedQuery(name = "Produto.listar", query = "SELECT DISTINCT p FROM Produto p " + "LEFT JOIN FETCH p.categorias " + "LEFT JOIN FETCH p.imagens"), @NamedQuery(name = "Produto.listarPorCategoria", query = "SELECT DISTINCT p FROM Produto p " + "LEFT JOIN FETCH p.categorias " + "LEFT JOIN FETCH p.imagens " + "INNER JOIN p.categorias c " + "WHERE c.id = :iCategoria"), @NamedQuery(name = "Produto.obter", query = "SELECT DISTINCT p FROM Produto p " + "LEFT JOIN FETCH p.categorias " + "LEFT JOIN FETCH p.imagens " + "WHERE p.id = :idProduto") }) @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Produto implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_PRODUTO") private Long id; @Column(name = "NM_PRODUTO", nullable = false) private String nome; @Column(name = "DS_PRODUTO") private String descricao; @Column(name = "VL_PRODUTO", precision = 12, scale = 2, nullable = false) private BigDecimal preco; @Column(name = "DT_CADASTRO", nullable = false) @Temporal(TemporalType.TIMESTAMP) @XmlTransient private Date dtCadastro; @ManyToMany @JoinTable(name = "TB_PRODUTO_CATEGORIA", joinColumns = { @JoinColumn(name = "ID_PRODUTO") }, inverseJoinColumns = { @JoinColumn(name = "ID_CATEGORIA") }) @XmlTransient private List<Categoria> categorias; @OneToMany(mappedBy = "produto") @XmlTransient private List<ImagemProduto> imagens; @Transient @XmlTransient private List<ItemCompra> itensCompra; public Produto() { } public Produto(Long id, String nome, String descricao, BigDecimal preco, Date dtCadastro) { this.id = id; this.nome = nome; this.descricao = descricao; this.preco = preco; this.dtCadastro = dtCadastro; } public Produto(Long id, String nome, String descricao, BigDecimal preco, Date dtCadastro, List<ImagemProduto> imagens, List<Categoria> categorias) { this.id = id; this.nome = nome; this.descricao = descricao; this.preco = preco; this.dtCadastro = dtCadastro; this.imagens = imagens; this.categorias = categorias; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public BigDecimal getPreco() { return preco; } public void setPreco(BigDecimal preco) { this.preco = preco; } public Date getDtCadastro() { return dtCadastro; } public void setDtCadastro(Date dtCadastro) { this.dtCadastro = dtCadastro; } public List<Categoria> getCategorias() { return categorias; } public void setCategorias(List<Categoria> categorias) { this.categorias = categorias; } public List<ImagemProduto> getImagens() { return imagens; } public void setImagens(List<ImagemProduto> imagens) { this.imagens = imagens; } public List<ItemCompra> getItensCompra() { return itensCompra; } public void setItensCompra(List<ItemCompra> itensCompra) { this.itensCompra = itensCompra; } @Override public String toString() { return "Produto{" + "id=" + id + ", nome=" + nome + ", descricao=" + descricao + ", preco=" + preco + ", dtCadastro=" + dtCadastro + ", categorias=" + categorias + ", imagens=" + imagens + '}'; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Produto other = (Produto) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } }
mit
onlychoice/ganger
src/main/java/com/netease/automate/exception/ProcessLaunchedException.java
362
package com.netease.automate.exception; /** * Exception thrown when a process has been launched. * * @author jiaozhihui@corp.netease.com */ public class ProcessLaunchedException extends Exception { private static final long serialVersionUID = 1723476836348967412L; public ProcessLaunchedException(String message) { super(message); } }
mit
joepjoosten/XSL-tester
test/ApplicationTest.java
1082
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import models.Fiddle; import org.codehaus.jackson.JsonNode; import org.junit.*; import play.mvc.*; import play.test.*; import play.data.DynamicForm; import play.data.validation.ValidationError; import play.data.validation.Constraints.RequiredValidator; import play.i18n.Lang; import play.libs.F; import play.libs.F.*; import static play.test.Helpers.*; import static org.fest.assertions.Assertions.*; /** * * Simple (JUnit) tests that can call all parts of a play app. * If you are interested in mocking a whole application, see the wiki for more details. * */ public class ApplicationTest { // @Test // public void renderTemplate() { // Content html = views.html.index.render(""); // assertThat(contentType(html)).isEqualTo("text/html"); // } // // @Test // public void shortenedIds() { // assertThat(Fiddle.encodeShortenedID(0)).isEqualTo("211111"); // assertThat(Fiddle.decodeShortenedID("211111")).isEqualTo(0); // } }
mit
sidoh/reactor_simulator
src/main/java/org/sidoh/reactor_simulator/service/SimulatorResource.java
1528
package org.sidoh.reactor_simulator.service; import org.sidoh.reactor_simulator.simulator.BigReactorSimulator; import org.sidoh.reactor_simulator.simulator.FakeReactorWorld; import org.sidoh.reactor_simulator.simulator.ReactorDefinition; import org.sidoh.reactor_simulator.simulator.ReactorResult; import restx.annotations.GET; import restx.annotations.RestxResource; import restx.factory.Component; import restx.security.PermitAll; @Component @RestxResource public class SimulatorResource { @PermitAll @GET("/simulate") public ReactorResult simulate(ReactorDefinition definition) { SimulatorServer.validateReactorDefinition(definition); BigReactorSimulator simulator = new BigReactorSimulator( definition.isActivelyCooled(), SimulatorServer.MAX_NUMBER_OF_TICKS ); FakeReactorWorld fakeReactorWorld = FakeReactorWorld.makeReactor( definition.getLayout(), definition.getxSize(), definition.getzSize(), definition.getHeight(), definition.getControlRodInsertion() ); ReactorResult rawResult = simulator.simulate(fakeReactorWorld); return new ReactorResult() .setCoolantTemperature(rawResult.coolantTemperature) .setFuelConsumption(rawResult.fuelConsumption) // for display purposes .setFuelFertility(rawResult.fuelFertility * 100) .setFuelHeat(rawResult.fuelHeat) .setOutput(rawResult.output) .setReactorDefinition(definition) .setReactorHeat(rawResult.reactorHeat); } }
mit
eduardodaluz/xfire
xfire-aegis/src/test/org/codehaus/xfire/client/ConcatClientTest.java
2006
package org.codehaus.xfire.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import org.codehaus.xfire.aegis.AbstractXFireAegisTest; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.invoker.BeanInvoker; import org.codehaus.xfire.transport.local.LocalTransport; public class ConcatClientTest extends AbstractXFireAegisTest { public void testDynamicClient() throws Exception { Service s = getServiceFactory().create(ConcatService.class); s.setInvoker(new BeanInvoker(new ConcatService() { public String concat(String s1, String s2) { return s1 + s2; } public String concat(String s1, String s2, String s3) { return s1 + s2 + s3; } public void noconcat(String s1, String s2) { } })); getServiceRegistry().register(s); ByteArrayOutputStream bos = new ByteArrayOutputStream(); s.getWSDLWriter().write(bos); Client client = new Client(new ByteArrayInputStream(bos.toByteArray()), null); client.setXFire(getXFire()); client.setUrl("xfire.local://ConcatService"); client.setTransport(getTransportManager().getTransport(LocalTransport.BINDING_ID)); Object[] res = client.invoke("concat", new Object[]{"1", "2"}); assertEquals("12", res[0]); res = client.invoke("concat1", new Object[]{"1", "2", "3"}); assertEquals("123", res[0]); res = client.invoke("noconcat", new Object[] {"a", "b"}); assertEquals(0, res.length); } public static interface ConcatService { String concat(String s1, String s2); String concat(String s1, String s2, String s3); void noconcat(String s1, String s2); } }
mit
MinecraftPortCentral/GriefPrevention
src/main/java/me/ryanhamshire/griefprevention/task/WelcomeTask.java
5129
/* * This file is part of GriefPrevention, licensed under the MIT License (MIT). * * Copyright (c) Ryan Hamshire * Copyright (c) bloodmc * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package me.ryanhamshire.griefprevention.task; import org.spongepowered.api.entity.living.player.Player; public class WelcomeTask implements Runnable { private final Player player; public WelcomeTask(Player player) { this.player = player; } @Override public void run() { // abort if player has logged out since this task was scheduled if (!this.player.isOnline()) { return; } // offer advice and a helpful link /*GriefPreventionPlugin.sendMessage(player, TextMode.Instr, Messages.AvoidGriefClaimLand); GriefPreventionPlugin.sendMessage(player, TextMode.Instr, Messages.SurvivalBasicsVideo2); // give the player a reference book for later if (GriefPreventionPlugin.getActiveConfig(player.getWorld().getProperties()).getConfig().claim.deliverManuals) { ItemStack.Builder factory = Sponge.getGame().getRegistry().createBuilder(ItemStack.Builder.class); DataStore datastore = GriefPreventionPlugin.instance.dataStore; final ItemStack itemStack = factory.itemType(ItemTypes.WRITTEN_BOOK).quantity(1).build(); final AuthorData authorData = itemStack.getOrCreate(AuthorData.class).get(); authorData.set(Keys.BOOK_AUTHOR, Text.of(datastore.getMessage(Messages.BookAuthor))); itemStack.offer(authorData); final DisplayNameData displayNameData = itemStack.getOrCreate(DisplayNameData.class).get(); displayNameData.set(Keys.DISPLAY_NAME, Text.of(datastore.getMessage(Messages.BookTitle))); displayNameData.set(Keys.CUSTOM_NAME_VISIBLE, true); itemStack.offer(displayNameData); StringBuilder page1 = new StringBuilder(); String URL = datastore.getMessage(Messages.BookLink, DataStore.SURVIVAL_VIDEO_URL_RAW); String intro = datastore.getMessage(Messages.BookIntro); page1.append(URL).append("\n\n"); page1.append(intro).append("\n\n"); String editToolName = GriefPreventionPlugin.instance.modificationTool.getId().replace('_', ' ') .toLowerCase(); String infoToolName = GriefPreventionPlugin.instance.investigationTool.getId().replace('_', ' ') .toLowerCase(); String configClaimTools = datastore.getMessage(Messages.BookTools, editToolName, infoToolName); page1.append(configClaimTools); if (GriefPreventionPlugin.getActiveConfig(player.getWorld().getProperties()).getConfig().claim.claimRadius < 0) { page1.append(datastore.getMessage(Messages.BookDisabledChestClaims)); } StringBuilder page2 = new StringBuilder(datastore.getMessage(Messages.BookUsefulCommands)).append("\n\n"); page2.append("/Trust /UnTrust /TrustList\n"); page2.append("/ClaimsList\n"); page2.append("/AbandonClaim\n\n"); page2.append("/IgnorePlayer\n\n"); page2.append("/SubdivideClaims\n"); page2.append("/AccessTrust\n"); page2.append("/ContainerTrust\n"); //page2.append("/PermissionTrust"); try { final Text page2Text = SpongeTexts.fromLegacy(page2.toString()); final Text page1Text = SpongeTexts.fromLegacy(page1.toString()); final PagedData pagedData = itemStack.getOrCreate(PagedData.class).get(); pagedData.set(pagedData.pages().add(page1Text).add(page2Text)); itemStack.offer(pagedData); } catch (Exception e) { e.printStackTrace(); } ((EntityPlayer) player).inventory.addItemStackToInventory((net.minecraft.item.ItemStack) (Object) itemStack.copy()); }*/ } }
mit
Eluinhost/UHC
src/main/java/gg/uhc/uhc/modules/death/DeathStandsModule.java
10404
/* * Project: UHC * Class: gg.uhc.uhc.modules.death.DeathStandsModule * * The MIT License (MIT) * * Copyright (c) 2015 Graham Howden <graham_howden1 at yahoo.co.uk>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package gg.uhc.uhc.modules.death; import gg.uhc.uhc.modules.DisableableModule; import gg.uhc.uhc.modules.ModuleRegistry; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Maps; import org.bukkit.*; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerArmorStandManipulateEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.metadata.MetadataValue; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.EulerAngle; import org.bukkit.util.Vector; import java.util.EnumMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class DeathStandsModule extends DisableableModule implements Listener { protected static final int DEATH_ANIMATION_TIME = 18; protected static final int TICKS_PER_SECOND = 20; protected static final double PLAYER_VELOCITY_MULTIPLIER = 1.5D; protected static final double PLAYER_VELOICY_Y_ADDITIONAL = .2D; protected static final Predicate<ItemStack> EMPTY_ITEM = new Predicate<ItemStack>() { @Override public boolean apply(ItemStack input) { return input == null || input.getType() == Material.AIR; } }; protected static final String ICON_NAME = "Death armour stands"; protected static final String STAND_PREFIX = ChatColor.RED + "RIP: " + ChatColor.RESET; public DeathStandsModule() { setId("DeathStands"); this.iconName = ICON_NAME; this.icon.setType(Material.ARMOR_STAND); this.icon.setWeight(ModuleRegistry.CATEGORY_DEATH); } protected boolean isProtectedArmourStand(Entity entity) { final String customName = entity.getCustomName(); return customName != null && customName.startsWith(STAND_PREFIX); } @SuppressWarnings("Duplicates") protected Map<EquipmentSlot, ItemStack> getItems(ArmorStand stand) { final Map<EquipmentSlot, ItemStack> slots = Maps.newHashMapWithExpectedSize(5); slots.put(EquipmentSlot.HAND, stand.getItemInHand()); slots.put(EquipmentSlot.HEAD, stand.getHelmet()); slots.put(EquipmentSlot.CHEST, stand.getChestplate()); slots.put(EquipmentSlot.LEGS, stand.getLeggings()); slots.put(EquipmentSlot.FEET, stand.getBoots()); return slots; } @SuppressWarnings("Duplicates") protected Map<EquipmentSlot, ItemStack> getItems(PlayerInventory inventory) { final Map<EquipmentSlot, ItemStack> slots = Maps.newHashMapWithExpectedSize(5); slots.put(EquipmentSlot.HAND, inventory.getItemInHand()); slots.put(EquipmentSlot.HEAD, inventory.getHelmet()); slots.put(EquipmentSlot.CHEST, inventory.getChestplate()); slots.put(EquipmentSlot.LEGS, inventory.getLeggings()); slots.put(EquipmentSlot.FEET, inventory.getBoots()); return slots; } protected EnumMap<EquipmentSlot, ItemStack> getSavedSlots(Player player) { for (final MetadataValue value : player.getMetadata(StandItemsMetadata.KEY)) { if (!(value instanceof StandItemsMetadata)) continue; // remove the metadata player.removeMetadata(StandItemsMetadata.KEY, value.getOwningPlugin()); // return the map return ((StandItemsMetadata) value).value(); } return Maps.newEnumMap(EquipmentSlot.class); } protected void removeFirstEquals(Iterable iterable, Object equal) { final Iterator iterator = iterable.iterator(); while (iterator.hasNext()) { if (iterator.next().equals(equal)) { iterator.remove(); return; } } } // run at high so previous events can modify the drops before we do (HeadDrops) @EventHandler(priority = EventPriority.HIGH) public void on(PlayerDeathEvent event) { if (!isEnabled()) return; final Player player = event.getEntity(); // make the player invisible for the duration of their death animation player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, DEATH_ANIMATION_TIME, 1)); final Location location = player.getLocation(); // create an armour stand at the player final ArmorStand stand = player.getWorld().spawn(location.clone().add(0, .2D, 0), ArmorStand.class); stand.setBasePlate(false); stand.setArms(true); // give the armour stand the death message as a name stand.setCustomName(STAND_PREFIX + event.getDeathMessage()); stand.setCustomNameVisible(true); // face the same direction as the player stand.getLocation().setDirection(location.getDirection()); // set the armour stand helmet to be looking at the same yaw stand.setHeadPose(new EulerAngle(Math.toRadians(location.getPitch()), 0, 0)); // use the player's velocity as a base and apply it to the stand stand.setVelocity( player.getVelocity() .clone() .multiply(PLAYER_VELOCITY_MULTIPLIER) .add(new Vector(0D, PLAYER_VELOICY_Y_ADDITIONAL, 0D)) ); // start with player's existing items in each slot (if exists) Map<EquipmentSlot, ItemStack> toSet = getItems(player.getInventory()); // overide with any saved items in the metadata toSet.putAll(getSavedSlots(player)); // filter out the invalid items toSet = Maps.filterValues(toSet, Predicates.not(EMPTY_ITEM)); final List<ItemStack> drops = event.getDrops(); for (final Map.Entry<EquipmentSlot, ItemStack> entry : toSet.entrySet()) { final ItemStack stack = entry.getValue(); if (stack == null) continue; // remove the first matching stack in the drop list removeFirstEquals(drops, stack); // set the item on the armour stand in the correct slot switch (entry.getKey()) { case HAND: stand.setItemInHand(stack); break; case HEAD: stand.setHelmet(stack); break; case CHEST: stand.setChestplate(stack); break; case LEGS: stand.setLeggings(stack); break; case FEET: stand.setBoots(stack); break; default: } } } @EventHandler public void on(PlayerArmorStandManipulateEvent event) { final ArmorStand stand = event.getRightClicked(); if (!isProtectedArmourStand(stand)) return; final ItemStack players = event.getPlayerItem(); final ItemStack stands = event.getArmorStandItem(); // if the player is holding something it will be a swap if (players == null || players.getType() != Material.AIR) return; // if the stand hasn't got something then the player is adding // items or nothing will happen if (stands == null || stands.getType() == Material.AIR) return; // they're removing an item from the armour stand. If there // is only 1 item on the stand then this is the final item // on the armour stand so kill it (fire optional) if (Maps.filterValues(getItems(stand), Predicates.not(EMPTY_ITEM)).values().size() == 1) { stand.remove(); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void on(EntityDamageEvent event) { if (event.getEntityType() != EntityType.ARMOR_STAND) return; if (!isProtectedArmourStand(event.getEntity())) return; // always cancel events, we choose when to break the stand event.setCancelled(true); final ArmorStand stand = (ArmorStand) event.getEntity(); final Location loc = stand.getLocation(); final World world = stand.getWorld(); // for the first 2 seconds don't allow breaking // to avoid accidental breaks after kill if (event.getEntity().getTicksLived() < 2 * TICKS_PER_SECOND) { world.playEffect(stand.getEyeLocation(), Effect.WITCH_MAGIC, 0); return; } // drop each of it's worn items for (final ItemStack stack : Maps.filterValues(getItems(stand), Predicates.not(EMPTY_ITEM)).values()) { world.dropItemNaturally(loc, stack); } // kill the stand now stand.remove(); } @Override protected boolean isEnabledByDefault() { return true; } }
mit
thanhpd/BeMan
app/src/main/java/com/uet/beman/support/SentenceNodeListAdapter.java
1597
package com.uet.beman.support; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.uet.beman.R; import com.uet.beman.object.SentenceNode; import java.util.List; /** * Created by thanhpd on 3/15/2015. */ public class SentenceNodeListAdapter extends ArrayAdapter<SentenceNode> { public SentenceNodeListAdapter (Context context, int textViewResourceId) { super(context, textViewResourceId); } public SentenceNodeListAdapter (Context context, int resource, List<SentenceNode> items) { super(context, resource, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if(v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.itemlistrow, null); } SentenceNode p = getItem(position); if(p != null) { TextView tt = (TextView) v.findViewById(R.id.id); // TextView tt1 = (TextView) v.findViewById(R.id.categoryId); TextView tt3 = (TextView) v.findViewById(R.id.description); if (tt != null) { tt.setText(p.getSendTime()); } // if (tt1 != null) { // // tt1.setText(p.getMessageId()); // } if (tt3 != null) { tt3.setText(p.getMessage()); } } return v; } }
mit
zhoujiagen/giant-data-analysis
data-models/datamodel-logic/src/main/java/com/spike/giantdataanalysis/model/logic/relational/expression/raw/SqlStatement.java
381
package com.spike.giantdataanalysis.model.logic.relational.expression.raw; /** * 关系代数语句表达式: * * <pre> sqlStatement : ddlStatement | dmlStatement | transactionStatement | replicationStatement | preparedStatement | administrationStatement | utilityStatement ; * </pre> */ public interface SqlStatement extends RelationalAlgebraExpression { }
mit
rzwitserloot/ivyplusplus
src/com/zwitserloot/ivyplusplus/ecj/CompileJobResult.java
955
/********************************************************************** * Copyright (c) 2005-2009 ant4eclipse project team. * * 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: * Nils Hartmann, Daniel Kasmeroglu, Gerd Wuetherich **********************************************************************/ package com.zwitserloot.ivyplusplus.ecj; import org.eclipse.jdt.core.compiler.CategorizedProblem; import java.io.File; import java.util.Map; /** * The {@link CompileJobResult} represents a compile job result. * * @author Gerd W&uuml;therich (gerd@gerd-wuetherich.de) */ public interface CompileJobResult { boolean succeeded(); CategorizedProblem[] getCategorizedProblems(); Map<String, File> getCompiledClassFiles(); }
mit
kevintweber/kimpachi
src/main/java/com/kevintweber/kimpachi/board/Group.java
5305
package com.kevintweber.kimpachi.board; import com.kevintweber.kimpachi.exception.UnconnectedException; import lombok.EqualsAndHashCode; import lombok.NonNull; import org.jgrapht.Graph; import org.jgrapht.alg.connectivity.ConnectivityInspector; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; import java.util.HashSet; import java.util.Set; /** * A Group is a set of connected points. * <p> * There is no such thing as an empty group. * <p> * This class exists in order to handle a group of points that lives and dies together. */ @EqualsAndHashCode public final class Group implements Points, Printable { private final PointSet pointSet; private Group(@NonNull Point point) { this.pointSet = PointSet.of(point); } private Group(@NonNull Set<Point> points) { if (points.isEmpty()) { throw new IllegalArgumentException("Group must not be empty."); } this.pointSet = PointSet.of(points); checkConnected(); } public static Group of(@NonNull Point point) { return new Group(point); } public static Group of(@NonNull Set<Point> points) { return new Group(points); } public static Group copyOf(@NonNull Group otherGroup) { return new Group(otherGroup.getPoints()); } private void checkConnected() { if (pointSet.size() <= 1) { return; } Graph<Point, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class); for (Point point : pointSet.getPoints()) { graph.addVertex(point); for (Point addedPoint : graph.vertexSet()) { if (point.isAdjacent(addedPoint)) { graph.addEdge(point, addedPoint); } } } ConnectivityInspector<Point, DefaultEdge> connectivityInspector = new ConnectivityInspector<>(graph); if (!connectivityInspector.isConnected()) { throw new UnconnectedException("Not all points are connected."); } } @Override public boolean contains(@NonNull Point point) { return pointSet.contains(point); } public Group enlarge() { Set<Point> enlargedGroupPoints = new HashSet<>(getPoints()); for (Point point : getPoints()) { enlargedGroupPoints.addAll(enlargePoint(point)); } return Group.of(enlargedGroupPoints); } public Group enlarge(int count) { if (count < 1) { throw new IllegalArgumentException("Invalid enlargement count: " + count); } Group startingGroup = Group.copyOf(this); for (int i = 0; i < count; i++) { Group enlargedGroup = startingGroup.enlarge(); if (enlargedGroup.equals(startingGroup)) { return enlargedGroup; } startingGroup = Group.copyOf(enlargedGroup); } return startingGroup; } private Set<Point> enlargePoint(Point point) { Set<Point> enlargedGroup = new HashSet<>(); enlargedGroup.add(point); enlargedGroup.addAll(point.getNeighboringPoints()); return enlargedGroup; } @Override public Set<Point> getPoints() { return pointSet.getPoints(); } @Override public Set<Point> getNeighboringPoints() { return pointSet.getNeighboringPoints(); } @Override public boolean isAdjacent(@NonNull Point point) { return pointSet.isAdjacent(point); } @Override public boolean isEmpty() { return false; } @Override public boolean isIntersecting(@NonNull Points otherGroup) { return pointSet.isIntersecting(otherGroup); } @Override public int size() { return pointSet.size(); } public Group with(@NonNull Point point) { if (contains(point)) { return this; } if (!isAdjacent(point)) { throw new UnconnectedException("Point is non-adjacent: " + point); } Set<Point> enlargedGroup = new HashSet<>(pointSet.getPoints()); enlargedGroup.add(point); return new Group(enlargedGroup); } @Override public String print() { Komi komi = Komi.KOMI; StringBuilder sb = new StringBuilder(" "); for (int i = 0; i < 19; i++) { sb.append(Board.positionCharacters.charAt(i)); sb.append(" "); } sb.append("\n"); for (int y = 19; y >= 1; y--) { sb.append(y); sb.append(" "); if (y < 10) { sb.append(" "); } for (int x = 1; x <= 19; x++) { Point point = Point.of(x, y); if (contains(point)) { sb.append("# "); } else { if (komi.isKomi(point)) { sb.append("+ "); } else { sb.append(". "); } } } sb.append("\n"); } return sb.toString(); } @Override public String toString() { return "Group(" + "points=" + pointSet.getPoints().toString() + ')'; } }
mit
angeldevil/ChatImageView
app/src/main/java/me/angeldeivl/chatimageview/MainActivity.java
341
package me.angeldeivl.chatimageview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
mit
RocketChat/Rocket.Chat.Java.SDK
rocketchat-core/src/main/java/com/rocketchat/core/callback/LoginCallback.java
371
package com.rocketchat.core.callback; import com.rocketchat.common.listener.Callback; import com.rocketchat.core.model.Token; /** * Created by sachin on 18/7/17. */ public interface LoginCallback extends Callback { /** * Called when the Login was successful. The callback may proceed to read the {@link Token} */ void onLoginSuccess(Token token); }
mit
aherbert/GDSC-Analytics
src/test/java/uk/ac/sussex/gdsc/analytics/parameters/ProtocolSpecificationTest.java
2479
/*- * #%L * Genome Damage and Stability Centre Analytics Package * * The GDSC Analytics package contains code to use the Google Analytics * Measurement protocol to collect usage information from a Java application. * %% * Copyright (C) 2016 - 2020 Alex Herbert * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ package uk.ac.sussex.gdsc.analytics.parameters; import java.util.HashSet; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings("javadoc") class ProtocolSpecificationTest { @Test void testIsSupported() { // This never gets hit by the code but we should check it works Assertions.assertFalse(ProtocolSpecification.PROTOCOL_VERSION.isSupported(null)); for (final HitType ht : HitType.values()) { Assertions.assertTrue(ProtocolSpecification.PROTOCOL_VERSION.isSupported(ht)); Assertions.assertEquals(ht == HitType.EVENT, ProtocolSpecification.EVENT_ACTION.isSupported(ht)); } } @Test void testGetMaxLength() { // Just check there are different values final HashSet<Integer> set = new HashSet<>(); for (final ProtocolSpecification spec : ProtocolSpecification.values()) { final int max = spec.getMaxLength(); if (spec.getValueType() != ValueType.TEXT) { Assertions.assertEquals(0, max); } set.add(max); } Assertions.assertTrue(set.size() > 1, "All max lengths are the same"); } }
mit
vrk-kpa/xroad-catalog
xroad-catalog-persistence/src/main/java/fi/vrk/xroad/catalog/persistence/repository/MemberRepository.java
3358
/** * The MIT License * Copyright (c) 2022, Population Register Centre (VRK) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fi.vrk.xroad.catalog.persistence.repository; import fi.vrk.xroad.catalog.persistence.entity.Member; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.time.LocalDateTime; import java.util.Set; /** * Basic CRUD for member */ public interface MemberRepository extends CrudRepository<Member, Long> { @EntityGraph(value = "member.full-tree.graph", type = EntityGraph.EntityGraphType.FETCH) Set<Member> findAll(); @EntityGraph(value = "member.full-tree.graph", type = EntityGraph.EntityGraphType.FETCH) @Query("SELECT m FROM Member m WHERE m.statusInfo.removed IS NULL") Set<Member> findAllActive(); @Query("SELECT m FROM Member m WHERE m.memberClass = :memberClass") Set<Member> findAllByClass(@Param("memberClass") String memberClass); // uses named query Member.findAllChangedSince Set<Member> findAllChangedSince(@Param("since") LocalDateTime since); // uses named query Member.findActiveChangedSince Set<Member> findActiveChangedSince(@Param("since") LocalDateTime since); /** * Returns only active items (non-deleted) * @param xRoadInstance X-Road instance parameter, for example FI * @param memberClass X-Road member class, for example GOF * @param memberCode X-Road member class, for example Company code * @return Member found */ @Query("SELECT m FROM Member m WHERE m.xRoadInstance = :xRoadInstance " + "AND m.memberClass = :memberClass " + "AND m.memberCode = :memberCode " + "AND m.statusInfo.removed IS NULL") Member findActiveByNaturalKey(@Param("xRoadInstance") String xRoadInstance, @Param("memberClass") String memberClass, @Param("memberCode") String memberCode); @Query(value = "SELECT 1", nativeQuery = true) Integer checkConnection(); @Query(value = "SELECT MAX(fetched) FROM member", nativeQuery = true) LocalDateTime findLatestFetched(); }
mit
jaxkodex/app
src/main/java/org/educando/app/controller/UsuarioApiController.java
854
package org.educando.app.controller; import org.educando.app.model.Usuario; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UsuarioApiController { @RequestMapping(value="/api/me", method=RequestMethod.GET) public @ResponseBody Usuario getUsuario () { Usuario usuario = null; if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof Usuario) { usuario = (Usuario) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } return usuario; } }
mit
souliss/soulissapp
SoulissApp/src/main/java/it/angelic/soulissclient/T15RGBIrActivity.java
8774
package it.angelic.soulissclient; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Looper; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import java.util.List; import it.angelic.soulissclient.helpers.AlertDialogHelper; import it.angelic.soulissclient.model.SoulissNode; import it.angelic.soulissclient.model.SoulissTypical; import it.angelic.soulissclient.model.db.SoulissDBHelper; import it.angelic.soulissclient.model.typicals.SoulissTypical15; import it.angelic.soulissclient.net.UDPHelper; import static it.angelic.soulissclient.Constants.TAG; import static junit.framework.Assert.assertTrue; public class T15RGBIrActivity extends AbstractStatusedFragmentActivity { private SoulissTypical collected; @Override protected void onCreate(Bundle savedInstanceState) { // tema if (opzioni.isLightThemeSelected()) setTheme(R.style.LightThemeSelector); else setTheme(R.style.DarkThemeSelector); super.onCreate(savedInstanceState); setContentView(R.layout.main_t15_irrgb); if (!opzioni.isDbConfigured()) { AlertDialogHelper.dbNotInitedDialog(this); } Button buttPlus = (Button) findViewById(R.id.buttonPlus); Button buttMinus = (Button) findViewById(R.id.buttonMinus); Button btOff = (Button) findViewById(R.id.buttonTurnOff); Button btOn = (Button) findViewById(R.id.buttonTurnOn); Button btWhite = (Button) findViewById(R.id.white); Button btFlash = (Button) findViewById(R.id.flash); Button btFade = (Button) findViewById(R.id.fade); Button btShoot = (Button) findViewById(R.id.smooth); Button btStrobo = (Button) findViewById(R.id.strobe); Button btRed = (Button) findViewById(R.id.red); Button btRed2 = (Button) findViewById(R.id.red2); Button btRed3 = (Button) findViewById(R.id.red3); Button btRed4 = (Button) findViewById(R.id.red4); Button btRed5 = (Button) findViewById(R.id.red5); Button btGreen = (Button) findViewById(R.id.green); Button btGreen2 = (Button) findViewById(R.id.green2); Button btGreen3 = (Button) findViewById(R.id.green3); Button btGreen4 = (Button) findViewById(R.id.green4); Button btGreen5 = (Button) findViewById(R.id.green5); Button btBlu = (Button) findViewById(R.id.blue); Button btBlu2 = (Button) findViewById(R.id.blue2); Button btBlu3 = (Button) findViewById(R.id.blue3); Button btBlu4 = (Button) findViewById(R.id.blue4); Button btBlu5 = (Button) findViewById(R.id.blue5); btOff.setTag(Constants.Typicals.Souliss_T1n_RGB_OffCmd); btOn.setTag(Constants.Typicals.Souliss_T1n_RGB_OnCmd); buttPlus.setTag(Constants.Typicals.Souliss_T_IrCom_RGB_bright_up); buttMinus.setTag(Constants.Typicals.Souliss_T_IrCom_RGB_bright_down); btWhite.setTag(Constants.Typicals.Souliss_T1n_RGB_W); btFlash.setTag(Constants.Typicals.Souliss_T_IrCom_RGB_mode_flash); btFade.setTag(Constants.Typicals.Souliss_T_IrCom_RGB_mode_fade); btShoot.setTag(Constants.Typicals.Souliss_T_IrCom_RGB_mode_smooth); btStrobo.setTag(Constants.Typicals.Souliss_T_IrCom_RGB_mode_strobe); btRed.setTag(Constants.Typicals.Souliss_T1n_RGB_R); btRed2.setTag(Constants.Typicals.Souliss_T1n_RGB_R2); btRed3.setTag(Constants.Typicals.Souliss_T1n_RGB_R3); btRed4.setTag(Constants.Typicals.Souliss_T1n_RGB_R4); btRed5.setTag(Constants.Typicals.Souliss_T1n_RGB_R5); btGreen.setTag(Constants.Typicals.Souliss_T1n_RGB_G); btGreen2.setTag(Constants.Typicals.Souliss_T1n_RGB_G2); btGreen3.setTag(Constants.Typicals.Souliss_T1n_RGB_G3); btGreen4.setTag(Constants.Typicals.Souliss_T1n_RGB_G4); btGreen5.setTag(Constants.Typicals.Souliss_T1n_RGB_G5); btBlu.setTag(Constants.Typicals.Souliss_T1n_RGB_B); btBlu2.setTag(Constants.Typicals.Souliss_T1n_RGB_B2); btBlu3.setTag(Constants.Typicals.Souliss_T1n_RGB_B3); btBlu4.setTag(Constants.Typicals.Souliss_T1n_RGB_B4); btBlu5.setTag(Constants.Typicals.Souliss_T1n_RGB_B5); SoulissDBHelper datasource = new SoulissDBHelper(this); SoulissDBHelper.open(); Bundle extras = getIntent().getExtras(); collected = (SoulissTypical15) extras.get("TIPICO"); assertTrue("TIPICO NULLO", collected instanceof SoulissTypical15); OnClickListener plus = new OnClickListener() { public void onClick(View v) { Short cmd = (Short) v.getTag(); assertTrue(cmd != null); issueIrCommand(cmd); } }; buttPlus.setOnClickListener(plus); buttMinus.setOnClickListener(plus); btOff.setOnClickListener(plus); btOn.setOnClickListener(plus); btWhite.setOnClickListener(plus); btFlash.setOnClickListener(plus); btFade.setOnClickListener(plus); btShoot.setOnClickListener(plus); btStrobo.setOnClickListener(plus); btRed.setOnClickListener(plus); btRed2.setOnClickListener(plus); btRed3.setOnClickListener(plus); btRed4.setOnClickListener(plus); btRed5.setOnClickListener(plus); btGreen.setOnClickListener(plus); btGreen2.setOnClickListener(plus); btGreen3.setOnClickListener(plus); btGreen4.setOnClickListener(plus); btGreen5.setOnClickListener(plus); btBlu.setOnClickListener(plus); btBlu2.setOnClickListener(plus); btBlu3.setOnClickListener(plus); btBlu4.setOnClickListener(plus); btBlu5.setOnClickListener(plus); // upcast // Integer status = // Integer.valueOf(collected.getTypicalDTO().getOutput()); } @Override protected void onStart() { super.onStart(); setActionBarInfo(collected.getNiceName()); // final ToggleButton tog = (ToggleButton) // findViewById(R.id.toggleButton1); this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); if (opzioni.isAnimationsEnabled()) overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); SoulissDBHelper.open(); IntentFilter filtere = new IntentFilter(); filtere.addAction("it.angelic.soulissclient.GOT_DATA"); registerReceiver(datareceiver, filtere); } @Override protected void onPause() { super.onPause(); unregisterReceiver(datareceiver); } /************************************************************************** * Souliss RGB light command Souliss OUTPUT Data is: * * * INPUT data 'read' from GUI **************************************************************************/ void issueIrCommand(final short val) { Thread t = new Thread() { public void run() { Looper.prepare(); UDPHelper.issueSoulissCommand("" + collected.getParentNode().getNodeId(), "" + collected.getTypicalDTO().getSlot(), opzioni, "" + val); } }; t.start(); return; } // Aggiorna il feedback private BroadcastReceiver datareceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { SoulissNode coll = collected.getParentNode(); Bundle extras = intent.getExtras(); Bundle vers = (Bundle) extras.get("NODES"); Log.d(TAG, "Detected data arrival: " + vers.size() + " nodes"); int howmany = extras.getInt("quantity"); // SoulissNode[] numversioni = new SoulissNode[(int) howmany]; int temp = howmany - 1; while (temp >= 0) { SoulissNode temrp = (SoulissNode) vers.getSerializable("" + temp); temp--; if (coll.getNodeId() == temrp.getNodeId()) { // rinfresca padre coll.setHealth(temrp.getHealth()); coll.setRefreshedAt(temrp.getRefreshedAt()); List<SoulissTypical> tips = temrp.getTypicals(); for (SoulissTypical soulissTypical : tips) { if (soulissTypical.getSlot() == collected.getSlot()) { collected = soulissTypical; // collected.getTypicalDTO().setOutput(soulissTypical.getTypicalDTO().getOutput()); // collected.getTypicalDTO().setRefreshedAt(soulissTypical.getTypicalDTO().getRefreshedAt()); Log.i(Constants.TAG, "RGB data refreshed"); // TODO setta gli spinner } }// ciclo tipici } }// ciclo nodi } }; }
mit
matija94/show-me-the-code
java/Android-projects/BeatBox/app/src/main/java/android/matija/com/beatbox/Sound.java
699
package android.matija.com.beatbox; /** * Created by matija on 26.2.17.. */ public class Sound { private String mAssetPath; private String mName; private Integer mSoundId; public Sound(String assetPath) { mAssetPath = assetPath; String[] components = assetPath.split("/"); String fileName = components[components.length-1]; mName = fileName.replace(".wav", ""); } public String getAssetPath() { return mAssetPath; } public String getName() { return mName; } public Integer getSoundId() { return mSoundId; } public void setSoundId(Integer soundId) { mSoundId = soundId; } }
mit
arnosthavelka/spring-advanced-training
sat-core/src/main/java/com/github/aha/sat/core/testing/profile/RichardConfig.java
424
package com.github.aha.sat.core.testing.profile; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import com.github.aha.sat.core.config.User; @Configuration @Profile("richard") public class RichardConfig { @Bean public User user() { return new User("Richard"); } }
mit
EntitypediaGames/games-framework-client
src/main/java/org/entitypedia/games/gameframework/client/GamesFrameworkClient.java
15222
package org.entitypedia.games.gameframework.client; import com.fasterxml.jackson.core.type.TypeReference; import org.entitypedia.games.common.client.GamesCommonClient; import org.entitypedia.games.common.model.ResultsPage; import org.entitypedia.games.gameframework.common.api.*; import org.entitypedia.games.gameframework.common.model.*; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @author <a href="http://autayeu.com/">Aliaksandr Autayeu</a> */ public class GamesFrameworkClient extends GamesCommonClient implements IGamesFrameworkClient { private static final TypeReference<Player> PLAYER_TYPE_REFERENCE = new TypeReference<Player>() { }; private static final TypeReference<ResultsPage<Player>> PLAYERS_RP_TYPE_REFERENCE = new TypeReference<ResultsPage<Player>>() { }; private static final TypeReference<Clue> CLUE_TYPE_REFERENCE = new TypeReference<Clue>() { }; private static final TypeReference<Word> WORD_TYPE_REFERENCE = new TypeReference<Word>() { }; private static final TypeReference<ResultsPage<Word>> WORDS_RP_TYPE_REFERENCE = new TypeReference<ResultsPage<Word>>() { }; private static final TypeReference<ResultsPage<Clue>> CLUES_RP_TYPE_REFERENCE = new TypeReference<ResultsPage<Clue>>() { }; private static final TypeReference<Feedback> FEEDBACK_TYPE_REFERENCE = new TypeReference<Feedback>() { }; private static final TypeReference<ClueTemplate> CLUE_TEMPLATE_TYPE_REFERENCE = new TypeReference<ClueTemplate>() { }; private static final TypeReference<ResultsPage<ClueTemplate>> CLUE_TEMPLATES_RP_TYPE_REFERENCE = new TypeReference<ResultsPage<ClueTemplate>>() { }; private static final TypeReference<Developer> DEVELOPER_TYPE_REFERENCE = new TypeReference<Developer>() { }; private static final TypeReference<ResultsPage<Developer>> DEVELOPERS_RP_TYPE_REFERENCE = new TypeReference<ResultsPage<Developer>>() { }; private static final TypeReference<Game> GAME_TYPE_REFERENCE = new TypeReference<Game>() { }; private static final TypeReference<ResultsPage<Game>> GAMES_RP_TYPE_REFERENCE = new TypeReference<ResultsPage<Game>>() { }; private static final String DEFAULT_API_ENDPOINT = "http://games.entitypedia.org/"; private static final String SECURE_API_ENDPOINT = "https://games.entitypedia.org/"; public GamesFrameworkClient(String uid, String password) { super(getDefaultAPIEndPoint(), uid, password); } public GamesFrameworkClient(String uid, String password, Boolean secure) { super(getSecureAPIEndPoint(), uid, password); } public GamesFrameworkClient(String uid, String password, String token, String tokenSecret) { super(getDefaultAPIEndPoint(), uid, password, token, tokenSecret); } public GamesFrameworkClient(String uid, String password, String token, String tokenSecret, Boolean secure) { super(getSecureAPIEndPoint(), uid, password, token, tokenSecret); } @Override public void login() { doEmptyGet(apiEndpoint + IPlayerAPI.LOGIN_PLAYER); } @Override public Player loginFacebook(String token) { return doPostRead(apiEndpoint + IPlayerAPI.LOGIN_FACEBOOK_PLAYER + "?token=" + token, PLAYER_TYPE_REFERENCE); } @Override public Player loginGPlus(String code) { return doPostRead(apiEndpoint + IPlayerAPI.LOGIN_GPLUS_PLAYER + "?code=" + code, PLAYER_TYPE_REFERENCE); } @Override public void activateEmail(String code) { doSimplePost(apiEndpoint + IPlayerAPI.ACTIVATE_PLAYER_EMAIL + "?code=" + code); } @Override public void requestEmailActivation() { doSimplePost(apiEndpoint + IPlayerAPI.REQUEST_PLAYER_EMAIL_ACTIVATION); } @Override public void resetPassword(String code, String password) { doSimplePost(apiEndpoint + IPlayerAPI.RESET_PLAYER_PASSWORD + "?code=" + code + "&password=" + encodeURL(password)); } @Override public void requestPasswordReset(String email) { doSimplePost(apiEndpoint + IPlayerAPI.REQUEST_PLAYER_PASSWORD_RESET + "?email=" + encodeURL(email)); } @Override public Player createPlayer(Player player) { return doPostReadObject(apiEndpoint + IPlayerAPI.CREATE_PLAYER, player, PLAYER_TYPE_REFERENCE); } @Override public Player readPlayer(String playerID) { return doSimpleGet(apiEndpoint + IPlayerAPI.READ_PLAYER.replaceAll("\\{.*\\}", playerID), PLAYER_TYPE_REFERENCE); } @Override public Player readPlayer(long playerID) { return doSimpleGet(apiEndpoint + IPlayerAPI.READ_PLAYER.replaceAll("\\{.*\\}", Long.toString(playerID)), PLAYER_TYPE_REFERENCE); } @Override public void deletePlayer(long playerID) { doSimplePost(apiEndpoint + IPlayerAPI.DELETE_PLAYER + "?playerID=" + Long.toString(playerID)); } @Override public void updatePlayer(Player player) { doPostObject(apiEndpoint + IPlayerAPI.UPDATE_PLAYER, player); } @Override public void updatePlayerPassword(long playerID, String password) { doSimplePost(apiEndpoint + IPlayerAPI.UPDATE_PLAYER_PASSWORD + "?playerID=" + Long.toString(playerID) + "&password=" + encodeURL(password)); } @Override public void updatePlayerEmail(long playerID, String email) { doSimplePost(apiEndpoint + IPlayerAPI.UPDATE_PLAYER_EMAIL + "?playerID=" + Long.toString(playerID) + "&email=" + encodeURL(email)); } @Override public void updatePlayerFirstName(long playerID, String firstName) { doSimplePost(apiEndpoint + IPlayerAPI.UPDATE_PLAYER_FIRST_NAME + "?playerID=" + Long.toString(playerID) + "&firstName=" + encodeURL(firstName)); } @Override public void updatePlayerLastName(long playerID, String lastName) { doSimplePost(apiEndpoint + IPlayerAPI.UPDATE_PLAYER_LAST_NAME + "?playerID=" + Long.toString(playerID) + "&lastName=" + encodeURL(lastName)); } @Override public void updatePlayerFacebook(long playerID, String token) { doSimplePost(apiEndpoint + IPlayerAPI.UPDATE_PLAYER_FACEBOOK + "?playerID=" + Long.toString(playerID) + "&token=" + encodeURL(token)); } @Override public void updatePlayerGPlus(long playerID, String code) { doSimplePost(apiEndpoint + IPlayerAPI.UPDATE_PLAYER_GPLUS + "?playerID=" + Long.toString(playerID) + "&code=" + encodeURL(code)); } @Override public ResultsPage<Player> listPlayers(Integer pageSize, Integer pageNo) { return doSimpleGet(addPageSizeAndNo(apiEndpoint + IPlayerAPI.LIST_PLAYERS + "?", pageSize, pageNo), PLAYERS_RP_TYPE_REFERENCE); } @Override public Clue readClue(long clueID) { return doSimpleGet(apiEndpoint + IClueAPI.READ_CLUE.replaceAll("\\{.*\\}", Long.toString(clueID)), CLUE_TYPE_REFERENCE); } @Override public ResultsPage<Clue> listClues(Integer pageSize, Integer pageNo, String filter, String order) { return doSimpleGet(addPageSizeAndNoAndFilterAndOrder(apiEndpoint + IClueAPI.LIST_CLUES, pageSize, pageNo, encodeURL(filter), order), CLUES_RP_TYPE_REFERENCE); } @Override public Word readWord(long wordID) { return doSimpleGet(apiEndpoint + IWordAPI.READ_WORD.replaceAll("\\{.*\\}", Long.toString(wordID)), WORD_TYPE_REFERENCE); } @Override public ResultsPage<Word> listWords(Integer pageSize, Integer pageNo, String filter, String order) { return doSimpleGet(addPageSizeAndNoAndFilterAndOrder(apiEndpoint + IWordAPI.LIST_WORDS, pageSize, pageNo, encodeURL(filter), order), WORDS_RP_TYPE_REFERENCE); } @Override public Feedback createFeedback(long clueID) { return doPostRead(apiEndpoint + IFeedbackAPI.CREATE_FEEDBACK + "?clueID=" + Long.toString(clueID), FEEDBACK_TYPE_REFERENCE); } @Override public void postFeedback(long feedbackID, int attributePosition, String attributeValue, String comment) { String url = apiEndpoint + IFeedbackAPI.POST_FEEDBACK + "?feedbackID=" + Long.toString(feedbackID) + "&attributePosition=" + Integer.toString(attributePosition); if (null != attributeValue) { url = url + "&attributeValue=" + encodeURL(attributeValue); } if (null != comment) { url = url + "&comment=" + encodeURL(comment); } doSimplePost(url); } @Override public void cancelFeedback(long feedbackID) { doSimplePost(apiEndpoint + IFeedbackAPI.CANCEL_FEEDBACK + "?feedbackID=" + Long.toString(feedbackID)); } @Override public void confirmClue(long clueID, double confidence) { doSimplePost(apiEndpoint + IFeedbackAPI.CONFIRM_CLUE + "?clueID=" + Long.toString(clueID) + "&confidence=" + Double.toString(confidence)); } @Override public ClueTemplate readClueTemplate(long clueTemplateID) { return doSimpleGet(apiEndpoint + IClueTemplateAPI.READ_CLUE_TEMPLATE.replaceAll("\\{.*\\}", Long.toString(clueTemplateID)), CLUE_TEMPLATE_TYPE_REFERENCE); } @Override public ResultsPage<ClueTemplate> listClueTemplates(Integer pageSize, Integer pageNo, String filter, String order) { return doSimpleGet(addPageSizeAndNoAndFilterAndOrder(apiEndpoint + IClueTemplateAPI.LIST_CLUE_TEMPLATES, pageSize, pageNo, encodeURL(filter), order), CLUE_TEMPLATES_RP_TYPE_REFERENCE); } @Override public void loginDeveloper() { doEmptyGet(apiEndpoint + IDeveloperAPI.LOGIN_DEVELOPER); } @Override public Developer readDeveloper(long developerID) { return doSimpleGet(apiEndpoint + IDeveloperAPI.READ_DEVELOPER.replaceAll("\\{.*\\}", Long.toString(developerID)), DEVELOPER_TYPE_REFERENCE); } @Override public void resetDeveloperPassword(String code, String password) { doSimplePost(apiEndpoint + IDeveloperAPI.RESET_DEVELOPER_PASSWORD + "?code=" + code + "&password=" + encodeURL(password)); } @Override public void requestDeveloperPasswordReset(String email) { doSimplePost(apiEndpoint + IDeveloperAPI.REQUEST_DEVELOPER_PASSWORD_RESET + "?email=" + encodeURL(email)); } @Override public void updateDeveloperPassword(long developerID, String password) { doSimplePost(apiEndpoint + IDeveloperAPI.UPDATE_DEVELOPER_PASSWORD + "?developerID=" + Long.toString(developerID) + "&password=" + encodeURL(password)); } @Override public void updateDeveloperEmail(long developerID, String email) { doSimplePost(apiEndpoint + IDeveloperAPI.UPDATE_DEVELOPER_EMAIL + "?developerID=" + Long.toString(developerID) + "&email=" + encodeURL(email)); } @Override public void updateDeveloperFirstName(long developerID, String firstName) { doSimplePost(apiEndpoint + IDeveloperAPI.UPDATE_DEVELOPER_FIRST_NAME + "?developerID=" + Long.toString(developerID) + "&firstName=" + encodeURL(firstName)); } @Override public void updateDeveloperLastName(long developerID, String lastName) { doSimplePost(apiEndpoint + IDeveloperAPI.UPDATE_DEVELOPER_LAST_NAME + "?developerID=" + Long.toString(developerID) + "&lastName=" + encodeURL(lastName)); } @Override public ResultsPage<Developer> listDevelopers(Integer pageSize, Integer pageNo, String filter, String order) { return doSimpleGet(addPageSizeAndNoAndFilterAndOrder(apiEndpoint + IDeveloperAPI.LIST_DEVELOPERS, pageSize, pageNo, encodeURL(filter), order), DEVELOPERS_RP_TYPE_REFERENCE); } @Override public Game createGame() { return doPostRead(apiEndpoint + IGameAPI.CREATE_GAME, GAME_TYPE_REFERENCE); } @Override public Game readGame(long gameID) { return doSimpleGet(apiEndpoint + IGameAPI.READ_GAME.replaceAll("\\{.*\\}", Long.toString(gameID)), GAME_TYPE_REFERENCE); } @Override public void updateGameTitle(long gameID, String title) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_TITLE + "?gameID=" + Long.toString(gameID) + "&title=" + encodeURL(title)); } @Override public void updateGameDescription(long gameID, String description) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_DESCRIPTION + "?gameID=" + Long.toString(gameID) + "&description=" + encodeURL(description)); } @Override public void updateGameURL(long gameID, String url) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_URL + "?gameID=" + Long.toString(gameID) + "&url=" + encodeURL(url)); } @Override public void updateGameLogoURL(long gameID, String url) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_LOGO_URL + "?gameID=" + Long.toString(gameID) + "&url=" + encodeURL(url)); } @Override public void updateGameSliderURL(long gameID, String url) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_SLIDER_URL + "?gameID=" + Long.toString(gameID) + "&url=" + encodeURL(url)); } @Override public void updateGameOAuthCallbackURL(long gameID, String url) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_OAUTH_CALLBACK_URL + "?gameID=" + Long.toString(gameID) + "&url=" + encodeURL(url)); } @Override public void updateGameOAuthSecret(long gameID, String secret) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_OAUTH_SECRET + "?gameID=" + Long.toString(gameID) + "&secret=" + encodeURL(secret)); } @Override public void updateGameProduction(long gameID, boolean production) { doSimplePost(apiEndpoint + IGameAPI.UPDATE_GAME_PRODUCTION + "?gameID=" + Long.toString(gameID) + "&production=" + Boolean.toString(production)); } @Override public void deleteGame(long gameID) { doSimplePost(apiEndpoint + IGameAPI.DELETE_GAME + "?gameID=" + Long.toString(gameID)); } @Override public ResultsPage<Game> listGames(Integer pageSize, Integer pageNo) { return doSimpleGet(addPageSizeAndNo(apiEndpoint + IGameAPI.LIST_GAMES + "?", pageSize, pageNo), GAMES_RP_TYPE_REFERENCE); } private static String getDefaultAPIEndPoint() { return getResourcePropertiesString("gameframework.root", DEFAULT_API_ENDPOINT) + "webapi/"; } private static String getSecureAPIEndPoint() { return getResourcePropertiesString("gameframework.secure.root", SECURE_API_ENDPOINT) + "webapi/"; } private static String getResourcePropertiesString(String key, String defaultValue) { InputStream propStream = GamesFrameworkClient.class.getClassLoader().getResourceAsStream("games-framework.properties"); String result = defaultValue; if (null != propStream) { Properties props = new Properties(); try { props.load(propStream); result = props.getProperty(key); } catch (IOException e) { // nop } } return result; } }
mit
agentspace/Agent-Space-in-Java
Robot Allen v AgentSpace/AgentSpace Architecture lib/wrl/java/util/StringComparator.java
347
package wrl.java.util; /** * DOCUMENT ME! * * @author $author$ * @version $Revision: 1.2 $ * * (c) 2004 MicroStep-MIS www.microstep-mis.com */ public class StringComparator implements Comparator { public int compare (Object obj1, Object obj2) { String s1 = (String) obj1; String s2 = (String) obj2; return s1.compareTo(s2); } }
mit
Cornutum/tcases
tcases-io/src/main/java/org/cornutum/tcases/io/SystemTestJsonReader.java
2262
////////////////////////////////////////////////////////////////////////////// // // Copyright 2019, Cornutum Project // www.cornutum.org // ////////////////////////////////////////////////////////////////////////////// package org.cornutum.tcases.io; import org.cornutum.tcases.SystemTestDef; import org.apache.commons.io.IOUtils; import org.leadpony.justify.api.JsonSchema; import org.leadpony.justify.api.JsonValidationService; import org.leadpony.justify.api.ProblemHandler; import java.io.Closeable; import java.io.InputStream; import javax.json.JsonObject; import javax.json.JsonReader; /** * An {@link ISystemTestSource} that reads from an JSON document. * */ public class SystemTestJsonReader implements ISystemTestSource, Closeable { /** * Creates a new SystemTestJsonReader object. */ public SystemTestJsonReader() { this( null); } /** * Creates a new SystemTestJsonReader object. */ public SystemTestJsonReader( InputStream stream) { setInputStream( stream); } /** * Returns a {@link SystemTestDef} instance. */ @Override public SystemTestDef getSystemTestDef() { JsonValidationService service = JsonValidationService.newInstance(); JsonSchema schema = service.readSchema( getClass().getResourceAsStream( "/schema/system-test-schema.json")); ProblemHandler handler = ProblemHandler.throwing(); try( JsonReader reader = service.createReader( stream_, schema, handler)) { JsonObject json; try { json = reader.readObject(); } catch( Exception e) { throw new SystemTestException( "Invalid system test definition", e); } return SystemTestJson.asSystemTestDef( json); } } /** * Changes the input stream for this reader. */ public void setInputStream( InputStream stream) { stream_ = stream==null ? System.in : stream; } /** * Returns the input stream for this reader. */ protected InputStream getInputStream() { return stream_; } @Override public void close() { IOUtils.closeQuietly( getInputStream(), null); } private InputStream stream_; }
mit
github/codeql
java/ql/test/stubs/springframework-5.3.8/org/springframework/beans/PropertyValues.java
1232
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.springframework.beans; import java.util.Iterator; import java.util.Spliterator; import java.util.stream.Stream; public interface PropertyValues extends Iterable<PropertyValue> { @Override default Iterator<PropertyValue> iterator() { return null; } @Override default Spliterator<PropertyValue> spliterator() { return null; } default Stream<PropertyValue> stream() { return null; } PropertyValue[] getPropertyValues(); PropertyValue getPropertyValue(String propertyName); PropertyValues changesSince(PropertyValues old); boolean contains(String propertyName); boolean isEmpty(); }
mit
softwarespot/weight-watchers
src/main/java/com/softala/bean/Message.java
603
package com.softala.bean; /** * @author SoftwareSpot */ public class Message { private int status; private String message; /** * Constructor * * @param status * Status value * @param message * Message string */ public Message(int status, String message) { super(); this.status = status; this.message = message; } public String getMessage() { return message; } public int getStatus() { return status; } public void setMessage(String message) { this.message = message; } public void setStatus(int status) { this.status = status; } }
mit
FunDevelopment/funlang
src/fun/lang/Continuation.java
606
/* Fun Compiler and Runtime Engine * Continuation.java * * Copyright (c) 2017 by Fun Development * All rights reserved. */ package fun.lang; /** * A Continuation is thrown by a Fun <code>continue</code> statement. This transfers * the current construction of the page to a different definition. */ public class Continuation extends Throwable { private static final long serialVersionUID = 1L; String location; public Continuation(String location) { super(); this.location = location; } public String getLocation() { return location; } }
mit
yysoft/yy-auth
auth-dashboard/src/main/java/net/caiban/auth/dashboard/dao/auth/impl/AuthRightDaoImpl.java
2470
/** * Copyright 2011 ASTO. * All right reserved. * Created on 2011-5-5 */ package net.caiban.auth.dashboard.dao.auth.impl; import java.util.List; import net.caiban.auth.dashboard.dao.BaseDao; import net.caiban.auth.dashboard.dao.auth.AuthRightDao; import net.caiban.auth.dashboard.domain.auth.AuthRight; import org.springframework.stereotype.Component; /** * @author mays (mays@zz91.com) * * created on 2011-5-5 */ @Component("authRightDao") public class AuthRightDaoImpl extends BaseDao implements AuthRightDao { final static String SQL_PREFIX = "authRight"; @Override public Integer countChild(String parentCode) { return (Integer) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "countChild"), parentCode); } @Override public Integer createRight(AuthRight right) { return null; } @Override public Integer deleteRightByCode(String code) { return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteRightByCode"), code); } @SuppressWarnings("unchecked") @Override public List<AuthRight> queryChild(String parentCode) { return getSqlMapClientTemplate().queryForList(buildId(SQL_PREFIX, "queryChild"), parentCode); } @Override public String queryMaxCodeOfChild(String parentCode) { return (String) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryMaxCodeOfChild"), parentCode); } @Override public Integer updateRight(AuthRight right) { return getSqlMapClientTemplate().update(buildId(SQL_PREFIX, "updateRight"), right); } @Override public AuthRight queryOneRight(String code){ return (AuthRight) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryOneRight"), code); } @Override public Integer insertRight(AuthRight right) { return (Integer) getSqlMapClientTemplate().insert(buildId(SQL_PREFIX, "insertRight"), right); } @Override public Integer deleteDeptRight(String code) { return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteDeptRight"), code); } @Override public Integer deleteRoleRight(String code) { return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "deleteRoleRight"), code); } @Override public Integer queryIdByCode(String code) { return getSqlMapClientTemplate().delete(buildId(SQL_PREFIX, "queryIdByCode"), code); } @Override public String queryNameByCode(String code) { return (String) getSqlMapClientTemplate().queryForObject(buildId(SQL_PREFIX, "queryNameByCode"), code); } }
mit
itohiro73/playground
java/jpa-simple/src/main/java/jp/itohiro/playground/jpa/LocalDateTimeToTimestampConverter.java
531
package jp.itohiro.playground.jpa; import javax.persistence.AttributeConverter; import java.sql.Timestamp; import java.time.LocalDateTime; public class LocalDateTimeToTimestampConverter implements AttributeConverter<LocalDateTime, Timestamp> { @Override public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) { return Timestamp.valueOf(localDateTime); } @Override public LocalDateTime convertToEntityAttribute(Timestamp timestamp) { return timestamp.toLocalDateTime(); } }
mit
Arckenver/MightyLoot
src/main/java/com/arckenver/mightyloot/cmdexecutor/FindExecutor.java
2581
package com.arckenver.mightyloot.cmdexecutor; import java.util.ArrayList; import java.util.Iterator; import java.util.Optional; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.Text.Builder; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import com.arckenver.mightyloot.DataHandler; import com.arckenver.mightyloot.LanguageHandler; import com.arckenver.mightyloot.object.Loot; public class FindExecutor implements CommandExecutor { public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException { Optional<World> optWorld = ctx.<World> getOne("world"); World world; Player player = null; if (optWorld.isPresent()) { world = optWorld.get(); } else { if (src instanceof Player) { player = (Player) src; world = player.getWorld(); } else { src.sendMessage(Text.of(TextColors.RED, LanguageHandler.get("AA"))); return CommandResult.success(); } } ArrayList<Loot> loots = DataHandler.getLoots(world.getUniqueId()); if (loots == null || loots.isEmpty()) { src.sendMessage(Text.of(TextColors.RED, LanguageHandler.get("AC"))); return CommandResult.success(); } String[] s = LanguageHandler.get("AB").split("\\{POS\\}"); Builder builder = Text.builder(); builder.append(Text.of(TextColors.GOLD, (s.length > 0) ? s[0] : "")); Iterator<Loot> iter = loots.iterator(); while (iter.hasNext()) { Location<World> loc = iter.next().getLoc(); builder.append(Text .builder(loc.getBlockX() + " " + loc.getBlockY() + " " + loc.getBlockZ()) .color(TextColors.YELLOW) .onClick(TextActions.runCommand("/tp " + ((player != null) ? player.getName() : "") + " " + loc.getBlockX() + " " + loc.getBlockY() + " " + loc.getBlockZ())) .build()); if (iter.hasNext()) { builder.append(Text.of(TextColors.GOLD, ", ")); } } builder.append(Text.of(TextColors.GOLD, (s.length > 1) ? s[1] : "")); builder.append(Text.of(TextColors.DARK_GRAY, " <- " + LanguageHandler.get("DD"))); src.sendMessage(builder.build()); return CommandResult.success(); } }
mit
bhatti/PlexServices
plexsvc-framework/src/test/java/com/plexobject/handler/ws/performance/PriceType.java
92
package com.plexobject.handler.ws.performance; public enum PriceType { LIMIT, MARKET }
mit
JCThePants/NucleusFramework
src/com/jcwhatever/nucleus/internal/managed/items/meta/ItemLore.java
3364
/* * This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.nucleus.internal.managed.items.meta; import com.jcwhatever.nucleus.managed.items.meta.IItemMetaHandler; import com.jcwhatever.nucleus.managed.items.meta.ItemMetaValue; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.utils.items.ItemStackUtils; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; /** * Handles {@link org.bukkit.inventory.ItemStack} lore meta. * * @see InternalItemMetaHandlers */ class ItemLore implements IItemMetaHandler { @Override public String getMetaName() { return "lore"; } @Override public boolean canHandle(ItemStack itemStack) { PreCon.notNull(itemStack); ItemMeta meta = itemStack.getItemMeta(); return meta != null && meta.hasLore(); } @Override public boolean apply(ItemStack itemStack, ItemMetaValue meta) { PreCon.notNull(itemStack); PreCon.notNull(meta); if (!meta.getName().equals(getMetaName())) return false; List<String> currentLore = ItemStackUtils.getLore(itemStack); List<String> newLore = currentLore == null ? new ArrayList<String>(5) : new ArrayList<String>(currentLore.size() + 1); if (currentLore != null) { for (String lore : currentLore) { newLore.add(lore); } } newLore.add(meta.getRawData()); ItemStackUtils.setLore(itemStack, newLore); return true; } @Override public List<ItemMetaValue> getMeta(ItemStack itemStack) { PreCon.notNull(itemStack); ItemMeta meta = itemStack.getItemMeta(); if (meta == null) return new ArrayList<>(0); List<String> lore = meta.getLore(); if (lore == null || lore.isEmpty()) return new ArrayList<>(0); List<ItemMetaValue> result = new ArrayList<>(1); for (String line : lore) { result.add(new ItemMetaValue(getMetaName(), line)); } return result; } }
mit
venson999/EasyFTP
src/test/java/com/venson/easyftp/AbstractFTPClientTest.java
30862
package com.venson.easyftp; import java.lang.reflect.Method; import junit.framework.Assert; import org.apache.commons.net.ftp.FTPClient; import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.venson.easyftp.AbstractFTPClient; import com.venson.easyftp.FTPFileInfoVO; /** * The test class of AbstractFTPClient. * * @author venson */ @RunWith(PowerMockRunner.class) @PrepareForTest({ FTPClient.class }) public class AbstractFTPClientTest { /** * When input URL is null, NullException is expected. */ @Test public void testConvertFTPUrlToVO001() { // =================== Before =================== // =================== Input =================== String url = null; // =================== Process =================== Exception result = null; FTPFileInfoVO resultVO = null; try { resultVO = AbstractFTPClient.convertFTPUrlToVO(url); } catch (Exception e) { result = e; } // =================== Output =================== Assert.assertEquals(true, result instanceof NullPointerException); Assert.assertEquals(null, resultVO); // =================== After =================== } /** * When input URL is empty string, IllegalArgumentException is expected. */ @Test public void testConvertFTPUrlToVO002() { // =================== Before =================== // =================== Input =================== String url = ""; // =================== Process =================== Exception result = null; FTPFileInfoVO resultVO = null; try { resultVO = AbstractFTPClient.convertFTPUrlToVO(url); } catch (Exception e) { result = e; } // =================== Output =================== Assert.assertEquals(true, result instanceof IllegalArgumentException); Assert.assertEquals(null, resultVO); // =================== After =================== } /** * When input URL format is invalid, IllegalArgumentException is expected. */ @Test public void testConvertFTPUrlToVO003() { // =================== Before =================== // =================== Input =================== String url = "AAA"; // =================== Process =================== Exception result = null; FTPFileInfoVO resultVO = null; try { resultVO = AbstractFTPClient.convertFTPUrlToVO(url); } catch (Exception e) { result = e; } // =================== Output =================== Assert.assertEquals(true, result instanceof IllegalArgumentException); Assert.assertEquals(null, resultVO); // =================== After =================== } /** * When input URL is valid, and port is not specified, success is expected. */ @Test public void testConvertFTPUrlToVO004() { // =================== Before =================== // =================== Input =================== String url = "ftp://username:password@192.168.19.251/ftp/cmdfile/04_VOD_20110411093958_001047556.xml"; // =================== Process =================== FTPFileInfoVO result = AbstractFTPClient.convertFTPUrlToVO(url); // =================== Output =================== Assert.assertEquals("username", result.getUserName()); Assert.assertEquals("password", result.getPassword()); Assert.assertEquals("192.168.19.251", result.getIp()); Assert.assertEquals(null, result.getPort()); Assert.assertEquals("ftp://username:password@192.168.19.251/ftp/cmdfile/04_VOD_20110411093958_001047556.xml", result.getUrl()); Assert.assertEquals("/ftp/cmdfile/04_VOD_20110411093958_001047556.xml", result.getFileFullPath()); Assert.assertEquals("/ftp/cmdfile", result.getFileDirectory()); Assert.assertEquals("04_VOD_20110411093958_001047556.xml", result.getFileName()); // =================== After =================== } /** * When input URL is valid, and file name is specified, and parent directory is not specified, * success is expected. */ @Test public void testConvertFTPUrlToVO005() { // =================== Before =================== // =================== Input =================== String url = "ftp://username:password@192.168.19.251:20/04_VOD_20110411093958_001047556.xml"; // =================== Process =================== FTPFileInfoVO result = AbstractFTPClient.convertFTPUrlToVO(url); // =================== Output =================== Assert.assertEquals(null, result.getFileDirectory()); Assert.assertEquals("/04_VOD_20110411093958_001047556.xml", result.getFileName()); Assert.assertEquals("/04_VOD_20110411093958_001047556.xml", result.getFileFullPath()); // =================== After =================== } /** * When input URL valid, and port is specified, success is expected. */ @Test public void testConvertFTPUrlToVO006() { // =================== Before =================== // =================== Input =================== String url = "ftp://username:password@192.168.19.251:20/ftp/cmdfile/04_VOD_20110411093958_001047556.xml"; // =================== Process =================== FTPFileInfoVO result = AbstractFTPClient.convertFTPUrlToVO(url); // =================== Output =================== Assert.assertEquals("20", result.getPort()); // =================== After =================== } /** * When input URL is not begin with "ftp://", IllegalArgumentException is expected. */ @Test public void testConvertFTPUrlToVO007() { // =================== Before =================== // =================== Input =================== String url = "aftp://username:password@192.168.19.251/ftp/cmdfile/"; // =================== Process =================== Exception result = null; FTPFileInfoVO resultVO = null; try { resultVO = AbstractFTPClient.convertFTPUrlToVO(url); } catch (Exception e) { result = e; } // =================== Output =================== Assert.assertEquals(true, result instanceof IllegalArgumentException); Assert.assertEquals(null, resultVO); // =================== After =================== } /** * When input URL is end with "/", IllegalArgumentException is expected. */ @Test public void testConvertFTPUrlToVO008() { // =================== Before =================== // =================== Input =================== String url = "ftp://username:password@192.168.19.251/ftp/cmdfile/"; // =================== Process =================== Exception result = null; FTPFileInfoVO resultVO = null; try { resultVO = AbstractFTPClient.convertFTPUrlToVO(url); } catch (Exception e) { result = e; } // =================== Output =================== Assert.assertEquals(true, result instanceof IllegalArgumentException); Assert.assertEquals(null, resultVO); // =================== After =================== } /** * When input URL only has "/", IllegalArgumentException is expected. */ @Test public void testConvertFTPUrlToVO009() { // =================== Before =================== // =================== Input =================== String url = "ftp://username:password@192.168.19.251/"; // =================== Process =================== Exception result = null; FTPFileInfoVO resultVO = null; try { resultVO = AbstractFTPClient.convertFTPUrlToVO(url); } catch (Exception e) { result = e; } // =================== Output =================== Assert.assertEquals(true, result instanceof IllegalArgumentException); Assert.assertEquals(null, resultVO); // =================== After =================== } /** * Test default behaviors. */ @Test public void testDefaultBehavior001() { // =================== Before =================== // =================== Input =================== // =================== Process =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); // =================== Output =================== Assert.assertEquals(0, stub.getRetryTimes()); Assert.assertEquals(0, stub.getCurrentRetryTimes()); Assert.assertEquals(1L, stub.getRetryWaitTime()); Assert.assertEquals(true, stub.isResumeBroken()); // =================== After =================== } /** * Test changing default behaviors. */ @Test public void testChangeBehavior001() { // =================== Before =================== // =================== Input =================== // =================== Process =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); stub.setRetryTimes(1); stub.setRetryWaitTime(2L); stub.setResumeBroken(false); // =================== Output =================== Assert.assertEquals(1, stub.getRetryTimes()); Assert.assertEquals(0, stub.getCurrentRetryTimes()); Assert.assertEquals(2L, stub.getRetryWaitTime()); Assert.assertEquals(false, stub.isResumeBroken()); // =================== After =================== } /** * When connect to FTP server failed, failure is expected. * * @throws Exception */ @Test public void testDoTransferFlow001() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); stub.setConnectResult(false); stub.setLoginResult(true); stub.setDoTransferResult(true); // =================== Input =================== // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("doTransferFlow"); boolean result = (Boolean) method.invoke(stub); // =================== Output =================== Assert.assertEquals(false, result); // =================== After =================== } /** * When connect to FTP server succeed, but login to FTP server failed, failure is expected. * * @throws Exception */ @Test public void testDoTransferFlow002() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); stub.setConnectResult(true); stub.setLoginResult(false); stub.setDoTransferResult(true); // =================== Input =================== // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("doTransferFlow"); boolean result = (Boolean) method.invoke(stub); // =================== Output =================== Assert.assertEquals(false, result); // =================== After =================== } /** * When connect and login to FTP server succeed, but file transfer failed, * expect the count of retry time is 0. * * @throws Exception */ @Test public void testDoTransferFlow003() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); stub.setConnectResult(true); stub.setLoginResult(true); stub.setDoTransferResult(false); // =================== Input =================== // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("doTransferFlow"); boolean result = (Boolean) method.invoke(stub); // =================== Output =================== Assert.assertEquals(false, result); Assert.assertEquals(0, stub.getCurrentRetryTimes()); // =================== After =================== } /** * When the max count of retry time is set to 1, connect and login to FTP server succeed, * but file transfer failed, expect the count of retry time is 1. * * @throws Exception */ @Test public void testDoTransferFlow004() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); stub.setConnectResult(true); stub.setLoginResult(true); stub.setDoTransferResult(false); stub.setRetryTimes(1); // =================== Input =================== // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("doTransferFlow"); boolean result = (Boolean) method.invoke(stub); // =================== Output =================== Assert.assertEquals(false, result); Assert.assertEquals(1, stub.getCurrentRetryTimes()); // =================== After =================== } /** * When connect and login to FTP server succeed, and file transfer succeed, * expect the count of retry time is 0. * * @throws Exception */ @Test public void testDoTransferFlow005() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); stub.setConnectResult(true); stub.setLoginResult(true); stub.setDoTransferResult(true); // =================== Input =================== // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("doTransferFlow"); boolean result = (Boolean) method.invoke(stub); // =================== Output =================== Assert.assertEquals(true, result); Assert.assertEquals(0, stub.getCurrentRetryTimes()); // =================== After =================== } /** * When the max count of retry time is set to 1, connect and login to FTP server succeed, * and file transfer succeed, expect the count of retry time is 0. * * @throws Exception */ @Test public void testDoTransferFlow006() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); stub.setConnectResult(true); stub.setLoginResult(true); stub.setDoTransferResult(true); stub.setRetryTimes(1); // =================== Input =================== // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("doTransferFlow"); boolean result = (Boolean) method.invoke(stub); // =================== Output =================== Assert.assertEquals(true, result); Assert.assertEquals(0, stub.getCurrentRetryTimes()); // =================== After =================== } /** * When FTP port is not specified, success is expected. * * @throws Exception */ @Test public void testConnect001() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); mock.connect("192.168.19.251"); EasyMock.expectLastCall().times(1); EasyMock.expect(mock.getRemotePort()).andReturn(200).anyTimes(); EasyMock.expect(mock.getReplyCode()).andReturn(200).times(1); EasyMock.replay(mock); // =================== Input =================== FTPFileInfoVO vo = new FTPFileInfoVO(); vo.setIp("192.168.19.251"); vo.setPort(null); // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("connect", FTPClient.class, FTPFileInfoVO.class); boolean result = (Boolean) method.invoke(stub, mock, vo); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When FTP port is empty string, success is expected. * * * @throws Exception */ @Test public void testConnect002() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); mock.connect("192.168.19.251"); EasyMock.expectLastCall().times(1); EasyMock.expect(mock.getRemotePort()).andReturn(200).anyTimes(); EasyMock.expect(mock.getReplyCode()).andReturn(200).times(1); EasyMock.replay(mock); // =================== Input =================== FTPFileInfoVO vo = new FTPFileInfoVO(); vo.setIp("192.168.19.251"); vo.setPort(""); // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("connect", FTPClient.class, FTPFileInfoVO.class); boolean result = (Boolean) method.invoke(stub, mock, vo); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When FTP port is specified, success is expected. * * @throws Exception */ @Test public void testConnect003() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); mock.connect("192.168.19.251", 20); EasyMock.expectLastCall().times(1); EasyMock.expect(mock.getRemotePort()).andReturn(200).anyTimes(); EasyMock.expect(mock.getReplyCode()).andReturn(200).times(1); EasyMock.replay(mock); // =================== Input =================== FTPFileInfoVO vo = new FTPFileInfoVO(); vo.setIp("192.168.19.251"); vo.setPort("20"); // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("connect", FTPClient.class, FTPFileInfoVO.class); boolean result = (Boolean) method.invoke(stub, mock, vo); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When connection is something wrong, failure is expected. * * @throws Exception */ @Test public void testConnect004() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); mock.connect("192.168.19.251", 20); EasyMock.expectLastCall().times(1); EasyMock.expect(mock.getRemotePort()).andReturn(200).anyTimes(); EasyMock.expect(mock.getReplyCode()).andReturn(100).times(1); EasyMock.replay(mock); // =================== Input =================== FTPFileInfoVO vo = new FTPFileInfoVO(); vo.setIp("192.168.19.251"); vo.setPort("20"); // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("connect", FTPClient.class, FTPFileInfoVO.class); boolean result = (Boolean) method.invoke(stub, mock, vo); // =================== Output =================== Assert.assertEquals(false, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is not specified, success is expected. * * @throws Exception */ @Test public void testChangeDir001() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); EasyMock.replay(mock); // =================== Input =================== String path = null; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is empty string, success is expected. * * @throws Exception */ @Test public void testChangeDir002() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); EasyMock.replay(mock); // =================== Input =================== String path = ""; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is "/path1" which really exists, success is expected. * * @throws Exception */ @Test public void testChangeDir003() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); // mock step 1 EasyMock.expect(mock.changeWorkingDirectory("/")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path1")).andReturn(true).times(1); EasyMock.replay(mock); // =================== Input =================== String path = "/path1"; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is "/path1" which not exists, and path creating and path changing are OK, * success is expected. * * @throws Exception */ @Test public void testChangeDir004() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); // mock step 1 EasyMock.expect(mock.changeWorkingDirectory("/")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path1")).andReturn(false).times(1); // mock step 2 EasyMock.expect(mock.makeDirectory("path1")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path1")).andReturn(true).times(1); EasyMock.replay(mock); // =================== Input =================== String path = "/path1"; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is "/path1" which not exists, and something wrong with path creating, * failure is expected. * * @throws Exception */ @Test public void testChangeDir005() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); // mock step 1 EasyMock.expect(mock.changeWorkingDirectory("/")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path1")).andReturn(false).times(1); // mock step 2 EasyMock.expect(mock.makeDirectory("path1")).andReturn(false).times(1); EasyMock.replay(mock); // =================== Input =================== String path = "/path1"; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(false, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is "/path1" which not exists, path creating is OK, but something wrong with path changing, * failure is expected. * * @throws Exception */ @Test public void testChangeDir006() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); // mock step 1 EasyMock.expect(mock.changeWorkingDirectory("/")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path1")).andReturn(false).times(1); // mock step 2 EasyMock.expect(mock.makeDirectory("path1")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path1")).andReturn(false).times(1); EasyMock.replay(mock); // =================== Input =================== String path = "/path1"; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(false, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is "/path1/path2/path3", and "/path1" exists, path creating and path changing are OK, * success is expected. * * @throws Exception */ @Test public void testChangeDir007() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); // mock step 1 EasyMock.expect(mock.changeWorkingDirectory("/")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path1")).andReturn(true).times(1); // mock step 2 EasyMock.expect(mock.changeWorkingDirectory("path2")).andReturn(false).times(1); EasyMock.expect(mock.makeDirectory("path2")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path2")).andReturn(true).times(1); // mock step 3 EasyMock.expect(mock.changeWorkingDirectory("path3")).andReturn(false).times(1); EasyMock.expect(mock.makeDirectory("path3")).andReturn(true).times(1); EasyMock.expect(mock.changeWorkingDirectory("path3")).andReturn(true).times(1); EasyMock.replay(mock); // =================== Input =================== String path = "/path1/path2/path3"; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(true, result); // =================== After =================== EasyMock.verify(mock); } /** * When input path is "/path1/path2/path3", but something wrong with path changing to root, * failure is expected. * * @throws Exception */ @Test public void testChangeDir008() throws Exception { // =================== Before =================== AbstractFTPClientStub stub = new AbstractFTPClientStub(); FTPClient mock = PowerMock.createStrictMock(FTPClient.class); // mock step 1 EasyMock.expect(mock.changeWorkingDirectory("/")).andReturn(false).times(1); EasyMock.replay(mock); // =================== Input =================== String path = "/path1/path2/path3"; // =================== Process =================== Method method = AbstractFTPClient.class.getDeclaredMethod("changeDir", FTPClient.class, String.class); boolean result = (Boolean) method.invoke(stub, mock, path); // =================== Output =================== Assert.assertEquals(false, result); // =================== After =================== EasyMock.verify(mock); } }
mit
cmunell/micro-util
src/main/java/edu/cmu/ml/rtw/generic/data/annotation/nlp/WordNet.java
3592
package edu.cmu.ml.rtw.generic.data.annotation.nlp; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.sf.extjwnl.JWNLException; import net.sf.extjwnl.data.IndexWord; import net.sf.extjwnl.data.POS; import net.sf.extjwnl.data.Synset; import net.sf.extjwnl.dictionary.Dictionary; /** * WordNet represents various aspects of English WordNet * (http://wordnet.princeton.edu/) or other non-English * WordNets (http://www.illc.uva.nl/EuroWordNet/). The class * currently only works with the English WordNet, but might * be extended further to work with the non-English one. * * @authors Bill McDowell */ public class WordNet { private Dictionary dictionary; public WordNet() { try { this.dictionary = Dictionary.getDefaultResourceInstance(); } catch (JWNLException e) { e.printStackTrace(); } } private POS convertPoSTag(PoSTag tag) { if (PoSTagClass.classContains(PoSTagClass.VB, tag)) return POS.VERB; else if (PoSTagClass.classContains(PoSTagClass.JJ, tag)) return POS.ADJECTIVE; else if (PoSTagClass.classContains(PoSTagClass.RB, tag)) return POS.ADVERB; else if (PoSTagClass.classContains(PoSTagClass.NN, tag) || PoSTagClass.classContains(PoSTagClass.NNP, tag)) return POS.NOUN; else return null; } private String getSynsetName(Synset synset) { return synset.getKey().toString().replaceAll("\\s+", "_"); } private Map<String, Synset> getImmediateSynsets(String word, PoSTag tag) { try { Map<String, Synset> synsets = new HashMap<String, Synset>(); POS pos = convertPoSTag(tag); if (pos == null) return synsets; IndexWord iword = this.dictionary.lookupIndexWord(pos, word); if (iword == null) return synsets; List<Synset> synsetArray = iword.getSenses(); if (synsetArray == null) return synsets; for (Synset synset : synsetArray) synsets.put(getSynsetName(synset), synset); return synsets; } catch (Exception ex) { return null; } } public synchronized boolean areSynonyms(String word1, PoSTag tag1, String word2, PoSTag tag2) { Map<String, Synset> synsets1 = getImmediateSynsets(word1, tag1); Map<String, Synset> synsets2 = getImmediateSynsets(word2, tag2); for (String synset : synsets1.keySet()) if (synsets2.containsKey(synset)) return true; return false; } public synchronized String getFirstImmediateSynsetName(String word, PoSTag tag) { try { POS pos = convertPoSTag(tag); if (pos == null) return null; IndexWord iword = this.dictionary.lookupIndexWord(pos, word); if (iword == null) return null; List<Synset> synsetArray = iword.getSenses(); if (synsetArray == null) return null; Synset s = synsetArray.get(0); return getSynsetName(s); } catch (Exception ex) { return null; } } public synchronized Set<String> getImmediateSynsetNames(String word, PoSTag tag) { return getImmediateSynsets(word, tag).keySet(); } public synchronized String getLemma(String word, PoSTag tag) { if(word.indexOf('-') > -1 || word.indexOf('/') > -1) return word; try { POS pos = convertPoSTag(tag); if (pos == null) return word; IndexWord iword = this.dictionary.lookupIndexWord(pos, word); if (iword == null) return word; String lemma = iword.getLemma(); lemma = lemma.trim().replace(' ', '_'); return lemma; } catch (JWNLException e) { return null; } } }
mit
yancyn/ParcelTrack
ParcelTrack/src/main/java/com/muje/parcel/Carrier.java
2250
package com.muje.parcel; import java.util.ArrayList; import java.util.Collections; /** * Carrier abstract class * TODO: sort track collection in descending for convenient reading. * @author yeang-shing.then * */ public abstract class Carrier { public Carrier() { this.name = ""; this.consignmentNo = ""; this.tracks = new ArrayList<Track>(); } protected String name; /** * Return name of the provider after trace the consignment no. * @return */ public String getProviderName() { return this.name;} protected String consignmentNo; /** * Return resource id for logo image. * @return */ public int getLogoId() { if(this.name.equals("poslaju")) { return R.drawable.poslaju; } else if(this.name.equals("citylink")) { return R.drawable.citylink; } else if(this.name.equals("gdex")) { return R.drawable.gdex; } else if(this.name.equals("fedex")) { return R.drawable.fedex; } else if(this.name.equals("skynet")) { return R.drawable.skynet; } else if(this.name.equals("ups")) { return R.drawable.ups;// source http://upload.wikimedia.org/wikipedia/en/9/9f/United_Parcel_Service_logo.svg } return -1;//null } // protected String origin; // public void setOrigin(String origin) { // this.origin = origin; // } // public String getOrigin() {return this.origin;} // // protected String destination; // public void setDestination(String destination) { // this.destination = destination; // } // public String getDestination() {return this.destination;} protected String url; /** * Return tracking number in original courier website. * @return */ public String getUrl() { return this.url; } protected ArrayList<Track> tracks; /** * Return track collection in descending order of time. * @return */ public ArrayList<Track> getTracks() { Collections.sort(this.tracks, new TrackComparator()); //HACK: Collections.sort(this.tracks, Collections.reverseOrder());//fail return this.tracks; } /** * Trace by consignment no. * @param consignmentNo * @throws Exception */ public abstract void trace(String consignmentNo) throws Exception; }
mit
gabfssilva/geryon
core/src/main/java/org/geryon/Request.java
4060
package org.geryon; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Gabriel Francisco <gabfssilva@gmail.com> */ public class Request { private String url; private String rawPath; private String body; private String contentType; private String method; private Map<String, String> headers; private Map<String, String> queryParameters; private Map<String, String> pathParameters; private Map<String, Map<String, String>> matrixParameters; Request(String url, String rawPath, String body, String contentType, String method, Map<String, String> headers, Map<String, String> queryParameters, Map<String, String> pathParameters) { this.url = url; this.rawPath = rawPath; this.body = body; this.contentType = contentType; this.method = method; this.headers = headers; this.queryParameters = queryParameters; this.pathParameters = pathParameters; } public String url() { return url; } public String rawPath() { return rawPath; } public String body() { return body; } public String contentType() { return contentType; } public String method() { return method; } public Map<String, String> headers() { return headers; } public Map<String, String> queryParameters() { return queryParameters; } public Map<String, String> pathParameters() { return pathParameters; } public Map<String, Map<String, String>> matrixParameters() { if (matrixParameters == null) { matrixParameters = new HashMap<>(); final String[] split = url.split("/"); for (String s : split) { if (!s.contains(";")) continue; final String[] result = s.split(";"); final String path = result[0]; for (int i = 1; i < result.length; i++) { final String[] keyValue = result[i].split("="); final String key = keyValue[0]; final String value = keyValue[1]; Map<String, String> params = matrixParameters.computeIfAbsent(path, k -> new HashMap<>()); params.put(key, value); } } } return matrixParameters; } static class Builder { private String url; private String rawPath; private String body; private String contentType; private String method; private Map<String, String> headers; private Map<String, String> queryParameters; private Map<String, String> pathParameters; private Builder self = this; Builder url(String url) { this.url = url; return self; } Builder rawPath(String rawPath) { this.rawPath = rawPath; return self; } Builder contentType(String contentType) { this.contentType = contentType; return self; } Builder body(String body) { this.body = body; return self; } Builder method(String method) { this.method = method; return self; } Builder headers(Map<String, String> headers) { this.headers = headers; return self; } Builder queryParameters(Map<String, String> queryParameters) { this.queryParameters = queryParameters; return self; } Builder pathParameters(Map<String, String> pathParameters) { this.pathParameters = pathParameters; return self; } Request build() { return new Request(url, rawPath, body, contentType, method, headers, queryParameters, pathParameters); } } }
mit
rushmore/zbus
src/main/java/io/zbus/rpc/RpcStartInterceptor.java
104
package io.zbus.rpc; public interface RpcStartInterceptor { void onStart(RpcProcessor processor); }
mit
loicortola/led-controller
android/app/src/main/java/com/loicortola/controller/library/ledstrip/model/AnimationSet.java
957
package com.loicortola.controller.library.ledstrip.model; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * Created by loicortola on 06/08/2017. */ public class AnimationSet { public final List<Animation> animations = new LinkedList<>(); public AnimationSet animation(Animation a) { animations.add(a); return this; } public List<Animation> getAnimations() { return animations; } public List<String> queryString() { List<String> s = new ArrayList<>(animations.size()); for (Animation a : animations) { s.add(new StringBuilder() .append(a.r) .append(",") .append(a.g) .append(",") .append(a.b) .append(",") .append(a.loopTime) .toString()); } return s; } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_05_01/src/main/java/com/microsoft/azure/management/network/v2020_05_01/ApplicationGatewaySslProtocol.java
1647
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_05_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for ApplicationGatewaySslProtocol. */ public final class ApplicationGatewaySslProtocol extends ExpandableStringEnum<ApplicationGatewaySslProtocol> { /** Static value TLSv1_0 for ApplicationGatewaySslProtocol. */ public static final ApplicationGatewaySslProtocol TLSV1_0 = fromString("TLSv1_0"); /** Static value TLSv1_1 for ApplicationGatewaySslProtocol. */ public static final ApplicationGatewaySslProtocol TLSV1_1 = fromString("TLSv1_1"); /** Static value TLSv1_2 for ApplicationGatewaySslProtocol. */ public static final ApplicationGatewaySslProtocol TLSV1_2 = fromString("TLSv1_2"); /** * Creates or finds a ApplicationGatewaySslProtocol from its string representation. * @param name a name to look for * @return the corresponding ApplicationGatewaySslProtocol */ @JsonCreator public static ApplicationGatewaySslProtocol fromString(String name) { return fromString(name, ApplicationGatewaySslProtocol.class); } /** * @return known ApplicationGatewaySslProtocol values */ public static Collection<ApplicationGatewaySslProtocol> values() { return values(ApplicationGatewaySslProtocol.class); } }
mit
DarrenBellew/Lock-dot-Paint
lock_screen_prototype/app/src/test/java/com/islarf6546/gmail/lock_screen_prototype/ExampleUnitTest.java
420
package com.islarf6546.gmail.lock_screen_prototype; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
graphql-java/graphql-java
src/main/java/graphql/schema/GraphQLTypeReference.java
1731
package graphql.schema; import graphql.PublicApi; import graphql.language.Node; import graphql.util.TraversalControl; import graphql.util.TraverserContext; import static graphql.Assert.assertValidName; /** * A special type to allow a object/interface types to reference itself. It's replaced with the real type * object when the schema is built. */ @PublicApi public class GraphQLTypeReference implements GraphQLNamedOutputType, GraphQLNamedInputType { /** * A factory method for creating type references so that when used with static imports allows * more readable code such as * {@code .type(typeRef(GraphQLString)) } * * @param typeName the name of the type to reference * * @return a GraphQLTypeReference of that named type */ public static GraphQLTypeReference typeRef(String typeName) { return new GraphQLTypeReference(typeName); } private final String name; public GraphQLTypeReference(String name) { assertValidName(name); this.name = name; } @Override public String getName() { return name; } @Override public String getDescription() { return null; } @Override public Node getDefinition() { return null; } @Override public String toString() { return "GraphQLTypeReference{" + "name='" + name + '\'' + '}'; } @Override public TraversalControl accept(TraverserContext<GraphQLSchemaElement> context, GraphQLTypeVisitor visitor) { return visitor.visitGraphQLTypeReference(this, context); } @Override public GraphQLSchemaElement copy() { return typeRef(getName()); } }
mit
sbouclier/java-algorithms-and-data-structures
src/main/java/com/github/sbouclier/jaads/tree/Tree.java
1389
package com.github.sbouclier.jaads.tree; /** * A tree is a hierarchical data without cycle which contains nodes. The first * tree node (without parent) is called 'root node'. * * @author Stéphane Bouclier * * @param <T> * type of tree node value */ public class Tree<T> { protected Node<T> root; public Tree(Node<T> root) { this.root = root; } public void print() { print(root, "", true); } /** * Recursive algorithm for printing nodes * * @param node * current node * @param prefix * to print before node value * @param isLastNode * last node of parent node */ private void print(Node<T> node, String prefix, boolean isLastNode) { if (node != null) { String nextPrefix = prefix + (isLastNode ? " " : "│ "); if (node == root) { prefix = nextPrefix = ""; System.out.println(prefix + node.value); } else { System.out.println(prefix + (isLastNode ? "└── " : "├── ") + node.value); } // print all nodes except last for (int i = 0; i < node.children.size() - 1; i++) { print(node.children.get(i), nextPrefix, false); } // print last node if (node.children.size() > 0) { print(node.children.get(node.children.size() - 1), nextPrefix, true); } } } @Override public String toString() { return "Tree [root=" + root + "]"; } }
mit
MiJack/Smali-Methods-Analysis
src/test/java/CommandTest.java
922
import com.mijackstudio.bean.CClazz; import com.mijackstudio.core.method.ApkMethodProcesser; import com.mijackstudio.util.Loger; import org.junit.Test; import java.io.File; /** * @author MiJack * @since 2016/4/8. */ public class CommandTest { @Test public void Test() { File file = new File("E:\\Graduation_Project\\malware\\Java\\Smali-Methods-Analysis\\works\\apk2\\decompile\\smali" + "\\oicq\\wlogin_sdk\\sharemem\\WloginSigInfo.smali"); ApkMethodProcesser processer = new ApkMethodProcesser(); CClazz clazz = processer.getSmaliCClazz(file); String apkdir = "E:\\Graduation_Project\\malware\\Java\\Smali-Methods-Analysis\\works\\apk2"; File file1 = new File(apkdir+File.separator+"mii"+File.separator+clazz.getClassName().replace("/","_")+".mii"); // processer.convertMIIFile(clazz,file1); Loger.d(file1.getAbsolutePath()); } }
mit
jdcarrillor/RotondAndes2
src/vos/Pedido.java
1708
package vos; import java.util.Date; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; public class Pedido { @JsonProperty(value="id") private Long id; @JsonProperty(value="fecha") private String fecha; @JsonProperty(value="idUsuario") private Long idUsuario; @JsonProperty(value="idProducto") private Long idProducto; @JsonProperty(value="idMenu") private Long idMenu; @JsonProperty(value="numeroRepetidas") private int numeroRepetidas; public Pedido(@JsonProperty(value="id")Long id, @JsonProperty(value="fecha")String fecha, @JsonProperty(value="idUsuario")Long idUsuario, @JsonProperty(value="idProducto")Long idProducto, @JsonProperty(value="idMenu")Long idMenu) { super(); this.id=id; this.fecha=fecha; this.idUsuario =idUsuario; this.idProducto=idProducto; this.idMenu= idMenu; } public Pedido( @JsonProperty(value="idProducto")Long idProducto, @JsonProperty(value="numeroRepetidas") int numeroRepetidas) { super(); this.idProducto=idProducto; this.numeroRepetidas= numeroRepetidas; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getfecha() { return fecha; } public void setfecha(String fecha) { this.fecha = fecha; } public Long getIdUsuario() { return idUsuario; } public void setIdUsuario(Long idUsuario) { this.idUsuario = idUsuario; } public Long getIdProducto() { return idProducto; } public void setIdProducto(Long idProducto) { this.idProducto = idProducto; } public Long getIdMenu() { return idMenu; } public void setIdMenu(Long idMenu) { this.idMenu = idMenu; } }
mit
m87/tsp-miob
tsp/src/main/java/com/hal9000/random/Random.java
160
package com.hal9000.random; public interface Random { int nextInt(boolean unsinged); int nextInt(int n, boolean unsigned); double nextDouble(); }
mit
xetorthio/jedis
src/test/java/redis/clients/jedis/tests/utils/RedisVersionUtil.java
836
package redis.clients.jedis.tests.utils; import redis.clients.jedis.Jedis; public class RedisVersionUtil { public static int getRedisMajorVersionNumber() { String completeVersion = null; try (Jedis jedis = new Jedis()) { jedis.auth("foobared"); String info = jedis.info("server"); String[] splitted = info.split("\\s+|:"); for (int i = 0; i < splitted.length; i++) { if (splitted[i].equalsIgnoreCase("redis_version")) { completeVersion = splitted[i + 1]; break; } } } if (completeVersion == null) { return 0; } return Integer.parseInt(completeVersion.substring(0, completeVersion.indexOf("."))); } public static boolean checkRedisMajorVersionNumber(int minVersion) { return getRedisMajorVersionNumber() >= minVersion; } }
mit
korkorna/desginpatterns
iterator/src/main/java/my/designpatterns/iterator/Iterator.java
129
package my.designpatterns.iterator; @Deprecated public interface Iterator { public boolean hasNext(); public Object next(); }
mit
Epredator/projects
spring-petclinic/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java
4595
/* * Copyright 2012-2018 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.springframework.samples.petclinic.owner; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.util.Collection; import java.util.Map; /** * @author Juergen Hoeller * @author Ken Krebs * @author Arjen Poutsma * @author Michael Isvy */ @Controller class OwnerController { private static final String VIEWS_OWNER_CREATE_OR_UPDATE_FORM = "owners/createOrUpdateOwnerForm"; private final OwnerRepository owners; public OwnerController(OwnerRepository clinicService) { this.owners = clinicService; } @InitBinder public void setAllowedFields(WebDataBinder dataBinder) { dataBinder.setDisallowedFields("id"); } @GetMapping("/owners/new") public String initCreationForm(Map<String, Object> model) { Owner owner = new Owner(); model.put("owner", owner); return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; } @PostMapping("/owners/new") public String processCreationForm(@Valid Owner owner, BindingResult result) { if (result.hasErrors()) { return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; } else { this.owners.save(owner); return "redirect:/owners/" + owner.getId(); } } @GetMapping("/owners/find") public String initFindForm(Map<String, Object> model) { model.put("owner", new Owner()); return "owners/findOwners"; } @GetMapping("/owners") public String processFindForm(Owner owner, BindingResult result, Map<String, Object> model) { // allow parameterless GET request for /owners to return all records if (owner.getLastName() == null) { owner.setLastName(""); // empty string signifies broadest possible search } // find owners by last name Collection<Owner> results = this.owners.findByLastName(owner.getLastName()); if (results.isEmpty()) { // no owners found result.rejectValue("lastName", "notFound", "not found"); return "owners/findOwners"; } else if (results.size() == 1) { // 1 owner found owner = results.iterator().next(); return "redirect:/owners/" + owner.getId(); } else { // multiple owners found model.put("selections", results); return "owners/ownersList"; } } @GetMapping("/owners/{ownerId}/edit") public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) { Owner owner = this.owners.findById(ownerId); model.addAttribute(owner); return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; } @PostMapping("/owners/{ownerId}/edit") public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @PathVariable("ownerId") int ownerId) { if (result.hasErrors()) { return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; } else { owner.setId(ownerId); this.owners.save(owner); return "redirect:/owners/{ownerId}"; } } /** * Custom handler for displaying an owner. * * @param ownerId the ID of the owner to display * @return a ModelMap with the model attributes for the view */ @GetMapping("/owners/{ownerId}") public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) { ModelAndView mav = new ModelAndView("owners/ownerDetails"); mav.addObject(this.owners.findById(ownerId)); return mav; } }
mit