repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
jangesz/java-action | tic-vertx-bp/tic-vertx-bp-modular-route/src/main/java/org/tic/vertx/bp/modular/route/ServiceEndpoint.java | 199 | package org.tic.vertx.bp.modular.route;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
public interface ServiceEndpoint {
String mountPoint();
Router router(Vertx vertx);
}
| mit |
zerobandwidth-net/android-poppycock | Poppycock/appPoppycock/src/main/java/net/zerobandwidth/android/apps/poppycock/model/Sentence.java | 3831 | package net.zerobandwidth.android.apps.poppycock.model;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import net.zerobandwidth.android.lib.database.SQLitePortal;
import java.util.Date;
/**
* Container for a nonsense sentence, suitable for marshalling into the
* database. Unlike other data objects, this one does not hide its fields.
* @since zerobandwidth-net/android-poppycock 1.0.1 (#2)
*/
public class Sentence
implements Parcelable
{
/** Indicates that the instance has not yet been stored in the database. */
public static long NOT_IDENTIFIED = -1L ;
/** The numeric index of the record. */
public long nItemID = NOT_IDENTIFIED ;
/** The timestamp at which the sentence was created. */
public long nItemTS = (new Date()).getTime() ;
/** The nonsense itself. */
public String sSentence = null ;
/** Indicates whether the sentence has been marked as a favorite. */
public boolean bIsFavorite = false ;
/// Database Exchange //////////////////////////////////////////////////////////
/**
* Marshals data out of a {@link Cursor} containing a database row.
* @param crs the cursor
* @return an instance with values extracted from the cursor
*/
public static Sentence fromCursor( Cursor crs )
{
Sentence o = new Sentence() ;
o.nItemID = crs.getLong( crs.getColumnIndex( "item_id" ) ) ;
o.nItemTS = crs.getLong( crs.getColumnIndex( "item_ts" ) ) ;
o.sSentence = crs.getString( crs.getColumnIndex( "sentence" ) ) ;
o.bIsFavorite = SQLitePortal.intToBool(
crs.getInt( crs.getColumnIndex( "favorite" ) ) ) ;
return o ;
}
/**
* Marshals the object into {@link ContentValues} for storage in the
* database.
* @return the object's fields, for storage in the DB
*/
public ContentValues toContentValues()
{
ContentValues vals = new ContentValues() ;
if( nItemID != NOT_IDENTIFIED ) vals.put( "item_id", nItemID ) ;
vals.put( "item_ts", nItemTS ) ;
vals.put( "sentence", sSentence ) ;
vals.put( "favorite", SQLitePortal.boolToInt(bIsFavorite) ) ;
return vals ;
}
/// Parcel Exchange ////////////////////////////////////////////////////////////
/** Required by {@link Parcelable}. */
public static final Creator<Sentence> CREATOR = new Sentence.Parceler() ;
/**
* Parcelizer for the {@link Sentence} class, required by the
* {@link Parcelable} interface.
* @since zerobandwidth-net/android-poppycock 1.0.1 (#2)
*/
public static class Parceler
implements Creator<Sentence>
{
@Override
public Sentence createFromParcel( Parcel pcl )
{ return (new Sentence()).readFromParcel(pcl) ; }
@Override
public Sentence[] newArray( int nSize )
{ return new Sentence[nSize] ; }
}
/**
* Populates the fields of this instance based on the extras in a
* {@link Parcel}.
* @param pcl the parcel containing items for this class
* @return this instance, updated with values from the parcel
*/
public Sentence readFromParcel( Parcel pcl )
{
this.nItemID = pcl.readLong() ;
this.nItemTS = pcl.readLong() ;
this.sSentence = pcl.readString() ;
this.bIsFavorite = SQLitePortal.intToBool( pcl.readInt() ) ;
return this ;
}
@Override
public void writeToParcel( Parcel pcl, int zFlags )
{
pcl.writeLong( this.nItemID ) ;
pcl.writeLong( this.nItemTS ) ;
pcl.writeString( this.sSentence ) ;
pcl.writeInt( SQLitePortal.boolToInt(this.bIsFavorite) ) ;
}
@Override
public int describeContents()
{ return 0 ; }
}
| mit |
clxy/SSM | src/main/java/cn/clxy/ssm/common/web/WebAppListener.java | 459 | package cn.clxy.ssm.common.web;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class WebAppListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
String rootPath = sce.getServletContext().getRealPath("/");
System.setProperty("webroot", rootPath);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
| mit |
SpongePowered/Sponge | src/mixins/java/org/spongepowered/common/mixin/api/minecraft/world/entity/projectile/FireballMixin_API.java | 1644 | /*
* 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.mixin.api.minecraft.world.entity.projectile;
import net.minecraft.world.entity.projectile.Fireball;
import org.spongepowered.api.entity.projectile.explosive.fireball.FireballEntity;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(Fireball.class)
public abstract class FireballMixin_API extends AbstractHurtingProjectileMixin_API implements FireballEntity {
}
| mit |
helospark/SparkTools | SparkBuilderGeneratorPlugin/src/com/helospark/spark/builder/DiContainer.java | 34100 | package com.helospark.spark.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.ui.preferences.WorkingCopyManager;
import com.helospark.spark.builder.handlers.CompilationUnitSourceSetter;
import com.helospark.spark.builder.handlers.CurrentShellProvider;
import com.helospark.spark.builder.handlers.DialogWrapper;
import com.helospark.spark.builder.handlers.ErrorHandlerHook;
import com.helospark.spark.builder.handlers.GenerateBuilderExecutorImpl;
import com.helospark.spark.builder.handlers.GenerateBuilderHandlerErrorHandlerDecorator;
import com.helospark.spark.builder.handlers.HandlerUtilWrapper;
import com.helospark.spark.builder.handlers.ImportRepository;
import com.helospark.spark.builder.handlers.IsEventOnJavaFilePredicate;
import com.helospark.spark.builder.handlers.StateInitializerGenerateBuilderExecutorDecorator;
import com.helospark.spark.builder.handlers.StatefulBeanHandler;
import com.helospark.spark.builder.handlers.WorkingCopyManagerWrapper;
import com.helospark.spark.builder.handlers.codegenerator.ApplicableBuilderFieldExtractor;
import com.helospark.spark.builder.handlers.codegenerator.BuilderCompilationUnitGenerator;
import com.helospark.spark.builder.handlers.codegenerator.BuilderOwnerClassFinder;
import com.helospark.spark.builder.handlers.codegenerator.BuilderRemover;
import com.helospark.spark.builder.handlers.codegenerator.CompilationUnitParser;
import com.helospark.spark.builder.handlers.codegenerator.RegularBuilderCompilationUnitGenerator;
import com.helospark.spark.builder.handlers.codegenerator.RegularBuilderCompilationUnitGeneratorBuilderFieldCollectingDecorator;
import com.helospark.spark.builder.handlers.codegenerator.RegularBuilderUserPreferenceDialogOpener;
import com.helospark.spark.builder.handlers.codegenerator.RegularBuilderUserPreferenceProvider;
import com.helospark.spark.builder.handlers.codegenerator.StagedBuilderCompilationUnitGenerator;
import com.helospark.spark.builder.handlers.codegenerator.StagedBuilderCompilationUnitGeneratorFieldCollectorDecorator;
import com.helospark.spark.builder.handlers.codegenerator.builderfieldcollector.ClassFieldCollector;
import com.helospark.spark.builder.handlers.codegenerator.builderfieldcollector.SuperClassSetterFieldCollector;
import com.helospark.spark.builder.handlers.codegenerator.builderfieldcollector.SuperConstructorParameterCollector;
import com.helospark.spark.builder.handlers.codegenerator.builderprocessor.GlobalBuilderPostProcessor;
import com.helospark.spark.builder.handlers.codegenerator.builderprocessor.JsonDeserializeAdder;
import com.helospark.spark.builder.handlers.codegenerator.component.BuilderAstRemover;
import com.helospark.spark.builder.handlers.codegenerator.component.DefaultConstructorAppender;
import com.helospark.spark.builder.handlers.codegenerator.component.ImportPopulator;
import com.helospark.spark.builder.handlers.codegenerator.component.PrivateInitializingConstructorCreator;
import com.helospark.spark.builder.handlers.codegenerator.component.RegularBuilderBuilderMethodCreator;
import com.helospark.spark.builder.handlers.codegenerator.component.RegularBuilderClassCreator;
import com.helospark.spark.builder.handlers.codegenerator.component.RegularBuilderCopyInstanceBuilderMethodCreator;
import com.helospark.spark.builder.handlers.codegenerator.component.StagedBuilderClassCreator;
import com.helospark.spark.builder.handlers.codegenerator.component.StagedBuilderCreationBuilderMethodAdder;
import com.helospark.spark.builder.handlers.codegenerator.component.StagedBuilderCreationWithMethodAdder;
import com.helospark.spark.builder.handlers.codegenerator.component.StagedBuilderStaticBuilderCreatorMethodCreator;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.EmptyBuilderClassGeneratorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.builderclass.JsonPOJOBuilderAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.buildmethod.BuildMethodBodyCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.buildmethod.BuildMethodCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.buildmethod.BuildMethodDeclarationCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.constructor.PrivateConstructorAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.constructor.PublicConstructorWithMandatoryFieldsAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.constructor.RegularBuilderCopyInstanceConstructorAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.field.BuilderFieldAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.field.FieldDeclarationPostProcessor;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.field.FullyQualifiedNameExtractor;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.field.StaticMethodInvocationFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.field.chain.BuiltInCollectionsInitializerChainitem;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.field.chain.FieldDeclarationPostProcessorChainItem;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.field.chain.OptionalInitializerChainItem;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.stagedinterface.StagedBuilderInterfaceCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.stagedinterface.StagedBuilderInterfaceTypeDefinitionCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.withmethod.RegularBuilderWithMethodAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.withmethod.StagedBuilderWithMethodAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.withmethod.StagedBuilderWithMethodDefiniationCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.builderclass.withmethod.WithMethodParameterCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.buildermethod.StaticBuilderMethodSignatureGeneratorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.buildermethod.copy.BlockWithNewCopyInstanceConstructorCreationFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.buildermethod.copy.CopyInstanceBuilderMethodDefinitionCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.buildermethod.empty.BlockWithNewBuilderCreationFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.buildermethod.empty.BuilderMethodDefinitionCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.buildermethod.empty.NewBuilderAndWithMethodCallCreationFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.constructor.BuilderFieldAccessCreatorFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.constructor.ConstructorInsertionFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.constructor.FieldSetterAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.constructor.PrivateConstructorBodyCreationFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.constructor.PrivateConstructorMethodDefinitionCreationFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.fragment.constructor.SuperFieldSetterMethodAdderFragment;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.ActiveJavaEditorOffsetProvider;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.ApplicableFieldVisibilityFilter;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.BuilderMethodNameBuilder;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.CamelCaseConverter;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.CurrentlySelectedApplicableClassesClassNameProvider;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.FieldNameToBuilderFieldNameConverter;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.FieldPrefixSuffixPreferenceProvider;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.GeneratedAnnotationPopulator;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.ITypeExtractor;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.InterfaceSetter;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.IsRegularBuilderInstanceCopyEnabledPredicate;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.IsTypeApplicableForBuilderGenerationPredicate;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.JavadocAdder;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.JavadocGenerator;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.MarkerAnnotationAttacher;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.ParentITypeExtractor;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.PreferenceStoreProvider;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.StagedBuilderInterfaceNameProvider;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.StagedBuilderStagePropertiesProvider;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.StagedBuilderStagePropertyInputDialogOpener;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.TemplateResolver;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.TypeDeclarationFromSuperclassExtractor;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.TypeDeclarationToVariableNameConverter;
import com.helospark.spark.builder.handlers.codegenerator.component.helper.domain.BodyDeclarationVisibleFromPredicate;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.BuilderClassRemover;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.BuilderRemoverChainItem;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.JsonDeserializeRemover;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.PrivateConstructorRemover;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.StagedBuilderInterfaceRemover;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.StaticBuilderMethodRemover;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.helper.BodyDeclarationOfTypeExtractor;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.helper.GeneratedAnnotationContainingBodyDeclarationFilter;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.helper.GeneratedAnnotationPredicate;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.helper.GenericModifierPredicate;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.helper.IsPrivatePredicate;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.helper.IsPublicPredicate;
import com.helospark.spark.builder.handlers.codegenerator.component.remover.helper.IsStaticPredicate;
import com.helospark.spark.builder.handlers.codegenerator.converter.RegularBuilderDialogDataConverter;
import com.helospark.spark.builder.handlers.codegenerator.converter.RegularBuilderUserPreferenceConverter;
import com.helospark.spark.builder.preferences.PreferencesManager;
public class DiContainer {
public static List<Object> diContainer = new ArrayList<>();
public static void clearDiContainer() {
diContainer.clear();
}
// Visible for testing
// TODO: Introduce LightDi here
public static void initializeDiContainer() {
addDependency(new CamelCaseConverter());
addDependency(new JavadocGenerator());
addDependency(new TemplateResolver());
addDependency(new PreferenceStoreProvider());
addDependency(new CurrentShellProvider());
addDependency(new ITypeExtractor());
addDependency(new DialogWrapper(getDependency(CurrentShellProvider.class)));
addDependency(new PreferencesManager(getDependency(PreferenceStoreProvider.class)));
addDependency(new ErrorHandlerHook(getDependency(DialogWrapper.class)));
addDependency(new BodyDeclarationOfTypeExtractor());
addDependency(new GeneratedAnnotationPredicate());
addDependency(new GenericModifierPredicate());
addDependency(new IsPrivatePredicate(getDependency(GenericModifierPredicate.class)));
addDependency(new IsStaticPredicate(getDependency(GenericModifierPredicate.class)));
addDependency(new IsPublicPredicate(getDependency(GenericModifierPredicate.class)));
addDependency(new GeneratedAnnotationContainingBodyDeclarationFilter(getDependency(GeneratedAnnotationPredicate.class)));
addDependency(new PrivateConstructorRemover(getDependency(IsPrivatePredicate.class),
getDependency(GeneratedAnnotationContainingBodyDeclarationFilter.class)));
addDependency(new BodyDeclarationOfTypeExtractor());
addDependency(new BuilderClassRemover(getDependency(BodyDeclarationOfTypeExtractor.class),
getDependency(GeneratedAnnotationContainingBodyDeclarationFilter.class),
getDependency(IsPrivatePredicate.class),
getDependency(IsStaticPredicate.class),
getDependency(PreferencesManager.class)));
addDependency(new JsonDeserializeRemover(getDependency(PreferencesManager.class)));
addDependency(new StagedBuilderInterfaceRemover(getDependency(BodyDeclarationOfTypeExtractor.class),
getDependency(GeneratedAnnotationContainingBodyDeclarationFilter.class)));
addDependency(new StaticBuilderMethodRemover(getDependency(IsStaticPredicate.class), getDependency(IsPublicPredicate.class),
getDependency(GeneratedAnnotationContainingBodyDeclarationFilter.class)));
addDependency(new BuilderAstRemover(getDependencyList(BuilderRemoverChainItem.class)));
addDependency(new BuilderRemover(getDependency(PreferencesManager.class), getDependency(ErrorHandlerHook.class),
getDependency(BuilderAstRemover.class)));
addDependency(new CompilationUnitSourceSetter());
addDependency(new HandlerUtilWrapper());
addDependency(new WorkingCopyManager());
addDependency(new WorkingCopyManagerWrapper(getDependency(HandlerUtilWrapper.class)));
addDependency(new CompilationUnitParser());
addDependency(new GeneratedAnnotationPopulator(getDependency(PreferencesManager.class)));
addDependency(new MarkerAnnotationAttacher());
addDependency(new ImportRepository());
addDependency(new ImportPopulator(getDependency(PreferencesManager.class), getDependency(ImportRepository.class)));
addDependency(new BuilderMethodNameBuilder(getDependency(CamelCaseConverter.class),
getDependency(PreferencesManager.class),
getDependency(TemplateResolver.class)));
addDependency(new PrivateConstructorAdderFragment());
addDependency(new JsonPOJOBuilderAdderFragment(getDependency(PreferencesManager.class), getDependency(ImportRepository.class)));
addDependency(new EmptyBuilderClassGeneratorFragment(getDependency(GeneratedAnnotationPopulator.class),
getDependency(PreferencesManager.class),
getDependency(JavadocGenerator.class),
getDependency(TemplateResolver.class),
getDependency(JsonPOJOBuilderAdderFragment.class)));
addDependency(new BuildMethodBodyCreatorFragment());
addDependency(new BuildMethodDeclarationCreatorFragment(getDependency(PreferencesManager.class),
getDependency(MarkerAnnotationAttacher.class),
getDependency(TemplateResolver.class)));
addDependency(new JavadocAdder(getDependency(JavadocGenerator.class), getDependency(PreferencesManager.class)));
addDependency(new BuildMethodCreatorFragment(getDependency(BuildMethodDeclarationCreatorFragment.class),
getDependency(BuildMethodBodyCreatorFragment.class)));
addDependency(new FullyQualifiedNameExtractor());
addDependency(new StaticMethodInvocationFragment());
addDependency(new OptionalInitializerChainItem(getDependency(StaticMethodInvocationFragment.class), getDependency(PreferencesManager.class)));
addDependency(new BuiltInCollectionsInitializerChainitem(getDependency(StaticMethodInvocationFragment.class), getDependency(PreferencesManager.class)));
addDependency(new FieldDeclarationPostProcessor(getDependency(PreferencesManager.class), getDependency(FullyQualifiedNameExtractor.class),
getDependency(ImportRepository.class), getDependencyList(FieldDeclarationPostProcessorChainItem.class)));
addDependency(new BuilderFieldAdderFragment(getDependency(FieldDeclarationPostProcessor.class)));
addDependency(new WithMethodParameterCreatorFragment(getDependency(PreferencesManager.class), getDependency(MarkerAnnotationAttacher.class)));
addDependency(new RegularBuilderWithMethodAdderFragment(getDependency(PreferencesManager.class),
getDependency(JavadocAdder.class),
getDependency(MarkerAnnotationAttacher.class),
getDependency(BuilderMethodNameBuilder.class),
getDependency(WithMethodParameterCreatorFragment.class)));
addDependency(new BuilderFieldAccessCreatorFragment());
addDependency(new TypeDeclarationToVariableNameConverter(getDependency(CamelCaseConverter.class)));
addDependency(new FieldSetterAdderFragment(getDependency(BuilderFieldAccessCreatorFragment.class)));
addDependency(new IsRegularBuilderInstanceCopyEnabledPredicate(getDependency(PreferencesManager.class)));
addDependency(
new RegularBuilderCopyInstanceConstructorAdderFragment(getDependency(FieldSetterAdderFragment.class), getDependency(TypeDeclarationToVariableNameConverter.class),
getDependency(IsRegularBuilderInstanceCopyEnabledPredicate.class)));
addDependency(new PublicConstructorWithMandatoryFieldsAdderFragment());
addDependency(new RegularBuilderClassCreator(getDependency(PrivateConstructorAdderFragment.class),
getDependency(EmptyBuilderClassGeneratorFragment.class),
getDependency(BuildMethodCreatorFragment.class),
getDependency(BuilderFieldAdderFragment.class),
getDependency(RegularBuilderWithMethodAdderFragment.class),
getDependency(JavadocAdder.class),
getDependency(RegularBuilderCopyInstanceConstructorAdderFragment.class),
getDependency(PublicConstructorWithMandatoryFieldsAdderFragment.class)));
addDependency(new StaticBuilderMethodSignatureGeneratorFragment(getDependency(GeneratedAnnotationPopulator.class), getDependency(PreferencesManager.class)));
addDependency(new BuilderMethodDefinitionCreatorFragment(getDependency(TemplateResolver.class),
getDependency(PreferencesManager.class),
getDependency(JavadocAdder.class), getDependency(StaticBuilderMethodSignatureGeneratorFragment.class)));
addDependency(new BlockWithNewBuilderCreationFragment());
addDependency(
new RegularBuilderBuilderMethodCreator(getDependency(BlockWithNewBuilderCreationFragment.class),
getDependency(BuilderMethodDefinitionCreatorFragment.class)));
addDependency(new PrivateConstructorMethodDefinitionCreationFragment(getDependency(PreferencesManager.class),
getDependency(GeneratedAnnotationPopulator.class),
getDependency(CamelCaseConverter.class)));
addDependency(new SuperFieldSetterMethodAdderFragment(getDependency(BuilderFieldAccessCreatorFragment.class)));
addDependency(new PrivateConstructorBodyCreationFragment(getDependency(TypeDeclarationToVariableNameConverter.class),
getDependency(FieldSetterAdderFragment.class),
getDependency(BuilderFieldAccessCreatorFragment.class),
getDependency(SuperFieldSetterMethodAdderFragment.class)));
addDependency(new ConstructorInsertionFragment());
addDependency(new PrivateInitializingConstructorCreator(
getDependency(PrivateConstructorMethodDefinitionCreationFragment.class),
getDependency(PrivateConstructorBodyCreationFragment.class),
getDependency(ConstructorInsertionFragment.class)));
addDependency(new FieldPrefixSuffixPreferenceProvider(getDependency(PreferenceStoreProvider.class)));
addDependency(new FieldNameToBuilderFieldNameConverter(getDependency(PreferencesManager.class),
getDependency(FieldPrefixSuffixPreferenceProvider.class),
getDependency(CamelCaseConverter.class)));
addDependency(new TypeDeclarationFromSuperclassExtractor(getDependency(CompilationUnitParser.class),
getDependency(ITypeExtractor.class)));
addDependency(new BodyDeclarationVisibleFromPredicate());
addDependency(new ApplicableFieldVisibilityFilter(getDependency(BodyDeclarationVisibleFromPredicate.class)));
addDependency(new ClassFieldCollector(getDependency(FieldNameToBuilderFieldNameConverter.class),
getDependency(PreferencesManager.class), getDependency(TypeDeclarationFromSuperclassExtractor.class),
getDependency(ApplicableFieldVisibilityFilter.class)));
addDependency(new SuperConstructorParameterCollector(getDependency(FieldNameToBuilderFieldNameConverter.class),
getDependency(PreferencesManager.class), getDependency(TypeDeclarationFromSuperclassExtractor.class),
getDependency(BodyDeclarationVisibleFromPredicate.class)));
addDependency(new SuperClassSetterFieldCollector(getDependency(PreferencesManager.class),
getDependency(TypeDeclarationFromSuperclassExtractor.class),
getDependency(CamelCaseConverter.class)));
addDependency(new ApplicableBuilderFieldExtractor(Arrays.asList(
getDependency(SuperConstructorParameterCollector.class),
getDependency(ClassFieldCollector.class),
getDependency(SuperClassSetterFieldCollector.class))));
addDependency(new ActiveJavaEditorOffsetProvider());
addDependency(new ParentITypeExtractor());
addDependency(new IsTypeApplicableForBuilderGenerationPredicate(getDependency(ParentITypeExtractor.class)));
addDependency(new CurrentlySelectedApplicableClassesClassNameProvider(getDependency(ActiveJavaEditorOffsetProvider.class),
getDependency(IsTypeApplicableForBuilderGenerationPredicate.class),
getDependency(ParentITypeExtractor.class)));
addDependency(new BuilderOwnerClassFinder(getDependency(CurrentlySelectedApplicableClassesClassNameProvider.class),
getDependency(PreferencesManager.class), getDependency(GeneratedAnnotationPredicate.class)));
addDependency(new BlockWithNewCopyInstanceConstructorCreationFragment());
addDependency(new CopyInstanceBuilderMethodDefinitionCreatorFragment(getDependency(TemplateResolver.class),
getDependency(PreferencesManager.class),
getDependency(JavadocAdder.class), getDependency(StaticBuilderMethodSignatureGeneratorFragment.class)));
addDependency(new RegularBuilderCopyInstanceBuilderMethodCreator(getDependency(BlockWithNewCopyInstanceConstructorCreationFragment.class),
getDependency(CopyInstanceBuilderMethodDefinitionCreatorFragment.class),
getDependency(TypeDeclarationToVariableNameConverter.class),
getDependency(IsRegularBuilderInstanceCopyEnabledPredicate.class)));
addDependency(new JsonDeserializeAdder(getDependency(ImportRepository.class)));
addDependency(new GlobalBuilderPostProcessor(getDependency(PreferencesManager.class), getDependency(JsonDeserializeAdder.class)));
addDependency(new DefaultConstructorAppender(getDependency(ConstructorInsertionFragment.class), getDependency(PreferencesManager.class),
getDependency(GeneratedAnnotationPopulator.class)));
addDependency(new RegularBuilderCompilationUnitGenerator(getDependency(RegularBuilderClassCreator.class),
getDependency(RegularBuilderCopyInstanceBuilderMethodCreator.class),
getDependency(PrivateInitializingConstructorCreator.class),
getDependency(RegularBuilderBuilderMethodCreator.class), getDependency(ImportPopulator.class),
getDependency(BuilderRemover.class),
getDependency(GlobalBuilderPostProcessor.class),
getDependency(DefaultConstructorAppender.class)));
addDependency(new RegularBuilderUserPreferenceDialogOpener(getDependency(CurrentShellProvider.class)));
addDependency(new RegularBuilderDialogDataConverter());
addDependency(new RegularBuilderUserPreferenceConverter(getDependency(PreferencesManager.class)));
addDependency(new RegularBuilderUserPreferenceProvider(getDependency(RegularBuilderUserPreferenceDialogOpener.class),
getDependency(PreferencesManager.class),
getDependency(RegularBuilderDialogDataConverter.class),
getDependency(RegularBuilderUserPreferenceConverter.class)));
addDependency(new RegularBuilderCompilationUnitGeneratorBuilderFieldCollectingDecorator(getDependency(ApplicableBuilderFieldExtractor.class),
getDependency(RegularBuilderCompilationUnitGenerator.class),
getDependency(RegularBuilderUserPreferenceProvider.class)));
addDependency(new IsEventOnJavaFilePredicate(getDependency(HandlerUtilWrapper.class)));
// staged builder dependencies
addDependency(new StagedBuilderInterfaceNameProvider(getDependency(PreferencesManager.class),
getDependency(CamelCaseConverter.class),
getDependency(TemplateResolver.class)));
addDependency(new StagedBuilderWithMethodDefiniationCreatorFragment(getDependency(PreferencesManager.class),
getDependency(BuilderMethodNameBuilder.class),
getDependency(MarkerAnnotationAttacher.class),
getDependency(StagedBuilderInterfaceNameProvider.class),
getDependency(WithMethodParameterCreatorFragment.class)));
addDependency(new StagedBuilderInterfaceTypeDefinitionCreatorFragment(getDependency(JavadocAdder.class)));
addDependency(new StagedBuilderInterfaceCreatorFragment(getDependency(StagedBuilderWithMethodDefiniationCreatorFragment.class),
getDependency(StagedBuilderInterfaceTypeDefinitionCreatorFragment.class),
getDependency(StagedBuilderInterfaceTypeDefinitionCreatorFragment.class),
getDependency(BuildMethodDeclarationCreatorFragment.class),
getDependency(JavadocAdder.class),
getDependency(GeneratedAnnotationPopulator.class)));
addDependency(new StagedBuilderCreationBuilderMethodAdder(getDependency(BlockWithNewBuilderCreationFragment.class),
getDependency(BuilderMethodDefinitionCreatorFragment.class)));
addDependency(new NewBuilderAndWithMethodCallCreationFragment());
addDependency(new StagedBuilderCreationWithMethodAdder(getDependency(StagedBuilderWithMethodDefiniationCreatorFragment.class),
getDependency(NewBuilderAndWithMethodCallCreationFragment.class), getDependency(JavadocAdder.class)));
addDependency(new StagedBuilderStaticBuilderCreatorMethodCreator(getDependency(StagedBuilderCreationBuilderMethodAdder.class),
getDependency(StagedBuilderCreationWithMethodAdder.class),
getDependency(PreferencesManager.class)));
addDependency(new StagedBuilderWithMethodAdderFragment(
getDependency(StagedBuilderWithMethodDefiniationCreatorFragment.class),
getDependency(MarkerAnnotationAttacher.class)));
addDependency(new InterfaceSetter());
addDependency(new StagedBuilderClassCreator(getDependency(PrivateConstructorAdderFragment.class),
getDependency(EmptyBuilderClassGeneratorFragment.class),
getDependency(BuildMethodCreatorFragment.class),
getDependency(BuilderFieldAdderFragment.class),
getDependency(StagedBuilderWithMethodAdderFragment.class),
getDependency(InterfaceSetter.class),
getDependency(MarkerAnnotationAttacher.class)));
addDependency(new StagedBuilderStagePropertyInputDialogOpener(getDependency(CurrentShellProvider.class)));
addDependency(new StagedBuilderStagePropertiesProvider(getDependency(StagedBuilderInterfaceNameProvider.class),
getDependency(StagedBuilderStagePropertyInputDialogOpener.class)));
addDependency(new StagedBuilderCompilationUnitGenerator(getDependency(StagedBuilderClassCreator.class),
getDependency(PrivateInitializingConstructorCreator.class),
getDependency(StagedBuilderStaticBuilderCreatorMethodCreator.class),
getDependency(ImportPopulator.class),
getDependency(StagedBuilderInterfaceCreatorFragment.class),
getDependency(BuilderRemover.class),
getDependency(GlobalBuilderPostProcessor.class),
getDependency(DefaultConstructorAppender.class)));
addDependency(new StagedBuilderCompilationUnitGeneratorFieldCollectorDecorator(
getDependency(StagedBuilderCompilationUnitGenerator.class),
getDependency(ApplicableBuilderFieldExtractor.class),
getDependency(StagedBuilderStagePropertiesProvider.class)));
// Generator chain
addDependency(new GenerateBuilderExecutorImpl(getDependency(CompilationUnitParser.class),
getDependencyList(BuilderCompilationUnitGenerator.class),
getDependency(IsEventOnJavaFilePredicate.class), getDependency(WorkingCopyManagerWrapper.class),
getDependency(CompilationUnitSourceSetter.class),
getDependency(ErrorHandlerHook.class),
getDependency(BuilderOwnerClassFinder.class)));
addDependency(new GenerateBuilderHandlerErrorHandlerDecorator(getDependency(GenerateBuilderExecutorImpl.class),
getDependency(ErrorHandlerHook.class)));
addDependency(new StatefulBeanHandler(getDependency(PreferenceStoreProvider.class),
getDependency(WorkingCopyManagerWrapper.class), getDependency(ImportRepository.class)));
addDependency(
new StateInitializerGenerateBuilderExecutorDecorator(
getDependency(GenerateBuilderHandlerErrorHandlerDecorator.class),
getDependency(StatefulBeanHandler.class)));
}
// Visible for testing
public static void addDependency(Object dependency) {
boolean alreadyHasDependency = diContainer.stream()
.filter(value -> isSameMockitoMockDependency(dependency.getClass().toString(),
value.getClass().toString()))
.findFirst()
.isPresent();
if (!alreadyHasDependency) {
diContainer.add(dependency);
}
}
private static boolean isSameMockitoMockDependency(String newDependency, String oldDependency) {
int mockitoClassNameStartIndex = oldDependency.indexOf("$$EnhancerByMockitoWithCGLIB");
if (mockitoClassNameStartIndex != -1) {
String mockitolessClassName = oldDependency.substring(0, mockitoClassNameStartIndex);
return newDependency.equals(mockitolessClassName);
} else {
return false;
}
}
/**
* Probably will be deprecated after I will be able to create e4 plugin.
*
* @param clazz
* type to get
* @return dependency of that class
*/
@SuppressWarnings("unchecked")
public static <T> T getDependency(Class<T> clazz) {
return (T) diContainer.stream()
.filter(value -> clazz.isAssignableFrom(value.getClass()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Unable to initialize " + clazz.getName() + " not found"));
}
@SuppressWarnings("unchecked")
public static <T> List<T> getDependencyList(Class<T> classToFind) {
List<Object> result = new ArrayList<>();
for (Object o : diContainer) {
if (classToFind.isAssignableFrom(o.getClass())) {
result.add(o);
}
}
return (List<T>) result;
}
}
| mit |
mym987/CPS308_Game_Final | examples/XStreamExample/XStreamGameEngine.java | 3156 | package XStreamExample;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import voogasalad_GucciGames.gameEngine.GameMap;
import voogasalad_GucciGames.gameEngine.MainGameEngine;
import voogasalad_GucciGames.gameEngine.gamePlayer.AllPlayers;
import voogasalad_GucciGames.gameEngine.gamePlayer.GamePlayerPerson;
import voogasalad_GucciGames.gameEngine.gamePlayer.UnitCollection;
import voogasalad_GucciGames.gameEngine.gameRule.OnlyOnePlayerHasUnitsCondition;
public class XStreamGameEngine {
@SuppressWarnings("resource")
public static void main(String[] args0) {
XStream serializer = new XStream(new DomDriver());
String currentTurn = "Current Turn: ";
String engineLocation = "./examples/XStreamExample/engine.xml";
try {
List<GamePlayerPerson> myListOfPlayers = new ArrayList<GamePlayerPerson>();
/*
* UnitCollection neutralUnits = new UnitCollection();
* myListOfPlayers.add(new GamePlayerPerson(neutralUnits, 0));
* //neutral player
*
* UnitCollection p1Units = new UnitCollection();
*
* GameUnitType soldier = new GameUnitType("soldier", null);
* GameUnitType archer = new GameUnitType("archer" , null);
*
* p1Units.addUnit(new GameUnit(1, soldier, 3, 3));
* p1Units.addUnit(new GameUnit(1, archer, 1, 1));
* myListOfPlayers.add(new GamePlayerPerson(p1Units, 0)); //player 1
*
* UnitCollection p2Units = new UnitCollection();
*
* p2Units.addUnit(new GameUnit(2, soldier, 2, 2));
*
* myListOfPlayers.add(new GamePlayerPerson(p2Units, 0)); //player 2
*
*/
AllPlayers myPlayers = new AllPlayers(myListOfPlayers);
GameMap myMap = new GameMap(myPlayers);
OnlyOnePlayerHasUnitsCondition myRule = new OnlyOnePlayerHasUnitsCondition(myMap);
MainGameEngine engine = new MainGameEngine(myPlayers, myRule, myMap);
engine.incrementCurrentTurn();
String engineXML = serializer.toXML(engine); // saved XML File
// should have
// current turn as 2
File file = new File(engineLocation);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write(engineXML);
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadEngine();
}
public GameEngineToGamePlayerInterface loadEngine() {
try {
File file = new File(engineLocation);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuilder engineXMLBuilder = new StringBuilder();
bufferedReader.lines().forEach(line -> engineXMLBuilder.append(line));
// loaded XML File should have current turn as 2
MainGameEngine engine = (MainGameEngine) serializer.fromXML(engineXMLBuilder.toString());
engine.incrementCurrentTurn();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
| mit |
DreamCloudWalker/SoccerMap | BasicFrame/src/com/dengjian/soccermap/utils/PreferenceHelper.java | 3043 | /**
* Copyright 2016 dengjian's code
*
* Create on 2016-8-4 ����10:34:38
*
*/
package com.dengjian.soccermap.utils;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
/**
* @author dengjian01 ���ڹ���Preference������
*/
public class PreferenceHelper {
private static PreferenceHelper mInstance;
private SharedPreferences mPreferences;
private Editor mEditor;
/**
* ������ȡ����
*
* @param context
* ������
* @return ��������
*/
public static PreferenceHelper getInstance(final Context context) {
if (mInstance == null) {
synchronized (PreferenceHelper.class) {
if (mInstance == null) {
mInstance = new PreferenceHelper(context);
}
}
}
return mInstance;
}
public SharedPreferences getPreferences() {
return mPreferences;
}
private PreferenceHelper(final Context context) {
mPreferences = context.getSharedPreferences("utils",
Activity.MODE_PRIVATE); // ��һ������Ϊxml�ļ���
mEditor = mPreferences.edit();
}
public Map<String, ?> getAll() {
return mPreferences.getAll();
}
public boolean contains(String key) {
return mPreferences.contains(key);
}
public boolean getBoolean(String key, boolean defValue) {
return mPreferences.getBoolean(key, defValue);
}
public float getFloat(String key, float defValue) {
return mPreferences.getFloat(key, defValue);
}
public int getInt(String key, int defValue) {
return mPreferences.getInt(key, defValue);
}
public long getLong(String key, long defValue) {
return mPreferences.getLong(key, defValue);
}
public String getString(String key, String defValue) {
return mPreferences.getString(key, defValue);
}
public void registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
mPreferences.registerOnSharedPreferenceChangeListener(listener);
}
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
mPreferences.unregisterOnSharedPreferenceChangeListener(listener);
}
public boolean putBoolean(String key, boolean b) {
mEditor.putBoolean(key, b);
return mEditor.commit();
}
public boolean putInt(String key, int i) {
mEditor.putInt(key, i);
return mEditor.commit();
}
public boolean putFloat(String key, float f) {
mEditor.putFloat(key, f);
return mEditor.commit();
}
public boolean putLong(String key, long l) {
mEditor.putLong(key, l);
return mEditor.commit();
}
public boolean putString(String key, String s) {
mEditor.putString(key, s);
return mEditor.commit();
}
/**
* �����¼
*
* @param key
* @return
*/
public boolean remove(String key) {
mEditor.remove(key);
return mEditor.commit();
}
} // end of class PreferenceHelper | mit |
pedrocavalero/metadata | src/main/java/net/sf/esfinge/metadata/annotation/validator/field/OneAnnotationWithVolatileFieldOnly.java | 258 | package net.sf.esfinge.metadata.annotation.validator.field;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@VolatileFieldOnly
@Retention(RetentionPolicy.RUNTIME)
public @interface OneAnnotationWithVolatileFieldOnly {
}
| mit |
langens-jonathan/delta-service | src/main/java/SPARQLParser/SPARQLStatements/BlockStatement.java | 2907 | package SPARQLParser.SPARQLStatements;
import java.util.ArrayList;
import java.util.List;
/**
* Created by langens-jonathan on 20.07.16.
*
* version 0.0.1
*
* Abstract class.
*
* The idea is that the update and where block types inherit from this block type because they allow
* for nested versions of each other.
*
* A block has a certain type, a graph upon which it operates and a list of statements between it's
* parentheses.
*
* The types of blocks are:
* - insert
* - delete
* - where
* - select
*/
public abstract class BlockStatement implements IStatement
{
/**
* the supported types of block statments
*/
public enum BLOCKTYPE {
INSERT, DELETE, WHERE, SELECT
}
// the type
protected BLOCKTYPE type;
// the graph upon which it operates
protected String graph = "";
// the statments between it's brackets
protected List<IStatement> statements;
/**
* Default constructor initializes the statements list.
*/
public BlockStatement()
{
statements = new ArrayList<IStatement>();
}
/**
* returns the statement type
* @return BLOCK
*/
public StatementType getType()
{
return StatementType.BLOCK;
}
/**
* @return the graph on which this block operates
*/
public String getGraph()
{
return this.graph;
}
/**
* @param graph this.graph = graph
*/
public void setGraph(String graph){this.graph = graph;}
/**
* @return the statements in this block
*/
public List<IStatement> getStatements()
{
return this.statements;
}
/**
* this will propagate the replacement of ALL subsequent graph statements with the new
* graph name.
*
* note that to remove all graph statements you can just pass an empty string as parameter
*
* @param newGraph the name of the new graph
*/
public void replaceGraphStatements(String newGraph)
{
this.graph = newGraph;
for(IStatement s : this.statements)
s.replaceGraphStatements(newGraph);
}
/**
* this will propagate the replacement of ALL subsequent graph statements which are
* equal to the oldGraph's name. All graph statements targetting other graphs will remain
* untouched.
*
* @param oldGraph the name of tha graph that needs be replaced
* @param newGraph the new graph name
*/
public void replaceGraphStatements(String oldGraph, String newGraph)
{
if(this.graph.equals(oldGraph))
this.graph = newGraph;
for(IStatement s : this.statements)
s.replaceGraphStatements(oldGraph, newGraph);
}
/**
* forcing subsequent classes to override the clone method
* @return a clone of the inheriting object
*/
public abstract BlockStatement clone();
}
| mit |
nasane/moarTP | moarTP/src/com/ofallonminecraft/moarTP/Move.java | 4457 | package com.ofallonminecraft.moarTP;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.Location;
import com.ofallonminecraft.SpellChecker.SpellChecker;
public class Move {
@SuppressWarnings("deprecation")
public static boolean move(CommandSender sender, String[] args, Connection c) {
// check user permissions
if (sender.hasPermission("moarTP.move")) {
// check number of arguments
if (args.length > 3) {
sender.sendMessage("Too many arguments!");
return false;
}
if (args.length < 2) {
sender.sendMessage("Not enough arguments!");
return false;
}
// ----- MOVE ----- //
try {
PreparedStatement s = c.prepareStatement("select x,y,z,world,secret from moarTP where location=?;");
s.setString(1, args[1].toLowerCase());
ResultSet rs = s.executeQuery();
if (!rs.next()) {
sender.sendMessage(args[1].toLowerCase()+" is not in the library!");
HashSet<String> dict_subs = new HashSet<String>();
dict_subs.add(SpellChecker.LOCATIONS);
String sug = new SpellChecker(c, dict_subs).getSuggestion(args[1].toLowerCase());
if (sug != null) {
sender.sendMessage("Did you mean \"/move "+ args[0] + " " + sug + "\"?");
}
} else {
Location toGoTo = null;
if (rs.getString(4).equals("Y")) {
if (args.length<3) {
sender.sendMessage(args[1].toLowerCase()+" is secret! A password is required for access.");
return false;
} else {
s = c.prepareStatement("select encryptedLocation,hashedPass from moarTP where location=?;");
s.setString(1, args[1].toLowerCase());
rs = s.executeQuery();
rs.next();
String encryptedLoc = rs.getString(1);
String passwordHash = rs.getString(2);
boolean validated = false;
String[] decryptedLocation = null;
try {
validated = PasswordHash.validatePassword(args[2], passwordHash);
if (validated) {
decryptedLocation = SimpleCrypto.decrypt(args[2], encryptedLoc).split(",");
toGoTo = new Location(
Bukkit.getServer().getWorld(decryptedLocation[0]),
Integer.parseInt(decryptedLocation[1]),
Integer.parseInt(decryptedLocation[2]),
Integer.parseInt(decryptedLocation[3]));
} else {
sender.sendMessage("Password could not be verified.");
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
toGoTo = new Location(Bukkit.getServer().getWorld(rs.getString(4)),
rs.getInt(1),rs.getInt(2),rs.getInt(3));
}
String[] playersToMove = args[0].split(",");
for (String playerToMove : playersToMove) {
// TODO: find alternate method for doing this (it is deprecated)
if (Bukkit.getServer().getPlayer(playerToMove)!=null &&
Bukkit.getServer().getPlayer(playerToMove).isOnline()) {
Bukkit.getServer().getPlayer(playerToMove).teleport(toGoTo);
sender.sendMessage("Successfully teleported " + playerToMove
+ " to " + args[1].toLowerCase()+'.');
} else {
HashSet<String> dict_subs = new HashSet<String>();
dict_subs.add(SpellChecker.ONLINE_PLAYERS);
String sugPlayer = new SpellChecker(c, dict_subs).getSuggestion(playerToMove);
String sug = "";
if (sugPlayer != null) {
sug = " Did you mean \"" + sugPlayer + "\"?";
}
sender.sendMessage(playerToMove + " could not be found on the server." + sug);
}
}
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
// ----- END MOVE ----- //
}
// if the user doesn't have permission, present an error message
sender.sendMessage("You don't have permission to do this!");
return false;
}
}
| mit |
CSSE497/pathfinder-webserver | app/controllers/ForceHttps.java | 501 | package controllers;
import play.libs.F;
import play.mvc.Action;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
public class ForceHttps extends Action<Controller> {
@Override public F.Promise<Result> call(Http.Context ctx) throws Throwable {
if (!ctx.request().secure()) {
return F.Promise.promise(
() -> redirect("https://" + ctx.request().host() + ctx.request().uri()));
}
return this.delegate.call(ctx);
}
}
| mit |
ittianyu/MVVM | app/src/main/java/com/ittianyu/mvvm/application/h_rxjava2/common/repository/remote/RetrofitFactory.java | 995 | package com.ittianyu.mvvm.application.h_rxjava2.common.repository.remote;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by yu on 2017/2/21.
*/
public class RetrofitFactory {
private static OkHttpClient client;
private static Retrofit retrofit;
private static final String HOST = "https://api.github.com";
static {
client = new OkHttpClient.Builder()
.connectTimeout(9, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(HOST)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static Retrofit getInstance() {
return retrofit;
}
}
| mit |
atsushieno/jmdsp | src/name/atsushieno/midi/SmfMessage.java | 2019 | package name.atsushieno.midi;
public class SmfMessage
{
public static final short NoteOff = (short) 0x80;
public static final short NoteOn = (short) 0x90;
public static final short PAf = (short) 0xA0;
public static final short CC = (short) 0xB0;
public static final short Program = (short) 0xC0;
public static final short CAf = (short) 0xD0;
public static final short Pitch = (short) 0xE0;
public static final short SysEx1 = (short) 0xF0;
public static final short SysEx2 = (short) 0xF7;
public static final short Meta = (short) 0xFF;
public static final byte EndSysEx = (byte) (short) 0xF7;
public SmfMessage (int value)
{
this.value = value;
data = null;
}
public SmfMessage (short type, short arg1, short arg2, byte [] data)
{
value = type + (arg1 << 8) + (arg2 << 16);
this.data = data;
}
public final int value;
// This expects EndSysEx byte _inclusive_ for F0 message.
public final byte [] data;
public short getStatusByte ()
{
return (short) (value & 0xFF);
}
public short getMessageType ()
{
switch (getStatusByte()) {
case Meta:
case SysEx1:
case SysEx2:
return getStatusByte();
default:
return (short) (value & 0xF0);
}
}
public short getMsb ()
{
return (short) ((value & 0xFF00) >> 8);
}
public short getLsb ()
{
return (short) ((value & 0xFF0000) >> 16);
}
public short getMetaType ()
{
return getMsb ();
}
public byte getChannel ()
{
return (byte) (value & 0x0F);
}
public static byte fixedDataSize (short statusByte)
{
switch (statusByte & (short) 0xF0) {
case (short) 0xF0: // and 0xF7, 0xFF
return 0; // no fixed data
case SmfMessage.Program: // ProgramChg
case SmfMessage.CAf: // CAf
return 1;
default:
return 2;
}
}
@Override
public String toString ()
{
return String.format("{0:X02}:{1:X02}:{2:X02}{3}", getStatusByte(), getMsb(), getLsb(), data != null ? data.length + "[data]" : "");
}
}
| mit |
MrPointVirgule/RocketLyon | RocketLyonAndroid/app/src/main/java/com/insa/rocketlyonandroid/view/ArretsFragment.java | 1078 | package com.insa.rocketlyonandroid.view;
import android.os.Bundle;
import com.insa.rocketlyonandroid.models.Arret;
import com.insa.rocketlyonandroid.services.GPSTracker;
import com.insa.rocketlyonandroid.utils.BaseFragment;
import trikita.log.Log;
public abstract class ArretsFragment extends BaseFragment implements RVView, ArretsView {
public static GPSTracker mGPSService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGPSService = new GPSTracker(mActivity);
updateLocation();
}
public void updateLocation() {
mGPSService.updateLocation();
if (!mGPSService.isLocationAvailable()) {
Log.d("GPS not available.");
}
mGPSService.closeGPS();
}
@Override
public void openMap(Arret arret) {
Log.d("openMap");
}
@Override
public void openTimetable(Arret arret) {
Log.d("openTimetable");
}
@Override
public void openStreetview(Arret arret) {
Log.d("openStreetview");
}
}
| mit |
wolfgangimig/joa | java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/impl/IRoomPropertyDictionaryImpl.java | 3292 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib.impl;
import com.wilutions.com.*;
@SuppressWarnings("all")
@CoClass(guid="{BB65927F-FCB2-920A-2EAF-F2F11F3B6AEA}")
public class IRoomPropertyDictionaryImpl extends Dispatch implements com.wilutions.mslib.uccollaborationlib.IRoomPropertyDictionary {
@DeclDISPID(1610743808) public Integer getCount() throws ComException {
final Object obj = this._dispatchCall(1610743808,"Count", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Integer)obj;
}
@DeclDISPID(0) public Object getItem(final com.wilutions.mslib.uccollaborationlib.RoomProperty _propertyType) throws ComException {
assert(_propertyType != null);
final Object obj = this._dispatchCall(0,"Item", DISPATCH_PROPERTYGET,null,_propertyType.value);
if (obj == null) return null;
return (Object)obj;
}
@DeclDISPID(1610743810) public com.wilutions.mslib.uccollaborationlib.RoomProperty[] getKeys() throws ComException {
final Object obj = this._dispatchCall(1610743810,"Keys", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (com.wilutions.mslib.uccollaborationlib.RoomProperty[])obj;
}
@DeclDISPID(1610743811) public Object[] getValues() throws ComException {
final Object obj = this._dispatchCall(1610743811,"Values", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Object[])obj;
}
@DeclDISPID(1610743812) public Boolean TryGetValue(final com.wilutions.mslib.uccollaborationlib.RoomProperty _propertyType, final ByRef<Object> _itemValue) throws ComException {
assert(_propertyType != null);
assert(_itemValue != null);
final Object obj = this._dispatchCall(1610743812,"TryGetValue", DISPATCH_METHOD,null,_propertyType.value,_itemValue);
if (obj == null) return null;
return (Boolean)obj;
}
@DeclDISPID(1610743813) public com.wilutions.mslib.uccollaborationlib.RoomProperty GetKeyAt(final Integer _index) throws ComException {
assert(_index != null);
final Object obj = this._dispatchCall(1610743813,"GetKeyAt", DISPATCH_METHOD,null,_index);
if (obj == null) return null;
return com.wilutions.mslib.uccollaborationlib.RoomProperty.valueOf((Integer)obj);
}
@DeclDISPID(1610743814) public Object GetValueAt(final Integer _index) throws ComException {
assert(_index != null);
final Object obj = this._dispatchCall(1610743814,"GetValueAt", DISPATCH_METHOD,null,_index);
if (obj == null) return null;
return (Object)obj;
}
@DeclDISPID(1610743815) public Boolean ContainsKey(final com.wilutions.mslib.uccollaborationlib.RoomProperty _propertyType) throws ComException {
assert(_propertyType != null);
final Object obj = this._dispatchCall(1610743815,"ContainsKey", DISPATCH_METHOD,null,_propertyType.value);
if (obj == null) return null;
return (Boolean)obj;
}
public IRoomPropertyDictionaryImpl(String progId) throws ComException {
super(progId, "{7BF20B14-58D1-494B-B301-9B16BACC9610}");
}
protected IRoomPropertyDictionaryImpl(long ndisp) {
super(ndisp);
}
public String toString() {
return "[IRoomPropertyDictionaryImpl" + super.toString() + "]";
}
}
| mit |
ClubObsidian/ObsidianEngine | src/com/clubobsidian/obsidianengine/snakeyaml/nodes/AnchorNode.java | 1050 | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.clubobsidian.obsidianengine.snakeyaml.nodes;
public class AnchorNode extends Node {
private Node realNode;
public AnchorNode(Node realNode) {
super(realNode.getTag(), realNode.getStartMark(), realNode.getEndMark());
this.realNode = realNode;
}
@Override
public NodeId getNodeId() {
return NodeId.anchor;
}
public Node getRealNode() {
return realNode;
}
}
| mit |
Aesthetikx/hubski-android | hubski-android/src/main/java/com/aesthetikx/hubski/parse/FeedParser.java | 4015 | package com.aesthetikx.hubski.parse;
import com.aesthetikx.hubski.model.Feed;
import com.aesthetikx.hubski.model.Post;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FeedParser {
public static Feed parse(String html) {
Document doc = Jsoup.parse(html);
Elements unitElements = doc.select("div#grid > div#unit.box");
List<Post> posts = new ArrayList<>();
for (Element unit: unitElements) {
Element plusMinus = unit.select("div.plusminus").get(0);
Element postContent = unit.select("div.postcontent").get(0);
String title = getTitle(postContent);
String username = getUsername(postContent);
List<String> tags = getTags(postContent);
int commentCount = getCommentCount(postContent);
int shareCount = getScore(plusMinus);
URL commentsUrl = getCommentsUrl(postContent);
URL articleUrl = getArticleUrl(postContent);
Post p;
if (articleUrl == null) {
p = new Post(title, username, tags, commentCount, shareCount, commentsUrl);
} else {
p = new Post(title, username, tags, commentCount, shareCount, commentsUrl, articleUrl);
}
// System.out.println(p.toString());
posts.add(p);
}
return new Feed(posts);
}
private static int getScore(Element plusMinus) {
try {
return Integer.parseInt(plusMinus.select("span.score > a > img").get(0).attr("class").substring(0,1));
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
private static String getTitle(Element postContent) {
try {
return postContent.select("div.feedtitle > span > a").get(0).text();
} catch (Exception e) {
e.printStackTrace();
return "notitle";
}
}
private static String getUsername(Element postContent) {
try {
return postContent.select("div.titlelinks > span#username").get(0).text();
} catch (Exception e) {
e.printStackTrace();
return "nouser";
}
}
private static List<String> getTags(Element postContent) {
List<String> tags = new ArrayList<>();
try {
Elements tagElements = postContent.select("div.subtitle > span a");
for (Element tag: tagElements) {
tags.add(tag.text());
}
} catch (Exception e) {
e.printStackTrace();
}
return tags;
}
private static int getCommentCount(Element postContent) {
try {
return Integer.parseInt(postContent.select("span.feedcombub > a").text());
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
private static URL getCommentsUrl(Element postContent) {
try {
return new URL("http://www.hubski.com/" + postContent.select("div.feedtitle > span > a").get(0).attr("href"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static URL getArticleUrl(Element postContent) {
try {
String onclick = postContent.select("div.feedtitle > span > a").get(0).attr("onclick");
if (onclick.isEmpty()) return null;
Pattern pattern = Pattern.compile("window\\.open\\('(.*)'\\);");
Matcher matcher = pattern.matcher(onclick);
if (matcher.find()) {
return new URL(matcher.group(1));
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| mit |
NickToony/scrAI | src/main/java/com/nicktoony/helpers/LodashCallback.java | 108 | package com.nicktoony.helpers;
/**
* Created by nick on 26/07/15.
*/
public interface LodashCallback {
}
| mit |
timitoc/groupicture | Groupic/src/com/timitoc/groupic/dialogBoxes/CreateFolderDialogBox.java | 5484 | package com.timitoc.groupic.dialogBoxes;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.timitoc.groupic.R;
import com.timitoc.groupic.utils.ConnectionStateManager;
import com.timitoc.groupic.utils.Encryptor;
import com.timitoc.groupic.utils.Global;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by timi on 01.05.2016.
*/
public class CreateFolderDialogBox extends DialogFragment {
View mainView;
private boolean invalid(String data)
{
if (data.length() == 0){
Toast.makeText(this.getActivity(), "Name can not be empty", Toast.LENGTH_SHORT).show();
return true;
}
for (int i = 0; i < data.length(); i++)
if (!Character.isDigit(data.charAt(i)) && !Character.isLetter(data.charAt(i)) && !(data.charAt(i) == ' ')){
String error = data.charAt(i) + " is not allowed when creating folders.";
Toast.makeText(this.getActivity(), error, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(mainView = inflater.inflate(R.layout.create_folder_dialog, null))
// Add action buttons
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String name = ((TextView)mainView.findViewById(R.id.folder_create_name)).getText().toString();
if (!invalid(name)) {
try {
createFolder(name);
} catch (JSONException e) {
e.printStackTrace();
giveError();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CreateFolderDialogBox.this.getDialog().cancel();
}
});
return builder.create();
}
public void giveError() {
//System.out.println("Network error, are you connected to internet?");
Toast.makeText(getActivity(), "Weak internet connection", Toast.LENGTH_SHORT).show();
ConnectionStateManager.decreaseUsingState();
}
public void createFolder(String name) throws JSONException {
RequestQueue queue = Volley.newRequestQueue(this.getActivity());
String url = getString(R.string.api_service_url);
final JSONObject params = new JSONObject();
params.put("title", name);
params.put("group_id", Global.current_group_id);
final String hash = Encryptor.hash(params.toString() + Global.MY_PRIVATE_KEY);
StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
try {
JSONObject jsonResponse = new JSONObject(response);
if ("success".equals(jsonResponse.getString("status"))) {
if (getActivity() != null && isAdded())
Toast.makeText(getActivity(), "Created folder successfully", Toast.LENGTH_SHORT).show();
}
else {
giveError();
}
} catch (JSONException e) {
e.printStackTrace();
giveError();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
System.out.println("Error " + error.getMessage());
giveError();
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> paramap = new HashMap<>();
paramap.put("function", "create_folder");
paramap.put("public_key", Global.MY_PUBLIC_KEY);
paramap.put("data", params.toString());
paramap.put("hash", hash);
return paramap;
}
};
queue.add(strRequest);
}
}
| mit |
Softhouse/orchid | se.softhouse.garden.orchid.commons/src/main/java/se/softhouse/garden/orchid/commons/text/storage/provider/OrchidMessageStorageCache.java | 7905 | /**
* Copyright (c) 2011, Mikael Svahn, Softhouse Consulting AB
*
* 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:
*
* 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 se.softhouse.garden.orchid.commons.text.storage.provider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* A message cache that loads strings from bare files in a directory structure.
* The file names have the following format
* key_[language]_[country]_[variant].[ext]
*
* If the [ext] equals properties the files is read as a property and insert
* into the property tree. Note that the location and name of the property file
* will be inserted into the message key.
*
* The getMessage operations returns the found content or if a none leaf node is
* queried the children of that node is returned.
*
* This class is not thread safe.
*
* @author Mikael Svahn
*
*/
public class OrchidMessageStorageCache<T> {
protected OrchidMessageStorageCacheTree cachedTree;
protected Map<String, Map<String, T>> cachedMessages;
protected MessageFactory<T> messageFactory;
protected int packageStartLevel;
/**
* Creates a cache instance
*/
public OrchidMessageStorageCache() {
this.cachedMessages = new HashMap<String, Map<String, T>>();
this.cachedTree = new OrchidMessageStorageCacheTree();
}
/**
* Sets the message factory to use
*/
public void setMessageFactory(MessageFactory<T> messageFactory) {
this.messageFactory = messageFactory;
}
/**
* Set the package start level
*/
public void setPackageStartLevel(int packageStartLevel) {
this.packageStartLevel = packageStartLevel;
}
/**
* Returns the current message factory
*/
public MessageFactory<T> getMessageFactory() {
return this.messageFactory;
}
/**
* Clears the cache, nothing new is read
*/
public void clear() {
this.cachedMessages.clear();
}
/**
* Returns the content of the message with the specified code.
*
* @param code
* A case sensitive key for the message
* @return The found message or null if none was found
*/
public T getMessage(String code) {
return getMessage(code, Locale.getDefault());
}
/**
* Returns the content of the message with the specified code and locale
*
* @param code
* A case sensitive key for the message
* @param locale
* The locale to look for.
*
* @return The found message or null if none was found
*/
public T getMessage(String code, Locale locale) {
return getMessageFromCache(code, locale);
}
/**
* Returns the content of the message with the specified code and locale
*
* @param code
* A case sensitive key for the message
* @param locale
* The locale to look for.
*
* @return The found message or null if none was found
*/
protected T getMessageFromCache(String code, Locale locale) {
List<String> localeKeys = calculateLocaleKeys(locale);
for (String localeKey : localeKeys) {
Map<String, T> map = this.cachedMessages.get(localeKey);
if (map != null) {
T message = map.get(code);
if (message != null) {
return this.messageFactory.createMessage(message, locale);
}
}
}
String list = this.cachedTree.getMessage(code, locale);
if (list != null) {
return this.messageFactory.createMessage(list, locale);
}
return null;
}
/**
* Add the specified message to the cache,
*
* @param list
* The code of the message
* @param locale
* The locale of the message
* @param message
* The content of the message
*
* @return The message
*/
protected T addToCache(List<String> prePkgs, List<String> pkgs, String locale, T message) {
String c = formatCode(prePkgs, pkgs);
if (c != null) {
Map<String, T> map = this.cachedMessages.get(locale);
if (map == null) {
map = new HashMap<String, T>();
this.cachedMessages.put(locale, map);
}
map.put(c, message);
this.cachedTree.addMessage(c, locale);
}
return message;
}
/**
* Calculates the locale keys accoring to the following prio list.
*
* 1. language_country_variant <br>
* 2. language_country <br>
* 3. language <br>
* 4. language__variant <br>
* 5. _country_variant <br>
* 6. _country <br>
* 7. __variant <br>
* 8. <br>
*
* @param locale
* @return
*/
protected List<String> calculateLocaleKeys(Locale locale) {
List<String> result = new ArrayList<String>(4);
String language = locale.getLanguage().toLowerCase();
String country = locale.getCountry().toLowerCase();
String variant = locale.getVariant().toLowerCase();
boolean hasLanguage = language.length() > 0;
boolean hasCountry = country.length() > 0;
boolean hasVariant = variant.length() > 0;
if (hasLanguage && hasCountry && hasVariant) {
result.add(new StringBuilder().append(language).append("_").append(country).append("_").append(variant).toString());
}
if (hasLanguage && hasCountry) {
result.add(new StringBuilder().append(language).append("_").append(country).toString());
}
if (hasLanguage && hasVariant) {
result.add(new StringBuilder().append(language).append("__").append(variant).toString());
}
if (hasLanguage) {
result.add(new StringBuilder().append(language).toString());
}
if (hasCountry && hasVariant) {
result.add(new StringBuilder().append("_").append(country).append("_").append(variant).toString());
}
if (hasCountry) {
result.add(new StringBuilder().append("_").append(country).toString());
}
if (hasVariant) {
result.add(new StringBuilder().append("__").append(variant).toString());
}
result.add("");
return result;
}
/**
* Creates a code key from the list of packages by separating them with a
* dot.
*
* @param pkgs
* The list of packages
* @param pkgs2
*
* @return A dot separated string of the list
*/
protected String formatCode(List<String> prePkgs, List<String> pkgs) {
StringBuilder b = new StringBuilder();
formatCode(0, prePkgs, b);
formatCode(this.packageStartLevel, pkgs, b);
if (b.length() > 0) {
return b.toString();
}
return null;
}
private void formatCode(int start, List<String> pkgs, StringBuilder b) {
for (int i = start; i < pkgs.size(); i++) {
if (b.length() > 0) {
b.append('.');
}
b.append(pkgs.get(i));
}
}
/**
* This factory class will create a message of type T from a string.
*/
public abstract static class MessageFactory<T> {
/**
* Create a T from a String
*
* @param message
* The string
* @param locale
* The current locale
*
* @return The created T
*/
public abstract T createMessage(String message, Locale local);
/**
* Create a T from a T. The same instance can be returned if it is
* thread safe.
*
* @param message
* The message to copy if needed
* @param locale
* The current locale
*
* @return The created T
*/
public abstract T createMessage(T message, Locale local);
}
}
| mit |
luddev/StatusHub | app/src/androidTest/java/com/futuretraxex/statushub/TestUriMatcher.java | 266 | package com.futuretraxex.statushub;
import android.test.AndroidTestCase;
/**
* Created by paresh on 10/24/2015.
*/
public class TestUriMatcher extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
}
| mit |
ffleurey/FFBPG | src/main/java/eu/diversify/ffbpg/sgh/model/SGHSystem.java | 21484 | package eu.diversify.ffbpg.sgh.model;
import eu.diversify.ffbpg.Application;
import eu.diversify.ffbpg.BPGraph;
import static eu.diversify.ffbpg.BPGraph.average;
import static eu.diversify.ffbpg.BPGraph.dataFileWithAverage;
import eu.diversify.ffbpg.Platform;
import eu.diversify.ffbpg.Service;
import eu.diversify.ffbpg.collections.Population;
import eu.diversify.ffbpg.random.RandomUtils;
import eu.diversify.ffbpg.utils.FileUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ffl
*/
public class SGHSystem {
public static SGHSystem generateSGHSystem(int max_clients, int max_servers) {
SGHSystem result = new SGHSystem();
SGHModel m = SGHModel.getInstance();
result.clients = new ArrayList<SGHClientApp>();
int id=1;
for (int i=0; i<max_clients; i++) {
SGHClientApp c = m.createRandomClient();
c.setName("C" + id);
result.clients.add(c);
id++;
}
result.servers = new ArrayList<SGHServer>();
id=1;
for (int i=0; i<max_servers; i++) {
SGHServer s = m.createRandomServer();
s.setName("S" + id);
result.servers.add(s);
id++;
}
// Add some random links
result.createRandomLinks();
// Cleanup the model
result.removedDeadClients();
result.removedUnusedServers();
return result;
}
public static SGHSystem generateRealisticManualSGHSystem(int max_clients, int max_servers) {
SGHSystem result = new SGHSystem();
SGHModel m = SGHModel.getInstance();
result.clients = new ArrayList<SGHClientApp>();
int id=1;
for (int i=0; i<max_clients; i++) {
SGHClientApp c = m.createRandomClient();
c.setName("C" + id);
result.clients.add(c);
id++;
}
result.servers = new ArrayList<SGHServer>();
id=1;
for (int i=0; i<max_servers; i++) {
SGHServer s = m.createRealisticManualServer();
s.setName("S" + id);
result.servers.add(s);
id++;
}
// Add some random links
result.createRandomLinks();
// Cleanup the model
result.removedDeadClients();
result.removedUnusedServers();
return result;
}
ArrayList<SGHClientApp> clients;
ArrayList<SGHServer> servers;
private SGHSystem() {}
public SGHSystem deep_clone() {
SGHSystem result = new SGHSystem();
result.clients = new ArrayList<SGHClientApp>();
result.servers = new ArrayList<SGHServer>();
HashMap<SGHServer, SGHServer> old_new_map = new HashMap<SGHServer, SGHServer>();
for (SGHServer s : servers) {
SGHServer cs = s.deep_clone();
old_new_map.put(s, cs);
result.servers.add(cs);
}
for (SGHClientApp c : clients) {
SGHClientApp cc = c.deep_clone(old_new_map);
result.clients.add(cc);
}
return result;
}
private void createRandomLinks() {
// Clone the server list to randomize its order for each client
ArrayList<SGHServer> _servers = (ArrayList<SGHServer>)servers.clone();
// For each client, add a set of links to satistfy its dependencies
for (SGHClientApp c : clients) {
Collections.shuffle(_servers, RandomUtils.getRandom());
c.getLinks().clear(); // remove any existing links
ArrayList reqs = c.getRequests();
for (SGHServer s : _servers) {
if (!s.hasCapacity()) continue;
ArrayList nreqs = s.filterRequestsWhichCanHandle(reqs);
if (nreqs.size() < reqs.size()) {
// the server is useful
c.getLinks().add(s);
s.increaseLoad();
reqs = nreqs;
}
if (reqs.isEmpty()) break;
}
if(!reqs.isEmpty()) {
for (SGHServer s : c.getLinks()) {
s.decreaseLoad();
}
c.getLinks().clear();
}
}
}
private void removedDeadClients() {
for (SGHClientApp c : (ArrayList<SGHClientApp>)clients.clone()) {
if (!c.isAlive()) {
for (SGHServer s : c.getLinks()) s.decreaseLoad(); // clear the load on the servers
clients.remove(c);
}
}
}
public int removedSomeRedondancy() {
int result = 0;
for (SGHClientApp c : (ArrayList<SGHClientApp>)clients.clone()) {
// for each client try to remove one link if possible
for (SGHServer candidate : (ArrayList<SGHServer>)c.getLinks().clone()) {
if (c.is_droping_server_link_acceptable(candidate)) {
c.getLinks().remove(candidate);
candidate.decreaseLoad();
result++;
break;
}
}
}
return result;
}
private void removedUnusedServers() {
HashSet<SGHServer> srvs = new HashSet<SGHServer>();
for (SGHClientApp c : clients) {
for (SGHServer s : c.getLinks()) {
srvs.add(s);
}
}
for (SGHServer s : (ArrayList<SGHServer>)servers.clone()) {
if (!srvs.contains(s)) {
servers.remove(s);
}
}
}
class ExecExtinctionSeq implements Callable<SGHExtinctionSequence[]> {
int nb_seq = 10;
public ExecExtinctionSeq(int nb_seq) {
this.nb_seq = nb_seq;
}
public SGHExtinctionSequence[] call() {
SGHExtinctionSequence[] result = computeRandomExtinctionSequence(nb_seq);
return result;
}
}
public SGHExtinctionSequence[] computeRandomExtinctionSequence(int seq, int threads) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads);
LinkedList<Future<?>> futures = new LinkedList<Future<?>>();
SGHExtinctionSequence[] eseqs = new SGHExtinctionSequence[seq];
for (int i = 0; i < threads; i++)
{
ExecExtinctionSeq task = new ExecExtinctionSeq(seq/threads);
futures.add(executor.submit(task));
}
int idx = 0;
for (Future<?> future:futures) {
try {
SGHExtinctionSequence[] res = (SGHExtinctionSequence[])future.get();
for (int i=0; i<res.length; i++) {
eseqs[idx++] = res[i];
}
} catch (InterruptedException ex) {
Logger.getLogger(SGHSystem.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(SGHSystem.class.getName()).log(Level.SEVERE, null, ex);
}
}
executor.shutdown();
return eseqs;
}
private SGHExtinctionSequence[] computeRandomExtinctionSequence(int seq) {
ArrayList<SGHServer> all_servers = (ArrayList<SGHServer>)servers.clone();
SGHExtinctionSequence[] eseqs = new SGHExtinctionSequence[seq];
for (int i=0; i<seq; i++) {
HashSet<SGHServer> alive_servers = new HashSet<SGHServer>(all_servers);
eseqs[i] = new SGHExtinctionSequence(servers.size(), clients.size());
// Randomize the order
Collections.shuffle(all_servers);
for (SGHServer to_kill : all_servers) {
int nb_cli_alive = 0;
double percent_cli_alive = 0f;
for(SGHClientApp c : clients) {
ArrayList<SGHRequest> reqs = c.getRequests();
for (SGHServer s : c.getLinks()) {
if (alive_servers.contains(s)) {
reqs = s.filterRequestsWhichCanHandle(reqs);
}
}
if (reqs.size() == 0) nb_cli_alive++;
percent_cli_alive += 1f - ((double)reqs.size() / ((double)c.getRequests().size()));
}
percent_cli_alive /= clients.size();
eseqs[i].extinctionStep(servers.size() - alive_servers.size(), nb_cli_alive, percent_cli_alive);
alive_servers.remove(to_kill);
}
eseqs[i].extinctionStep(servers.size(), 0, 0f);
}
return eseqs;
}
public String dumpData(boolean details) {
StringBuffer b = new StringBuffer();
Hashtable<SGHServer, Integer> srvs = new Hashtable<SGHServer, Integer>();
int srv_features_count = 0;
int cli_link_count = 0;
int alive = 0;
int dead = 0;
for (SGHClientApp c : clients) {
cli_link_count += c.links.size();
if (c.isAlive()) {
if (details) b.append(c.getOneLineString());
if (details) b.append("\n");
alive++;
for (SGHServer s : c.getLinks()) {
if (srvs.containsKey(s)) {
srvs.put(s, srvs.get(s)+1);
}
else {
srvs.put(s, 1);
}
}
}
}
for (SGHClientApp c : clients) {
if (!c.isAlive()) {
if (details)b.append(c.getOneLineString());
if (details)b.append("\n");
dead++;
}
}
b.append("ALIVE CLIENTS: " + alive +", DEAD: " + dead + "\n");
int s_alive = 0;
int s_dead = 0;
for (SGHServer s : servers) {
srv_features_count += s.featureSet.size();
if (srvs.containsKey(s)) {
if (details) { b.append("#"); b.append(srvs.get(s)); b.append("->"); b.append(s.getOneLineString());
b.append("\n"); }
s_alive++;
}
}
for (SGHServer s : servers) {
if (!srvs.containsKey(s)) {
if (details) { b.append("0 ->"); b.append(s.getOneLineString());
b.append("\n");}
s_dead++;
}
}
b.append("ALIVE SERVERS: " + s_alive +", DEAD: " + s_dead + "\n");
// Calculate some metrics on the network
HashMap<String, ArrayList<SGHNode>> srv_pop = SGHNode.getPopulation(servers);
Population srv_pop_stats = SGHNode.getPopulationStats(srv_pop);
b.append(" SERVER POPULATION : "); b.append(srv_pop_stats.toString());b.append("\n");
b.append(" SERVER POPULATION : ");b.append(servers.size());b.append("\n");
b.append(" SERVER SHANNON DIV : ");b.append(srv_pop_stats.getShannonIndex());b.append("\n");
b.append(" SERVER VARIETY : ");b.append(srv_pop_stats.getSpeciesCount());b.append("\n");
b.append(" SERVER BALANCE : ");b.append(srv_pop_stats.getShannonEquitability());b.append("\n");
b.append(" SERVER DISPARITY : ");b.append(SGHNode.disparityOfSpercies(srv_pop));b.append("\n");
b.append(" SERVER DIVERSITY : ");b.append(SGHNode.diversity(srv_pop));b.append("\n");
b.append(" CLIENT LINK CPT : ");b.append(cli_link_count);b.append("\n");
b.append(" SERVER FEATURES CPT : ");b.append(srv_features_count);b.append("\n");
return b.toString();
}
public int[] distLinksPerClients() {
int[] result = new int[servers.size()];
for(SGHClientApp c : clients) {
result[c.links.size()]++;
}
return result;
}
public int[] distLinksPerServers() {
int[] result = new int[clients.size()];
// Calulate server connections
Hashtable<SGHServer, ArrayList<SGHClientApp>> links = new Hashtable<SGHServer, ArrayList<SGHClientApp>>();
for (SGHClientApp client : clients) {
for (SGHServer s : client.getLinks()) {
if (!links.containsKey(s)) {
links.put(s, new ArrayList<SGHClientApp>());
}
links.get(s).add(client);
}
}
for(SGHServer s : servers) {
if (!links.containsKey(s)) result[0]++;
else result[links.get(s).size()]++;
}
return result;
}
public int[] distNbFeaturesPerClients() {
int[] result = new int[SGHModel.getInstance().totalNbFeatures()+1];
for(SGHClientApp c : clients) {
result[c.featureSet.size()]++;
}
return result;
}
public int[] distNbFeaturesPerServers() {
int[] result = new int[SGHModel.getInstance().totalNbFeatures()+1];
for(SGHServer s : servers) {
result[s.featureSet.size()]++;
}
return result;
}
public int[] distFeaturesOnClients() {
Hashtable<SGHFeature, Integer> count = new Hashtable<SGHFeature, Integer>();
for (SGHClientApp c : clients) {
for (SGHFeature f : c.featureSet) {
if (!count.containsKey(f)) {
count.put(f, 1);
}
else {
count.put(f, count.get(f) + 1);
}
}
}
ArrayList<Integer> counts = new ArrayList<Integer>(count.values());
Collections.sort(counts);
int[] result = new int[counts.size()];
for (int i=0; i<counts.size(); i++) result[counts.size()-i-1] = counts.get(i);
return result;
}
public int[] distFeaturesOnServers() {
Hashtable<SGHFeature, Integer> count = new Hashtable<SGHFeature, Integer>();
for (SGHServer s : servers) {
for (SGHFeature f : s.featureSet) {
if (!count.containsKey(f)) {
count.put(f, 1);
}
else {
count.put(f, count.get(f) + 1);
}
}
}
ArrayList<Integer> counts = new ArrayList<Integer>(count.values());
Collections.sort(counts);
int[] result = new int[counts.size()];
for (int i=0; i<counts.size(); i++) result[counts.size()-i-1] = counts.get(i);
return result;
}
public void exportGraphStatistics(File folder) {
DataExportUtils.writeGNUPlotScriptForIntArray(distNbFeaturesPerClients(), folder, "dist_nb_features_per_clients", "Size (in Features)", "# Clients");
DataExportUtils.writeGNUPlotScriptForIntArray(distNbFeaturesPerServers(), folder, "dist_nb_features_per_servers", "Size (in Features)", "# Servers");
DataExportUtils.writeGNUPlotScriptForIntArray(distFeaturesOnClients(), folder, "dist_feature_use_on_clients", "Feature", "# of usages in clients");
DataExportUtils.writeGNUPlotScriptForIntArray(distFeaturesOnServers(), folder, "dist_feature_use_on_servers", "Feature", "# of usages in servers");
DataExportUtils.writeGNUPlotScriptForIntArray(distLinksPerClients(), folder, "dist_nb_links_per_clients", "# Links (to Servers)", "# Clients");
DataExportUtils.writeGNUPlotScriptForIntArray(distLinksPerServers(), folder, "dist_nb_links_per_servers", "# Links (from Clients)", "# Servers");
}
public void exportClientsToJSONFiles(File base_folder, String name, File hostlist) throws Exception {
File outdir = new File(base_folder, name);
outdir.mkdir();
BufferedReader br = null;
HashMap<SGHServer, String> serverids = new HashMap<SGHServer, String>();
if (hostlist != null) {
br = new BufferedReader(new FileReader(hostlist));
for(SGHServer s : servers) {
serverids.put(s, br.readLine());
}
}
else {
int srvid = 0;
for(SGHServer s : servers) {
serverids.put(s, "coreff3:153" + srvid);
srvid++;
}
}
int clientid = 0;
// Export 1 JSON file per client
for (SGHClientApp c : clients) {
StringBuilder b = new StringBuilder();
b.append("{\n");
b.append("\"id\":\""+c.getName()+"\", \n");
writeJSONForServices(c, b);
b.append(",\n");
b.append("\"platforms\":[\n");
boolean first = true;
for (SGHServer s : c.getLinks()) {
if (first) { first = false; } else b.append(", ");
b.append("{\n");
b.append("\"id\":\""+s.getName()+"\", \n");
b.append("\"host\":\"http://"+serverids.get(s)+"/\",\n");
writeJSONForServices(s, b);
b.append("}\n");
}
b.append("]\n");
b.append("}\n");
FileUtils.writeTextFile(outdir, "client" + clientid + ".json", b.toString());
clientid++;
}
}
public void writeJSONForServices(SGHNode n, StringBuilder b) {
b.append("\"services\":[\n");
boolean vfirst = true;
for (SGHVariationPoint v : n.features.keySet()) {
//if (n.features.get(v).isEmpty()) continue;
if (vfirst) { vfirst = false; } else b.append(", ");
b.append("{\"name\":\"");b.append(v.getName());b.append("\",\"alternatives\":[");
boolean first = true;
for (SGHFeature f : n.features.get(v)) {
if (first) { first = false; } else b.append(", ");
b.append("\"");b.append(f.getName());b.append("\"");
}
b.append("]}\n");
}
b.append("]\n");
}
public BPGraph toBPGraph() {
// Create all the services and collect their indexes
ArrayList<Service> services = new ArrayList<Service>();
Hashtable<String, Integer> srvidx = new Hashtable<String, Integer>();
Hashtable<String, SGHRequest> reqs = new Hashtable<String, SGHRequest>();
for (SGHClientApp c : clients) {
for (SGHRequest r : c.getRequests()) {
String s = r.toString();
if (!srvidx.containsKey(s)) {
srvidx.put(s, services.size());
reqs.put(s, r);
Service ns = new Service(s);
ns.incrementUsage();
services.add(ns);
} else {
Service ns = services.get(srvidx.get(s));
ns.incrementUsage();
}
}
}
// Sort the list of services and update indexes
Collections.sort(services);
for (int i=0; i<services.size(); i++) {
String s = services.get(i).getName();
srvidx.put(s, i);
}
// Create all platforms
Hashtable<SGHServer, Platform> platmap = new Hashtable<SGHServer, Platform>();
ArrayList<Platform> plats= new ArrayList<Platform>();
for (SGHServer s : servers) {
Platform p = new Platform(s.getName(), s.getCapacity());
for (String str : reqs.keySet()) {
SGHRequest req = reqs.get(str);
if (s.canHandle(req)) {
p.getProvidedServices().add(srvidx.get(str));
}
}
platmap.put(s, p);
plats.add(p);
}
// Create applications
ArrayList<Application> apps= new ArrayList<Application>();
for (SGHClientApp c : clients) {
Application a = new Application(c.getName(), plats.size());
for (SGHRequest req : c.getRequests()) {
a.getRequiredServices().add(srvidx.get(req.toString()));
}
for (SGHServer s : c.getLinks()) {
Platform p = platmap.get(s);
p.incrementLoad();
a.getLinkedPlatforms().add(p);
}
apps.add(a);
}
BPGraph result = new BPGraph(services);
result.setPlatforms(plats);
result.setApplications(apps);
return result;
}
}
| mit |
tcooc/ModularTweaks | tco/modulartweaks/module/mjirc/MJIrcConnection.java | 1782 | package tco.modulartweaks.module.mjirc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class MJIrcConnection {
private final String server;
private final int port;
private final Queue<String> messageQueue;
private boolean open = false;
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private Thread listener;
public MJIrcConnection(String server, int port) {
messageQueue = new ConcurrentLinkedQueue<String>();
this.server = server;
this.port = port;
}
public void connect() throws UnknownHostException, IOException {
socket = new Socket(server, port);
writer = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
listener = new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while(open && (line = reader.readLine()) != null) {
messageQueue.add(line);
}
}catch (SocketException e) {
}
catch (IOException e) {
e.printStackTrace();
}
}
});
listener.start();
open = true;
}
public void disconnect() {
try {
if(socket != null) {
writer.close();
reader.close();
socket.close();
}
} catch(Exception e) {
} finally {
socket = null;
open = false;
}
}
public String read() {
return messageQueue.poll();
}
public BufferedWriter write() {
return writer;
}
public boolean open() {
return open;
}
}
| mit |
abysmli/FDSSimulator | src/main/java/simulator/guis/components/Valve.java | 4009 | package simulator.guis.components;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class Valve extends SimulationComponent {
private static final long serialVersionUID = 1L;
private final JLabel labelValve;
private final int widthPipe;
private final String name;
private boolean state;
public Valve(int x, int y, int width, int height, double pipeWidthPorcentage, int widthPipe, String name) {
super(x, y, width, height, pipeWidthPorcentage);
labelValve = new JLabel("Closed");
labelValve.setBounds(7, 55, 45, 15);
labelValve.setFont(new Font("Ubuntu", Font.PLAIN, 12));
labelValve.setHorizontalAlignment(SwingConstants.CENTER);
labelValve.setForeground(Color.white);
labelValve.setBackground(Color.GRAY);
labelValve.setOpaque(true);
add(labelValve);
this.widthPipe = widthPipe;
this.name = name;
}
@Override
protected void paintComponent(Graphics _g) {
Graphics2D g = (Graphics2D) _g;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paintComponent(g);
g.setColor(new Color(204, 229, 255));
g.fillRect(0, 0, this.getWidthComponent(), this.getHeightComponent());
g.setColor(new Color(40, 68, 255));
double m = (double) (this.widthPipe) / (double) (this.getWidthComponent());
for (int i = 0; i < this.getWidthComponent(); i++) {
g.drawLine(i, (int) (m * i + 0.5 * this.widthPipe), i, (int) (-m * i + 1.5 * this.widthPipe));
}
g.setColor(Color.black);
g.drawLine(0, this.widthPipe / 2, this.getWidthComponent(), (int) (1.5 * this.widthPipe));
g.drawLine(0, (int) (1.5 * this.widthPipe), this.getWidthComponent(), this.widthPipe / 2);
g.drawLine(0, this.widthPipe / 2, 0, (int) (1.5 * this.widthPipe));
g.drawLine(this.getWidthComponent() / 2, 0, this.getWidthComponent() / 2, (int) (1.5 * this.widthPipe));
g.drawLine(this.getWidthComponent(), this.widthPipe / 2, this.getWidthComponent(),
(int) (1.5 * this.widthPipe));
g.drawOval((int) (this.getWidthComponent() / 3), (int) (this.getWidthComponent() / 5) - 2, this.widthPipe,
this.widthPipe);
g.setColor(new Color(40, 68, 255));
g.fillOval((int) (this.getWidthComponent() / 3), (int) (this.getWidthComponent() / 5) - 2, this.widthPipe,
this.widthPipe);
// label
g.setFont(new Font("Ubuntu", Font.PLAIN, 12));
g.setColor(new Color(51, 51, 51));
g.drawString(name, (int) (this.getWidthComponent() / 2 - g.getFontMetrics().stringWidth(this.name) / 2),
this.getWidthComponent() - 12);
}
/**
*
* @param state: true means valve open and false means valve closed.
*/
public void setValveState(boolean state) {
this.state = state;
if (state) {
labelValve.setText("Open");
labelValve.setForeground(Color.darkGray);
labelValve.setBackground(Color.green);
} else {
labelValve.setText("Closed");
labelValve.setForeground(Color.white);
labelValve.setBackground(Color.gray);
}
}
public boolean getValveState() {
return this.state;
}
public int getInputX() {
return (this.getWidthComponent() / 3) + this.getXCoordinate();
}
public int getInputY() {
return this.getYCoordinate();
}
public int getPipeWidth() {
return (int) (this.getWidthComponent() / 3);
}
public int getPipeRadius() {
return (int) (this.getWidthComponent() * this.getPipeRadiusPercentage());
}
}
| mit |
sequarius/SequariusToys | MicroBlog/src/main/java/com/sequarius/microblog/handlers/PageController.java | 2750 | package com.sequarius.microblog.handlers;
import com.sequarius.microblog.entities.Post;
import com.sequarius.microblog.entities.User;
import com.sequarius.microblog.services.PostService;
import com.sequarius.microblog.services.UserService;
import com.sequarius.microblog.utilities.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.print.DocFlavor;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sequarius on 2015/6/6.
*/
@Controller
public class PageController {
@Autowired
private PostService postService;
@Autowired
private UserService userService;
@RequestMapping("/sign_up")
public String signUp() {
return "sign_up";
}
@RequestMapping("/sign_in")
public String signIn() {
return "sign_in";
}
@RequestMapping("/")
public String index(ModelMap model){
List<Post> posts = postService.getPosts();
List<String> formatedPostTime=new ArrayList<String>();
for(Post post:posts){
formatedPostTime.add(TimeUtil.converTimeString(post.getPostTime()));
}
model.addAttribute("posts",posts);
model.addAttribute("post_times",formatedPostTime);
return "index";
}
@RequestMapping("/user_index/{username}")
public String userIndex(@PathVariable String username,ModelMap model){
List<Post> posts = postService.findPostByUserName(username);
List<String> formatedPostTime=new ArrayList<String>();
for(Post post:posts){
formatedPostTime.add(TimeUtil.converTimeString(post.getPostTime()));
}
try {
model.addAttribute("username", URLEncoder.encode(username, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
model.addAttribute("user",userService.findUserByUsername(username));
model.addAttribute("posts",posts);
model.addAttribute("post_times",formatedPostTime);
return "user_index";
}
@RequestMapping("/edit_user_info")
public String editUserInfo(@CookieValue(value = "user_name",required = true)String username,ModelMap model){
User user=userService.findUserByUsername(username);
model.addAttribute(user);
return "edit_user_info";
}
@RequestMapping("/test")
public String test(){
return "testpage";
}
}
| mit |
munificent/magpie | src/com/stuffwithstuff/magpie/ast/ImportExpr.java | 1457 | package com.stuffwithstuff.magpie.ast;
import java.util.List;
import com.stuffwithstuff.magpie.parser.Position;
public class ImportExpr extends Expr {
/**
* Creates a new ImportExpr.
*
* @param module The name of the module to import. Will start with "." for
* a relative import.
*/
ImportExpr(Position position, String scheme, String module,
String prefix, boolean isOnly, List<ImportDeclaration> declarations) {
super(position);
mScheme = scheme;
mModule = module;
mPrefix = prefix;
mIsOnly = isOnly;
mDeclarations = declarations;
}
public String getScheme() { return mScheme; }
public String getModule() { return mModule; }
public String getPrefix() { return mPrefix; }
public boolean isOnly() { return mIsOnly; }
public List<ImportDeclaration> getDeclarations() { return mDeclarations; }
@Override
public <R, C> R accept(ExprVisitor<R, C> visitor, C context) {
return visitor.visit(this, context);
}
@Override
public void toString(StringBuilder builder, String indent) {
builder.append("import ");
if (mScheme != null) builder.append(mScheme).append(":");
builder.append(mModule);
// TODO(bob): Update.
builder.append("\n");
}
private final String mScheme;
private final String mModule;
private final String mPrefix;
private final boolean mIsOnly;
private final List<ImportDeclaration> mDeclarations;
}
| mit |
sharpstewie/ICS4UFinal | src/mainFrame_v2.java | 9675 | import java.awt.EventQueue;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.ImageIcon;
import javax.swing.JLayeredPane;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.UIManager;
import javax.swing.JButton;
import com.robrua.orianna.api.core.RiotAPI;
import com.robrua.orianna.type.core.common.Region;
import com.robrua.orianna.type.core.staticdata.Champion;
public class mainFrame_v2 {
JCheckBox checkPassive, checkDefault, checkUlti;
JLabel lblLoadingGif;
static List<Champion> champions;
JFrame frame;
JButton btnStart;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() { //secure way to run swing applications
public void run() {
try {
mainFrame_v2 window = new mainFrame_v2();
String disc = "\"Guess That Champion!\" isn't endorsed by Riot Games and doesn't reflect \nthe views or opinions of Riot Games or anyone officially involved in producing or managing League of Legends. \nLeague of Legends and Riot Games are trademarks or registered trademarks of Riot Games, Inc. League of Legends � Riot Games, Inc.";
JOptionPane.showMessageDialog(window.frame, disc, "Disclaimer", JOptionPane.WARNING_MESSAGE );
// Get list of champions
BufferedReader in = new BufferedReader(new FileReader("api-key.txt"));
String text = in.readLine();
in.close();
RiotAPI.setMirror(Region.NA);
RiotAPI.setRegion(Region.NA);
RiotAPI.setAPIKey(text);
champions = RiotAPI.getChampions();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* @throws IOException
*/
public mainFrame_v2() throws IOException {
initialize();
}
public mainFrame_v2(int score) throws IOException {
String disc = "You got a score of: " + score;
JOptionPane.showMessageDialog(this.frame, disc, "Alert", JOptionPane.WARNING_MESSAGE );
reset();
}
/**
* Initialize the contents of the frame.
* @throws IOException
*/
private void initialize() throws IOException {
frame = new JFrame("Guess That Champion!");
frame.setResizable(false);
frame.setBounds(100, 100, 687, 289);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
JLayeredPane mainPane = new JLayeredPane(); //The content of the launcher are layered to enable
frame.getContentPane().add(mainPane, "name_78800221383633"); //use of background image.
BufferedImage BG = ImageIO.read(new File("src/morgana_vs_ahri_3.jpg"));
mainPane.setLayout(null);
URL gifUrl = getClass().getResource("loading.gif");
ImageIcon loadingGif = new ImageIcon(gifUrl.getPath());
lblLoadingGif = new JLabel(loadingGif);
lblLoadingGif.setBounds(272, 140, 128, 128);
mainPane.add(lblLoadingGif);
lblLoadingGif.setVisible(false);
JLabel lblBG = new JLabel(new ImageIcon(BG));
lblBG.setBounds(-50, -10, 737, 375);
mainPane.add(lblBG);
JLabel lblTitle = new JLabel("Guess That Champion!");
lblTitle.setForeground(UIManager.getColor("Menu.background"));
lblTitle.setBounds(10, 23, 644, 27);
lblTitle.setFont(new Font("WeblySleek UI Semibold", Font.BOLD, 20));
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
mainPane.setLayer(lblTitle, 1);
mainPane.add(lblTitle);
checkPassive = new JCheckBox("Champion Passive");
checkPassive.setForeground(Color.GREEN);
checkPassive.setFont(new Font("Yu Gothic", Font.BOLD, 14));
checkPassive.setOpaque(false);
mainPane.setLayer(checkPassive, 1);
checkPassive.setBounds(6, 88, 164, 37);
mainPane.add(checkPassive);
checkDefault = new JCheckBox("Champion Default Ability");
checkDefault.setOpaque(false);
checkDefault.setForeground(Color.GREEN);
checkDefault.setFont(new Font("Yu Gothic", Font.BOLD, 14));
checkDefault.setToolTipText("Such as champion Q, W, E");
mainPane.setLayer(checkDefault, 1);
checkDefault.setBounds(227, 88, 225, 37);
mainPane.add(checkDefault);
checkUlti = new JCheckBox("Champion Ultimate");
checkUlti.setOpaque(false);
checkUlti.setForeground(Color.GREEN);
checkUlti.setFont(new Font("Yu Gothic", Font.BOLD, 14));
mainPane.setLayer(checkUlti, 1);
checkUlti.setBounds(503, 88, 172, 37);
mainPane.add(checkUlti);
btnStart = new JButton("Start!");
btnStart.setFont(new Font("Franklin Gothic Medium", Font.PLAIN, 15));
mainPane.setLayer(btnStart, 1);
btnStart.setBounds(260, 171, 150, 62);
mainPane.add(btnStart);
btnStart.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me) {
try {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("lib/sounds/open.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Sound error on playing file: " + "lib/sounds/open.wav");
ex.printStackTrace();
}
btnStart.setVisible(false);
lblLoadingGif.setVisible(true);
if(!(checkPassive.isSelected() || checkDefault.isSelected() || checkUlti.isSelected()) )
new guiGuess_v1_1(champions, true, true, true);
else
new guiGuess_v1_1(champions, checkPassive.isSelected(), checkDefault.isSelected(), checkUlti.isSelected());
frame.dispose();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void reset() throws IOException {
frame = new JFrame("Guess That Champion!");
frame.setResizable(false);
frame.setBounds(100, 100, 687, 289);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
JLayeredPane mainPane = new JLayeredPane(); //The content of the launcher are layered to enable
frame.getContentPane().add(mainPane, "name_78800221383633"); //use of background image.
BufferedImage BG = ImageIO.read(new File("src/morgana_vs_ahri_3.jpg"));
mainPane.setLayout(null);
URL gifUrl = getClass().getResource("loading.gif");
ImageIcon loadingGif = new ImageIcon(gifUrl.getPath());
lblLoadingGif = new JLabel(loadingGif);
lblLoadingGif.setBounds(272, 140, 128, 128);
mainPane.add(lblLoadingGif);
lblLoadingGif.setVisible(false);
JLabel lblBG = new JLabel(new ImageIcon(BG));
lblBG.setBounds(-50, -10, 737, 375);
mainPane.add(lblBG);
JLabel lblTitle = new JLabel("Guess That Champion!");
lblTitle.setForeground(UIManager.getColor("Menu.background"));
lblTitle.setBounds(10, 23, 644, 27);
lblTitle.setFont(new Font("WeblySleek UI Semibold", Font.BOLD, 20));
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
mainPane.setLayer(lblTitle, 1);
mainPane.add(lblTitle);
checkPassive = new JCheckBox("Champion Passive");
checkPassive.setForeground(Color.GREEN);
checkPassive.setFont(new Font("Yu Gothic", Font.BOLD, 14));
checkPassive.setOpaque(false);
mainPane.setLayer(checkPassive, 1);
checkPassive.setBounds(6, 88, 164, 37);
mainPane.add(checkPassive);
checkDefault = new JCheckBox("Champion Default Ability");
checkDefault.setOpaque(false);
checkDefault.setForeground(Color.GREEN);
checkDefault.setFont(new Font("Yu Gothic", Font.BOLD, 14));
checkDefault.setToolTipText("Such as champion Q, W, E");
mainPane.setLayer(checkDefault, 1);
checkDefault.setBounds(227, 88, 225, 37);
mainPane.add(checkDefault);
checkUlti = new JCheckBox("Champion Ultimate");
checkUlti.setOpaque(false);
checkUlti.setForeground(Color.GREEN);
checkUlti.setFont(new Font("Yu Gothic", Font.BOLD, 14));
mainPane.setLayer(checkUlti, 1);
checkUlti.setBounds(503, 88, 172, 37);
mainPane.add(checkUlti);
btnStart = new JButton("Start!");
btnStart.setFont(new Font("Franklin Gothic Medium", Font.PLAIN, 15));
mainPane.setLayer(btnStart, 1);
btnStart.setBounds(260, 171, 150, 62);
mainPane.add(btnStart);
btnStart.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me) {
try {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("lib/sounds/open.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Sound error on playing file: " + "lib/sounds/open.wav");
ex.printStackTrace();
}
btnStart.setVisible(false);
lblLoadingGif.setVisible(true);
new guiGuess_v1_1(champions, checkPassive.isSelected(), checkDefault.isSelected(), checkUlti.isSelected());
frame.dispose();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
| mit |
mglezh/Android | EarthQuakes/app/src/main/java/com/mglezh/earthquakes/fragments/abstracts/AbstractMapFragment.java | 2359 | package com.mglezh.earthquakes.fragments.abstracts;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.mglezh.earthquakes.database.EarthQuakesDB;
import com.mglezh.earthquakes.model.EarthQuake;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cursomovil on 13/04/15.
*/
public abstract class AbstractMapFragment extends MapFragment implements GoogleMap.OnMapLoadedCallback {
// private Activity context;
protected GoogleMap mMap; // Might be null if Google Play services APK is not available.
protected List<EarthQuake> earthQuakes;
protected EarthQuakesDB earthQuakeDB;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.earthQuakeDB = new EarthQuakesDB(getActivity());
earthQuakes = new ArrayList<>();
//mMap = getMap();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = super.onCreateView(inflater, container, savedInstanceState);
mMap = getMap();
mMap.setOnMapLoadedCallback(this);
return layout;
}
@Override
public void onResume() {
super.onResume();
setupMapIfNedded();
mMap.setOnMapLoadedCallback(this);
}
private void setupMapIfNedded(){
if (mMap == null) {
mMap = getMap();
}
}
public MarkerOptions createMarker(EarthQuake earthQuake)
{
LatLng point = new LatLng(earthQuake.getCoords().getLng(), earthQuake.getCoords().getLat());
MarkerOptions marker = new MarkerOptions()
.position(point)
.title(earthQuake.getMagnitudeFormated().concat(" ").concat(earthQuake.getPlace()))
.snippet(earthQuake.getCoords().toString());
mMap.addMarker(marker);
return marker;
}
abstract protected void getData();
abstract protected void showMap();
@Override
public void onMapLoaded() {
this.getData();
this.showMap();
}
}
| mit |
HaoyuHu/Bundleless | app/src/main/java/com/huhaoyu/bundleless/BundlelessBuilderImpl.java | 1875 | package com.huhaoyu.bundleless;
import android.os.Bundle;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Implement of Bundleless Builder
* Created by coderhuhy on 16/2/19.
*/
public class BundlelessBuilderImpl implements BundlelessBuilder {
private BundlelessManager manager;
private Map<String, String> store;
public BundlelessBuilderImpl() {
manager = BundlelessManager.getInstance();
manager.init();
store = new HashMap<>();
}
@Override
public BundlelessBuilder put(String key, Object object) {
String json = manager.serialize(key, object);
store.put(key, json);
return this;
}
@Override
public BundlelessBuilder put(String key, String string) {
String json = manager.serialize(key, string);
store.put(key, json);
return this;
}
@Override
public BundlelessBuilder put(String key, int i) {
String json = manager.serialize(key, i);
store.put(key, json);
return this;
}
@Override
public BundlelessBuilder put(String key, Date date) {
String json = manager.serialize(key, date);
store.put(key, json);
return this;
}
@Override
public BundlelessBuilder put(String key, double d) {
String json = manager.serialize(key, d);
store.put(key, json);
return this;
}
@Override
public BundlelessBuilder put(String key, float f) {
String json = manager.serialize(key, f);
store.put(key, json);
return this;
}
@Override
public Bundle toBundle() {
Bundle bundle = new Bundle();
for (Map.Entry<String, String> entry : store.entrySet()) {
bundle.putString(entry.getKey(), entry.getValue());
}
store.clear();
return bundle;
}
}
| mit |
CyclopsMC/CyclopsCore | src/main/java/org/cyclops/cyclopscore/config/extendedconfig/FluidConfig.java | 3536 | package org.cyclops.cyclopscore.config.extendedconfig;
import net.minecraft.fluid.Fluid;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.ForgeFlowingFluid;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.IForgeRegistry;
import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.datastructure.Wrapper;
import org.cyclops.cyclopscore.init.ModBase;
import javax.annotation.Nullable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Config for fluids.
* @author rubensworks
* @see ExtendedConfig
*/
public abstract class FluidConfig extends ExtendedConfig<FluidConfig, ForgeFlowingFluid.Properties> {
/**
* Make a new instance.
* @param mod The mod instance.
* @param namedId The unique name ID for the configurable.
* @param elementConstructor The element constructor.
*/
public FluidConfig(ModBase mod, String namedId, Function<FluidConfig, ForgeFlowingFluid.Properties> elementConstructor) {
super(mod, namedId, elementConstructor);
}
protected static ForgeFlowingFluid.Properties getDefaultFluidProperties(ModBase mod, String texturePrefixPath,
Consumer<FluidAttributes.Builder> fluidAttributesConsumer) {
FluidAttributes.Builder fluidAttributes = FluidAttributes.builder(
new ResourceLocation(mod.getModId(), texturePrefixPath + "_still"),
new ResourceLocation(mod.getModId(), texturePrefixPath + "_flow")
);
fluidAttributesConsumer.accept(fluidAttributes);
Wrapper<ForgeFlowingFluid.Properties> properties = new Wrapper<>();
final Wrapper<Fluid> source = new Wrapper<>();
final Wrapper<Fluid> flowing = new Wrapper<>();
properties.set(new ForgeFlowingFluid.Properties(
new Supplier<Fluid>() {
@Override
public Fluid get() {
if (source.get() == null) {
source.set(new ForgeFlowingFluid.Source(properties.get()));
}
return source.get();
}
},
new Supplier<Fluid>() {
@Override
public Fluid get() {
if (flowing.get() == null) {
flowing.set(new ForgeFlowingFluid.Flowing(properties.get()));
}
return flowing.get();
}
},
fluidAttributes
));
return properties.get();
}
@Override
public String getTranslationKey() {
return "block." + getMod().getModId() + ".block_" + getNamedId();
}
@Override
public ConfigurableType getConfigurableType() {
return ConfigurableType.FLUID;
}
/**
* Get the still icon location.
* @return The icon location.
*/
public ResourceLocation getIconLocationStill() {
return new ResourceLocation(getMod().getModId(), "blocks/" + getNamedId() + "_still");
}
/**
* Get the flow icon location.
* @return The icon location.
*/
public ResourceLocation getIconLocationFlow() {
return new ResourceLocation(getMod().getModId(), "blocks/" + getNamedId() + "_flow");
}
}
| mit |
atealxt/work-workspaces | minaDemo/prj/test/minademo/string/StringClient.java | 1972 | package minademo.string;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import minademo.Constants;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
public class StringClient {
public void sendMsgSocket() throws UnknownHostException, IOException {
Socket server = new Socket(InetAddress.getLocalHost(), Constants.PORT);
PrintWriter serverOutput = new PrintWriter(server.getOutputStream());
serverOutput.println("Hello MySocketClient");
serverOutput.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
System.out.println(in.readLine());
server.close();
}
public void sendMsg() {
SocketConnector connector = new NioSocketConnector();
connector.setConnectTimeoutMillis(5000);
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
connector.setHandler(new StringSendHandler("hello mina"));
ConnectFuture future = connector.connect(new InetSocketAddress(Constants.PORT));
// wait until the summation is done
future.awaitUninterruptibly();
future.getSession().getCloseFuture().awaitUninterruptibly();
connector.dispose();
}
public static void main(final String[] args) throws Exception {
// new StringClient().sendMsgSocket();
new StringClient().sendMsg();
}
}
| mit |
FanHuaRan/interview.algorithm | java/saopdemo/src/main/java/com/fhr/saopdemo/App.java | 179 | package com.fhr.saopdemo;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| mit |
meteotester/meteotester | src/main/java/com/meteotester/ForecastServlet.java | 2289 | package com.meteotester;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.meteotester.dao.PlacesDAO;
import com.meteotester.dao.SourcesDAO;
import com.meteotester.entities.Place;
import com.meteotester.entities.Source;
import com.meteotester.util.Parser;
/**
* Servlet implementation class ForecastServlet
*/
@WebServlet("/forecasts")
public class ForecastServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger log = Logger.getLogger(ForecastServlet.class);
PlacesDAO placesHelper = null;
SourcesDAO sourcesHelper = null;
/**
* @see HttpServlet#HttpServlet()
*/
public ForecastServlet() {
super();
// TODO Auto-generated constructor stub
placesHelper = new PlacesDAO();
sourcesHelper = new SourcesDAO();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
// Use "out" to send content to browser
String result = "";
Place place = null;
String sPlace = request.getParameter("place");
if ((sPlace != null) && (!sPlace.equals(""))) {
place = placesHelper.getPlaceByName(sPlace);
}
if (place == null)
place = placesHelper.getPlaceByName("Madrid");
String sourceId = request.getParameter("source");
if ((sourceId == null) || (sourceId.equals(""))) {
// The request parameter 'param' was not present in the query string
// e.g. http://hostname.com?a=b
HashMap<String, Source> sources = sourcesHelper.getForecastSources();
for (String key: sources.keySet()) {
Source source = sources.get(key);
result += Parser.parse2store(source, place);
}
} else {
Source source = sourcesHelper.getForecastSourceById(sourceId);
result += Parser.parse2store(source, place);
}
log.info(result);
out.println(result);
}
}
| mit |
kamalmahmudi/sia | src/main/java/id/ac/itb/dao/RoleDAO.java | 458 | package id.ac.itb.dao;
import id.ac.itb.model.AbstractModel;
import id.ac.itb.model.Role;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public class RoleDAO extends AbstractDAO {
public RoleDAO() {
modelClass = Role.class;
}
@Override
public AbstractModel newModel() {
return new Role();
}
}
| mit |
RomainSabathe/MyBodyweightTrainer | app/src/main/java/Exercises/F.java | 153 | package Exercises;
/**
* Created by root on 22/01/17.
*/
public class F extends Exercise {
public F() {
super("Saut extension");
}
}
| mit |
cowthan/Ayo2022 | ProjWechat/src/com/fanxin/huangfangyi/main/fragment/FragmentProfile.java | 5189 | package com.fanxin.huangfangyi.main.fragment;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.redpacketui.utils.RedPacketUtil;
import com.fanxin.huangfangyi.DemoApplication;
import com.fanxin.huangfangyi.DemoHelper;
import com.fanxin.huangfangyi.R;
import com.fanxin.huangfangyi.main.FXConstant;
import com.fanxin.huangfangyi.main.activity.PasswordResetActivity;
import com.fanxin.huangfangyi.main.activity.ProfileActivity;
import com.fanxin.huangfangyi.main.activity.SettingsActivity;
import com.fanxin.huangfangyi.main.moments.SocialFriendActivity;
public class FragmentProfile extends Fragment implements View.OnClickListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
setListener();
}
private void initView(){
ImageView ivAvatar= (ImageView) getView().findViewById(R.id.iv_avatar);
TextView tvNick= (TextView) getView().findViewById(R.id.tv_name);
TextView tvFxid= (TextView) getView().findViewById(R.id.tv_fxid);
JSONObject jsonObject=DemoApplication.getInstance().getUserJson();
Glide.with(this).load(FXConstant.URL_AVATAR+ jsonObject.getString(FXConstant.JSON_KEY_AVATAR)).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.fx_default_useravatar).into(ivAvatar);
tvNick.setText(jsonObject.getString(FXConstant.JSON_KEY_NICK));
String fxid=jsonObject.getString(FXConstant.JSON_KEY_FXID);
if(TextUtils.isEmpty(fxid)){
fxid="未设置";
}
fxid="微信号:"+fxid;
tvFxid.setText(fxid);
}
private void setListener(){
getView().findViewById(R.id.re_myinfo).setOnClickListener(this);
getView().findViewById(R.id.re_setting).setOnClickListener(this);
getView().findViewById(R.id.re_wallet).setOnClickListener(this);
getView().findViewById(R.id.re_xiangce).setOnClickListener(this);
getView().findViewById(R.id.re_fanxin).setOnClickListener(this);
getView().findViewById(R.id.re_xiangce).setOnClickListener(this);
getView().findViewById(R.id.re_yunzhanghu).setOnClickListener(this);
getView().findViewById(R.id.re_find_password).setOnClickListener(this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode== Activity.RESULT_OK){
initView();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.re_myinfo:
startActivityForResult(new Intent(getActivity(), ProfileActivity.class),0);
break;
case R.id.re_setting:
startActivity(new Intent(getActivity(), SettingsActivity.class));
break;
case R.id.re_wallet:
RedPacketUtil.startChangeActivity(getActivity());
break;
case R.id.re_xiangce:
startActivity(new Intent(getActivity(), SocialFriendActivity.class).putExtra("friendID", DemoHelper.getInstance().getCurrentUsernName()));
break;
case R.id.re_yunzhanghu:
joinQQGroup("ycxd0w_eXmTbKIjyDdHb5Dy_-ZhY8E7t");
break;
case R.id.re_fanxin:
joinQQGroup("5QH7bwWtFt5dCwIlIp__y4nuVF1rggp1");
break;
case R.id.re_find_password:
startActivity(new Intent(getActivity(), PasswordResetActivity.class).putExtra("isReset",true));
break;
}
}
public boolean joinQQGroup(String key) {
Intent intent = new Intent();
intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
// 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
startActivity(intent);
return true;
} catch (Exception e) {
// 未安装手Q或安装的版本不支持
Toast.makeText(getContext(),"本设备未安装手机QQ",Toast.LENGTH_LONG).show();
return false;
}
}
}
| mit |
gseteamproject/Examples | examples/src/main/java/employment/RequesterAgent.java | 12582 | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package employment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import employment.ontology.Address;
import employment.ontology.Company;
import employment.ontology.EmploymentOntology;
import employment.ontology.Engage;
import employment.ontology.Person;
import employment.ontology.WorksFor;
import jade.content.abs.AbsContentElementList;
import jade.content.abs.AbsObject;
import jade.content.abs.AbsPredicate;
import jade.content.lang.Codec;
import jade.content.lang.sl.SLCodec;
import jade.content.lang.sl.SLVocabulary;
import jade.content.onto.Ontology;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.SequentialBehaviour;
import jade.domain.FIPANames;
import jade.lang.acl.ACLMessage;
import jade.proto.SimpleAchieveREInitiator;
/**
* This agent is able to handle the engagement of people by requesting an
* engager-agent to do that. It first gets from the user
* <ul>
* <li>The name of the engager agent to send engagement requests to.</li>
* <li>The details of the company where to engage people</li>
* </ul>
* Then it cyclically gets from the user the details of a person to engage and
* handles the engagement of that person in collaboration with the initially
* indicated engager agent.
*
* <b>Note:</b> While entering input data, all fields composed of more than one
* word must be enclosed in "". E.g. the name Giovanni Caire must be entered as
* "Giovanni Caire".
*
* @author Giovanni Caire - CSELT S.p.A
* @version $Date: 2002-07-31 17:27:34 +0200 (mer, 31 lug 2002) $ $Revision:
* 3315 $
* @see employment.EngagerAgent
*/
public class RequesterAgent extends Agent {
private static final long serialVersionUID = 4027172853168232865L;
// AGENT BEHAVIOURS
/**
* Main behavior for the Requester Agent. First the details of a person to
* engage are requested to the user. Then a check is performed to verify
* that the indicated person is not already working for the indicated
* company Finally, according to the above check, the engagement is
* requested. This behavior is executed cyclically.
*/
class HandleEngagementBehaviour extends SequentialBehaviour {
private static final long serialVersionUID = 1713046792590983441L;
// Local variables
Behaviour queryBehaviour = null;
Behaviour requestBehaviour = null;
// Constructor
public HandleEngagementBehaviour(Agent myAgent) {
super(myAgent);
}
// This is executed at the beginning of the behavior
public void onStart() {
System.out.println("Engagement started");
// Get detail of person to be engaged
Person person = new Person();
person.getFromStandardInputStream();
// Create an object representing the fact that person p works for
// company c
WorksFor wf = new WorksFor();
wf.setPerson(person);
wf.setCompany(((RequesterAgent) myAgent).targetCompany);
// Create an ACL message to query the engager agent if the above
// fact is true or false
ACLMessage queryMsg = new ACLMessage(ACLMessage.QUERY_IF);
queryMsg.addReceiver(((RequesterAgent) myAgent).engager);
queryMsg.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
queryMsg.setOntology(EmploymentOntology.NAME);
// Write the works for predicate in the :content slot of the message
try {
myAgent.getContentManager().fillContent(queryMsg, wf);
} catch (Exception e) {
e.printStackTrace();
}
// Create and add a behavior to query the engager agent whether
// person p already works for company c following a FIPAQeury
// protocol
queryBehaviour = new CheckAlreadyWorkingBehaviour(myAgent, queryMsg);
addSubBehaviour(queryBehaviour);
}
// This is executed at the end of the behavior
public int onEnd() {
// Check whether the user wants to continue
try {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Would you like to continue?[y/n] ");
String stop = buff.readLine();
if (stop.equalsIgnoreCase("y")) {
reset(); // This makes this behavior be cyclically executed
myAgent.addBehaviour(this);
} else
myAgent.doDelete(); // Exit
} catch (IOException ioe) {
System.err.println("I/O error: " + ioe.getMessage());
}
return 0;
}
// Extends the reset method in order to remove the sub-behaviors that
// are dynamically added
public void reset() {
if (queryBehaviour != null) {
removeSubBehaviour(queryBehaviour);
queryBehaviour = null;
}
if (requestBehaviour != null) {
removeSubBehaviour(requestBehaviour);
requestBehaviour = null;
}
super.reset();
}
}
/**
* This behavior embeds the check that the indicated person is not already
* working for the indicated company. This is done following a FIPA-Query
* interaction protocol
*/
class CheckAlreadyWorkingBehaviour extends SimpleAchieveREInitiator {
private static final long serialVersionUID = 1242323210121240249L;
// Constructor
public CheckAlreadyWorkingBehaviour(Agent myAgent, ACLMessage queryMsg) {
super(myAgent, queryMsg);
queryMsg.setProtocol(FIPANames.InteractionProtocol.FIPA_QUERY);
}
protected void handleInform(ACLMessage msg) {
try {
AbsPredicate cs = (AbsPredicate) myAgent.getContentManager().extractAbsContent(msg);
Ontology o = myAgent.getContentManager().lookupOntology(EmploymentOntology.NAME);
if (cs.getTypeName().equals(EmploymentOntology.WORKS_FOR)) {
// The indicated person is already working for company c.
// Inform the user
WorksFor wf = (WorksFor) o.toObject((AbsObject) cs);
Person p = (Person) wf.getPerson();
Company c = (Company) wf.getCompany();
System.out.println("Person " + p.getName() + " is already working for " + c.getName());
} else if (cs.getTypeName().equals(SLVocabulary.NOT)) {
// The indicated person is NOT already working for company
// c.
// Get person and company details and create an object
// representing the engagement action
WorksFor wf = (WorksFor) o.toObject(cs.getAbsObject(SLVocabulary.NOT_WHAT));
Person p = (Person) wf.getPerson();
Company c = (Company) wf.getCompany();
Engage e = new Engage();
e.setPerson(p);
e.setCompany(c);
Action a = new Action();
a.setActor(((RequesterAgent) myAgent).engager);
a.setAction(e);
// Create an ACL message to request the above action
ACLMessage requestMsg = new ACLMessage(ACLMessage.REQUEST);
requestMsg.addReceiver(((RequesterAgent) myAgent).engager);
requestMsg.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
requestMsg.setOntology(EmploymentOntology.NAME);
// Write the action in the :content slot of the message
try {
myAgent.getContentManager().fillContent(requestMsg, a);
} catch (Exception pe) {
}
// Create and add a behavior to request the engager agent to
// engage
// person p in company c following a FIPARequest protocol
((HandleEngagementBehaviour) parent).requestBehaviour = new RequestEngagementBehaviour(myAgent,
requestMsg);
((SequentialBehaviour) parent)
.addSubBehaviour(((HandleEngagementBehaviour) parent).requestBehaviour);
} else {
// Unexpected response received from the engager agent.
// Inform the user
System.out.println("Unexpected response from engager agent");
}
} // End of try
catch (Codec.CodecException fe) {
System.err.println("FIPAException in fill/extract Msgcontent:" + fe.getMessage());
} catch (OntologyException fe) {
System.err.println("OntologyException in getRoleName:" + fe.getMessage());
}
}
}
/**
* This behavior embeds the request to engage the indicated person in the
* indicated company. This is done following a FIPA-Request interaction
* protocol
*/
class RequestEngagementBehaviour extends SimpleAchieveREInitiator {
private static final long serialVersionUID = -8699565427879297481L;
// Constructor
public RequestEngagementBehaviour(Agent myAgent, ACLMessage requestMsg) {
super(myAgent, requestMsg);
requestMsg.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
}
protected void handleAgree(ACLMessage msg) {
System.out.println("Engagement agreed. Waiting for completion notification...");
}
protected void handleInform(ACLMessage msg) {
System.out.println("Engagement successfully completed");
}
protected void handleNotUnderstood(ACLMessage msg) {
System.out.println("Engagement request not understood by engager agent");
}
protected void handleFailure(ACLMessage msg) {
System.out.println("Engagement failed");
// Get the failure reason and communicate it to the user
try {
AbsPredicate absPred = (AbsPredicate) myAgent.getContentManager().extractContent(msg);
System.out.println("The reason is: " + absPred.getTypeName());
} catch (Codec.CodecException fe) {
System.err.println("FIPAException reading failure reason: " + fe.getMessage());
} catch (OntologyException oe) {
System.err.println("OntologyException reading failure reason: " + oe.getMessage());
}
}
protected void handleRefuse(ACLMessage msg) {
System.out.println("Engagement refused");
// Get the refusal reason and communicate it to the user
try {
AbsContentElementList list = (AbsContentElementList) myAgent.getContentManager().extractAbsContent(msg);
AbsPredicate absPred = (AbsPredicate) list.get(1);
System.out.println("The reason is: " + absPred.getTypeName());
} catch (Codec.CodecException fe) {
System.err.println("FIPAException reading refusal reason: " + fe.getMessage());
} catch (OntologyException oe) {
System.err.println("OntologyException reading refusal reason: " + oe.getMessage());
}
}
}
// AGENT LOCAL VARIABLES
AID engager; // AID of the agent the engagement requests will have to be
// sent to
Company targetCompany; // The company where people will be engaged
// AGENT SETUP
protected void setup() {
// Register the codec for the SL0 language
getContentManager().registerLanguage(new SLCodec(), FIPANames.ContentLanguage.FIPA_SL0);
// Register the ontology used by this application
getContentManager().registerOntology(EmploymentOntology.getInstance());
// Get from the user the name of the agent the engagement requests
// will have to be sent to
try {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.print("ENTER the local name of the Engager agent --> ");
String name = buff.readLine();
engager = new AID(name, AID.ISLOCALNAME);
// Get from the user the details of the company where people will
// be engaged
targetCompany = new Company();
Address a = new Address();
System.out.println("ENTER details of the company where people will be engaged");
System.out.print(" Company name --> ");
targetCompany.setName(buff.readLine());
System.out.println(" Company address");
System.out.print(" Street ------> ");
a.setStreet(buff.readLine());
System.out.print(" Number ------> ");
a.setNumber(new Long(buff.readLine()));
System.out.print(" City ------> ");
a.setCity(buff.readLine());
targetCompany.setAddress(a);
} catch (IOException ioe) {
System.err.println("I/O error: " + ioe.getMessage());
}
// Create and add the main behavior of this agent
addBehaviour(new HandleEngagementBehaviour(this));
}
}
| mit |
Blackdread/filter-sort-jooq-api | src/test/java/org/blackdread/filtersortjooqapi/filter/ValueTest.java | 4349 | package org.blackdread.filtersortjooqapi.filter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.stream.Stream;
class ValueTest {
static Stream<Value> valuesStream() {
return Stream.of(
new ValueImpl<>("0"),
new ValueImpl<>("0", "oo"),
new ValueImpl<>("0", "oo", 2),
new ValueImpl<>("0", "oo", 2, -66),
new ValueImpl<>("0", "oo", 2, -66, LocalDateTime.now()),
new ValueImpl<>("0", "oo", 2, -66, LocalDateTime.now(), "val")
);
}
@Test
void emptyValueThrows() {
Assertions.assertThrows(IllegalArgumentException.class, ValueImpl::new);
Assertions.assertThrows(IllegalArgumentException.class, () -> new ValueImpl<>(new Object[0]));
final Object ff = null;
Assertions.assertThrows(IllegalArgumentException.class, () -> new ValueImpl<>(ff));
Assertions.assertThrows(IllegalArgumentException.class, () -> new ValueImpl<>(Collections.emptyList()));
}
@ParameterizedTest
@MethodSource("valuesStream")
void sizeWorks(final Value value) {
value.size();
}
@ParameterizedTest
@MethodSource("valuesStream")
void getValue(final Value value) {
for (int i = 0; i < value.size(); i++) {
Assertions.assertNotNull(value.getValue(i));
}
}
@ParameterizedTest
@MethodSource("valuesStream")
void getValueThrowsWhenOutOfRange(final Value value) {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> value.getValue(value.size() + 1));
}
@Test
void getValueWithType() {
final ValueImpl<Object, Object, Object, Object, Object, Object> value = new ValueImpl<>("0", "oo", 2, -66, LocalDateTime.now());
Assertions.assertNotNull(value.getValue(0, String.class));
Assertions.assertNotNull(value.getValue(1, String.class));
Assertions.assertNotNull(value.getValue(2, Integer.class));
Assertions.assertNotNull(value.getValue(3, Integer.class));
Assertions.assertNotNull(value.getValue(4, LocalDateTime.class));
}
@ParameterizedTest
@MethodSource("valuesStream")
void valueStream(final Value value) {
for (int i = 0; i < value.size(); i++) {
final Object val = value.valueStream().skip(i).findFirst().orElseThrow(() -> new IllegalStateException("Shall not happen"));
Assertions.assertEquals(value.getValue(i), val);
}
}
@ParameterizedTest
@MethodSource("valuesStream")
void values(final Value value) {
Assertions.assertEquals(value.size(), value.values().length);
}
@ParameterizedTest
@MethodSource("valuesStream")
void valueWithGetterNumbered(final Value value) {
final int size = value.size();
Assertions.assertNotNull(((Value1) value).value1());
if (size > 1)
Assertions.assertNotNull(((Value2) value).value2());
if (size > 2)
Assertions.assertNotNull(((Value3) value).value3());
if (size > 3)
Assertions.assertNotNull(((Value4) value).value4());
if (size > 4)
Assertions.assertNotNull(((Value5) value).value5());
if (size > 5)
Assertions.assertNotNull(((Value6) value).value6());
}
@ParameterizedTest
@MethodSource("valuesStream")
void valueWithGetterNumberedThrowsOutOfRange(final Value value) {
final int size = value.size();
// No class cast exception as Value == ValueImpl (supposedly)
if (size <= 1)
Assertions.assertThrows(IndexOutOfBoundsException.class, ((Value2) value)::value2);
if (size <= 2)
Assertions.assertThrows(IndexOutOfBoundsException.class, ((Value3) value)::value3);
if (size <= 3)
Assertions.assertThrows(IndexOutOfBoundsException.class, ((Value4) value)::value4);
if (size <= 4)
Assertions.assertThrows(IndexOutOfBoundsException.class, ((Value5) value)::value5);
if (size <= 5)
Assertions.assertThrows(IndexOutOfBoundsException.class, ((Value6) value)::value6);
}
}
| mit |
matgr1/ai-playground | neatsample/src/main/java/matgr/ai/neatsample/CustomWeightedEdge.java | 243 | package matgr.ai.neatsample;
import org.jgrapht.graph.DefaultWeightedEdge;
public class CustomWeightedEdge extends DefaultWeightedEdge {
@Override
public String toString() {
return String.format("%.2f", getWeight());
}
}
| mit |
thiba/FluidPirates-android | app/src/main/java/fluidpirates/fluidpirates_android/fluidPirates.java | 327 | package fluidpirates.fluidpirates_android;
import android.os.Bundle;
import android.app.Activity;
public class fluidPirates extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fluid_pirates);
}
}
| mit |
boggad/jdk9-sample | sample-catalog/spring-jdk9/src/spring.webmvc/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java | 16736 | /*
* Copyright 2002-2016 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.web.servlet.handler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerExecutionChain;
/**
* Abstract base class for URL-mapped {@link org.springframework.web.servlet.HandlerMapping}
* implementations. Provides infrastructure for mapping handlers to URLs and configurable
* URL lookup. For information on the latter, see "alwaysUseFullPath" property.
*
* <p>Supports direct matches, e.g. a registered "/test" matches "/test", and
* various Ant-style pattern matches, e.g. a registered "/t*" pattern matches
* both "/test" and "/team", "/test/*" matches all paths in the "/test" directory,
* "/test/**" matches all paths below "/test". For details, see the
* {@link org.springframework.util.AntPathMatcher AntPathMatcher} javadoc.
*
* <p>Will search all path patterns to find the most exact match for the
* current request path. The most exact match is defined as the longest
* path pattern that matches the current request path.
*
* @author Juergen Hoeller
* @author Arjen Poutsma
* @since 16.04.2003
*/
public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping implements MatchableHandlerMapping {
private Object rootHandler;
private boolean useTrailingSlashMatch = false;
private boolean lazyInitHandlers = false;
private final Map<String, Object> handlerMap = new LinkedHashMap<>();
/**
* Set the root handler for this handler mapping, that is,
* the handler to be registered for the root path ("/").
* <p>Default is {@code null}, indicating no root handler.
*/
public void setRootHandler(Object rootHandler) {
this.rootHandler = rootHandler;
}
/**
* Return the root handler for this handler mapping (registered for "/"),
* or {@code null} if none.
*/
public Object getRootHandler() {
return this.rootHandler;
}
/**
* Whether to match to URLs irrespective of the presence of a trailing slash.
* If enabled a URL pattern such as "/users" also matches to "/users/".
* <p>The default value is {@code false}.
*/
public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) {
this.useTrailingSlashMatch = useTrailingSlashMatch;
}
/**
* Whether to match to URLs irrespective of the presence of a trailing slash.
*/
public boolean useTrailingSlashMatch() {
return this.useTrailingSlashMatch;
}
/**
* Set whether to lazily initialize handlers. Only applicable to
* singleton handlers, as prototypes are always lazily initialized.
* Default is "false", as eager initialization allows for more efficiency
* through referencing the controller objects directly.
* <p>If you want to allow your controllers to be lazily initialized,
* make them "lazy-init" and set this flag to true. Just making them
* "lazy-init" will not work, as they are initialized through the
* references from the handler mapping in this case.
*/
public void setLazyInitHandlers(boolean lazyInitHandlers) {
this.lazyInitHandlers = lazyInitHandlers;
}
/**
* Look up a handler for the URL path of the given request.
* @param request current HTTP request
* @return the handler instance, or {@code null} if none found
*/
@Override
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
Object handler = lookupHandler(lookupPath, request);
if (handler == null) {
// We need to care for the default handler directly, since we need to
// expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.
Object rawHandler = null;
if ("/".equals(lookupPath)) {
rawHandler = getRootHandler();
}
if (rawHandler == null) {
rawHandler = getDefaultHandler();
}
if (rawHandler != null) {
// Bean name or resolved handler?
if (rawHandler instanceof String) {
String handlerName = (String) rawHandler;
rawHandler = getApplicationContext().getBean(handlerName);
}
validateHandler(rawHandler, request);
handler = buildPathExposingHandler(rawHandler, lookupPath, lookupPath, null);
}
}
if (handler != null && logger.isDebugEnabled()) {
logger.debug("Mapping [" + lookupPath + "] to " + handler);
}
else if (handler == null && logger.isTraceEnabled()) {
logger.trace("No handler mapping found for [" + lookupPath + "]");
}
return handler;
}
/**
* Look up a handler instance for the given URL path.
* <p>Supports direct matches, e.g. a registered "/test" matches "/test",
* and various Ant-style pattern matches, e.g. a registered "/t*" matches
* both "/test" and "/team". For details, see the AntPathMatcher class.
* <p>Looks for the most exact pattern, where most exact is defined as
* the longest path pattern.
* @param urlPath URL the bean is mapped to
* @param request current HTTP request (to expose the path within the mapping to)
* @return the associated handler instance, or {@code null} if not found
* @see #exposePathWithinMapping
* @see org.springframework.util.AntPathMatcher
*/
protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {
// Direct match?
Object handler = this.handlerMap.get(urlPath);
if (handler != null) {
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
return buildPathExposingHandler(handler, urlPath, urlPath, null);
}
// Pattern match?
List<String> matchingPatterns = new ArrayList<>();
for (String registeredPattern : this.handlerMap.keySet()) {
if (getPathMatcher().match(registeredPattern, urlPath)) {
matchingPatterns.add(registeredPattern);
}
else if (useTrailingSlashMatch()) {
if (!registeredPattern.endsWith("/") && getPathMatcher().match(registeredPattern + "/", urlPath)) {
matchingPatterns.add(registeredPattern +"/");
}
}
}
String bestPatternMatch = null;
Comparator<String> patternComparator = getPathMatcher().getPatternComparator(urlPath);
if (!matchingPatterns.isEmpty()) {
Collections.sort(matchingPatterns, patternComparator);
if (logger.isDebugEnabled()) {
logger.debug("Matching patterns for request [" + urlPath + "] are " + matchingPatterns);
}
bestPatternMatch = matchingPatterns.get(0);
}
if (bestPatternMatch != null) {
handler = this.handlerMap.get(bestPatternMatch);
if (handler == null) {
Assert.isTrue(bestPatternMatch.endsWith("/"));
handler = this.handlerMap.get(bestPatternMatch.substring(0, bestPatternMatch.length() - 1));
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestPatternMatch, urlPath);
// There might be multiple 'best patterns', let's make sure we have the correct URI template variables
// for all of them
Map<String, String> uriTemplateVariables = new LinkedHashMap<>();
for (String matchingPattern : matchingPatterns) {
if (patternComparator.compare(bestPatternMatch, matchingPattern) == 0) {
Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(matchingPattern, urlPath);
Map<String, String> decodedVars = getUrlPathHelper().decodePathVariables(request, vars);
uriTemplateVariables.putAll(decodedVars);
}
}
if (logger.isDebugEnabled()) {
logger.debug("URI Template variables for request [" + urlPath + "] are " + uriTemplateVariables);
}
return buildPathExposingHandler(handler, bestPatternMatch, pathWithinMapping, uriTemplateVariables);
}
// No handler found...
return null;
}
/**
* Validate the given handler against the current request.
* <p>The default implementation is empty. Can be overridden in subclasses,
* for example to enforce specific preconditions expressed in URL mappings.
* @param handler the handler object to validate
* @param request current HTTP request
* @throws Exception if validation failed
*/
protected void validateHandler(Object handler, HttpServletRequest request) throws Exception {
}
/**
* Build a handler object for the given raw handler, exposing the actual
* handler, the {@link #PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE}, as well as
* the {@link #URI_TEMPLATE_VARIABLES_ATTRIBUTE} before executing the handler.
* <p>The default implementation builds a {@link HandlerExecutionChain}
* with a special interceptor that exposes the path attribute and uri template variables
* @param rawHandler the raw handler to expose
* @param pathWithinMapping the path to expose before executing the handler
* @param uriTemplateVariables the URI template variables, can be {@code null} if no variables found
* @return the final handler object
*/
protected Object buildPathExposingHandler(Object rawHandler, String bestMatchingPattern,
String pathWithinMapping, Map<String, String> uriTemplateVariables) {
HandlerExecutionChain chain = new HandlerExecutionChain(rawHandler);
chain.addInterceptor(new PathExposingHandlerInterceptor(bestMatchingPattern, pathWithinMapping));
if (!CollectionUtils.isEmpty(uriTemplateVariables)) {
chain.addInterceptor(new UriTemplateVariablesHandlerInterceptor(uriTemplateVariables));
}
return chain;
}
/**
* Expose the path within the current mapping as request attribute.
* @param pathWithinMapping the path within the current mapping
* @param request the request to expose the path to
* @see #PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
*/
protected void exposePathWithinMapping(String bestMatchingPattern, String pathWithinMapping, HttpServletRequest request) {
request.setAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, bestMatchingPattern);
request.setAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, pathWithinMapping);
}
/**
* Expose the URI templates variables as request attribute.
* @param uriTemplateVariables the URI template variables
* @param request the request to expose the path to
* @see #PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
*/
protected void exposeUriTemplateVariables(Map<String, String> uriTemplateVariables, HttpServletRequest request) {
request.setAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVariables);
}
@Override
public RequestMatchResult match(HttpServletRequest request, String pattern) {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
if (getPathMatcher().match(pattern, lookupPath)) {
return new RequestMatchResult(pattern, lookupPath, getPathMatcher());
}
else if (useTrailingSlashMatch()) {
if (!pattern.endsWith("/") && getPathMatcher().match(pattern + "/", lookupPath)) {
return new RequestMatchResult(pattern + "/", lookupPath, getPathMatcher());
}
}
return null;
}
/**
* Register the specified handler for the given URL paths.
* @param urlPaths the URLs that the bean should be mapped to
* @param beanName the name of the handler bean
* @throws BeansException if the handler couldn't be registered
* @throws IllegalStateException if there is a conflicting handler registered
*/
protected void registerHandler(String[] urlPaths, String beanName) throws BeansException, IllegalStateException {
Assert.notNull(urlPaths, "URL path array must not be null");
for (String urlPath : urlPaths) {
registerHandler(urlPath, beanName);
}
}
/**
* Register the specified handler for the given URL path.
* @param urlPath the URL the bean should be mapped to
* @param handler the handler instance or handler bean name String
* (a bean name will automatically be resolved into the corresponding handler bean)
* @throws BeansException if the handler couldn't be registered
* @throws IllegalStateException if there is a conflicting handler registered
*/
protected void registerHandler(String urlPath, Object handler) throws BeansException, IllegalStateException {
Assert.notNull(urlPath, "URL path must not be null");
Assert.notNull(handler, "Handler object must not be null");
Object resolvedHandler = handler;
// Eagerly resolve handler if referencing singleton via name.
if (!this.lazyInitHandlers && handler instanceof String) {
String handlerName = (String) handler;
if (getApplicationContext().isSingleton(handlerName)) {
resolvedHandler = getApplicationContext().getBean(handlerName);
}
}
Object mappedHandler = this.handlerMap.get(urlPath);
if (mappedHandler != null) {
if (mappedHandler != resolvedHandler) {
throw new IllegalStateException(
"Cannot map " + getHandlerDescription(handler) + " to URL path [" + urlPath +
"]: There is already " + getHandlerDescription(mappedHandler) + " mapped.");
}
}
else {
if (urlPath.equals("/")) {
if (logger.isInfoEnabled()) {
logger.info("Root mapping to " + getHandlerDescription(handler));
}
setRootHandler(resolvedHandler);
}
else if (urlPath.equals("/*")) {
if (logger.isInfoEnabled()) {
logger.info("Default mapping to " + getHandlerDescription(handler));
}
setDefaultHandler(resolvedHandler);
}
else {
this.handlerMap.put(urlPath, resolvedHandler);
if (logger.isInfoEnabled()) {
logger.info("Mapped URL path [" + urlPath + "] onto " + getHandlerDescription(handler));
}
}
}
}
private String getHandlerDescription(Object handler) {
return "handler " + (handler instanceof String ? "'" + handler + "'" : "of type [" + handler.getClass() + "]");
}
/**
* Return the registered handlers as an unmodifiable Map, with the registered path
* as key and the handler object (or handler bean name in case of a lazy-init handler)
* as value.
* @see #getDefaultHandler()
*/
public final Map<String, Object> getHandlerMap() {
return Collections.unmodifiableMap(this.handlerMap);
}
/**
* Indicates whether this handler mapping support type-level mappings. Default to {@code false}.
*/
protected boolean supportsTypeLevelMappings() {
return false;
}
/**
* Special interceptor for exposing the
* {@link AbstractUrlHandlerMapping#PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE} attribute.
* @see AbstractUrlHandlerMapping#exposePathWithinMapping
*/
private class PathExposingHandlerInterceptor extends HandlerInterceptorAdapter {
private final String bestMatchingPattern;
private final String pathWithinMapping;
public PathExposingHandlerInterceptor(String bestMatchingPattern, String pathWithinMapping) {
this.bestMatchingPattern = bestMatchingPattern;
this.pathWithinMapping = pathWithinMapping;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
exposePathWithinMapping(this.bestMatchingPattern, this.pathWithinMapping, request);
request.setAttribute(INTROSPECT_TYPE_LEVEL_MAPPING, supportsTypeLevelMappings());
return true;
}
}
/**
* Special interceptor for exposing the
* {@link AbstractUrlHandlerMapping#URI_TEMPLATE_VARIABLES_ATTRIBUTE} attribute.
* @see AbstractUrlHandlerMapping#exposePathWithinMapping
*/
private class UriTemplateVariablesHandlerInterceptor extends HandlerInterceptorAdapter {
private final Map<String, String> uriTemplateVariables;
public UriTemplateVariablesHandlerInterceptor(Map<String, String> uriTemplateVariables) {
this.uriTemplateVariables = uriTemplateVariables;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
exposeUriTemplateVariables(this.uriTemplateVariables, request);
return true;
}
}
}
| mit |
Uniandes-isis2603/backstepbystep | backstepbystep-back/src/test/java/co/edu/uniandes/csw/bookstore/test/logic/AuthorLogicTest.java | 8364 | /*
MIT License
Copyright (c) 2017 Universidad de los Andes - ISIS2603
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 co.edu.uniandes.csw.bookstore.test.logic;
import co.edu.uniandes.csw.bookstore.ejb.AuthorLogic;
import co.edu.uniandes.csw.bookstore.entities.AuthorEntity;
import co.edu.uniandes.csw.bookstore.entities.BookEntity;
import co.edu.uniandes.csw.bookstore.entities.PrizeEntity;
import co.edu.uniandes.csw.bookstore.exceptions.BusinessLogicException;
import co.edu.uniandes.csw.bookstore.persistence.AuthorPersistence;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import org.junit.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;
/**
* Pruebas de logica de Authors
*
* @author ISIS2603
*/
@RunWith(Arquillian.class)
public class AuthorLogicTest {
private PodamFactory factory = new PodamFactoryImpl();
@Inject
private AuthorLogic authorLogic;
@PersistenceContext
private EntityManager em;
@Inject
private UserTransaction utx;
private List<AuthorEntity> data = new ArrayList<>();
/**
* @return Devuelve el jar que Arquillian va a desplegar en Payara embebido.
* El jar contiene las clases, el descriptor de la base de datos y el
* archivo beans.xml para resolver la inyección de dependencias.
*/
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addPackage(AuthorEntity.class.getPackage())
.addPackage(AuthorLogic.class.getPackage())
.addPackage(AuthorPersistence.class.getPackage())
.addAsManifestResource("META-INF/persistence.xml", "persistence.xml")
.addAsManifestResource("META-INF/beans.xml", "beans.xml");
}
/**
* Configuración inicial de la prueba.
*/
@Before
public void configTest() {
try {
utx.begin();
clearData();
insertData();
utx.commit();
} catch (Exception e) {
e.printStackTrace();
try {
utx.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
/**
* Limpia las tablas que están implicadas en la prueba.
*/
private void clearData() {
em.createQuery("delete from PrizeEntity").executeUpdate();
em.createQuery("delete from BookEntity").executeUpdate();
em.createQuery("delete from AuthorEntity").executeUpdate();
}
/**
* Inserta los datos iniciales para el correcto funcionamiento de las
* pruebas.
*/
private void insertData() {
for (int i = 0; i < 3; i++) {
AuthorEntity entity = factory.manufacturePojo(AuthorEntity.class);
em.persist(entity);
entity.setBooks(new ArrayList<>());
data.add(entity);
}
AuthorEntity author = data.get(2);
BookEntity entity = factory.manufacturePojo(BookEntity.class);
entity.getAuthors().add(author);
em.persist(entity);
author.getBooks().add(entity);
PrizeEntity prize = factory.manufacturePojo(PrizeEntity.class);
prize.setAuthor(data.get(1));
em.persist(prize);
data.get(1).getPrizes().add(prize);
}
/**
* Prueba para crear un Author.
*/
@Test
public void createAuthorTest() {
AuthorEntity newEntity = factory.manufacturePojo(AuthorEntity.class);
AuthorEntity result = authorLogic.createAuthor(newEntity);
Assert.assertNotNull(result);
AuthorEntity entity = em.find(AuthorEntity.class, result.getId());
Assert.assertEquals(newEntity.getId(), entity.getId());
Assert.assertEquals(newEntity.getName(), entity.getName());
Assert.assertEquals(newEntity.getBirthDate(), entity.getBirthDate());
}
/**
* Prueba para consultar la lista de Authors.
*/
@Test
public void getAuthorsTest() {
List<AuthorEntity> list = authorLogic.getAuthors();
Assert.assertEquals(data.size(), list.size());
for (AuthorEntity entity : list) {
boolean found = false;
for (AuthorEntity storedEntity : data) {
if (entity.getId().equals(storedEntity.getId())) {
found = true;
}
}
Assert.assertTrue(found);
}
}
/**
* Prueba para consultar un Author.
*/
@Test
public void getAuthorTest() {
AuthorEntity entity = data.get(0);
AuthorEntity resultEntity = authorLogic.getAuthor(entity.getId());
Assert.assertNotNull(resultEntity);
Assert.assertEquals(entity.getId(), resultEntity.getId());
Assert.assertEquals(entity.getName(), resultEntity.getName());
Assert.assertEquals(entity.getBirthDate(), resultEntity.getBirthDate());
}
/**
* Prueba para actualizar un Author.
*/
@Test
public void updateAuthorTest() {
AuthorEntity entity = data.get(0);
AuthorEntity pojoEntity = factory.manufacturePojo(AuthorEntity.class);
pojoEntity.setId(entity.getId());
authorLogic.updateAuthor(pojoEntity.getId(), pojoEntity);
AuthorEntity resp = em.find(AuthorEntity.class, entity.getId());
Assert.assertEquals(pojoEntity.getId(), resp.getId());
Assert.assertEquals(pojoEntity.getName(), resp.getName());
Assert.assertEquals(pojoEntity.getBirthDate(), resp.getBirthDate());
}
/**
* Prueba para eliminar un Author
*
* @throws co.edu.uniandes.csw.bookstore.exceptions.BusinessLogicException
*/
@Test
public void deleteAuthorTest() throws BusinessLogicException {
AuthorEntity entity = data.get(0);
authorLogic.deleteAuthor(entity.getId());
AuthorEntity deleted = em.find(AuthorEntity.class, entity.getId());
Assert.assertNull(deleted);
}
/**
* Prueba para eliminar un Author asociado a un libro
*
* @throws co.edu.uniandes.csw.bookstore.exceptions.BusinessLogicException
*/
@Test(expected = BusinessLogicException.class)
public void deleteAuthorConLibroTest() throws BusinessLogicException {
authorLogic.deleteAuthor(data.get(2).getId());
}
/**
* Prueba para eliminar un Author asociado a un premio
*
* @throws co.edu.uniandes.csw.bookstore.exceptions.BusinessLogicException
*/
@Test(expected = BusinessLogicException.class)
public void deleteAuthorConPremioTest() throws BusinessLogicException {
authorLogic.deleteAuthor(data.get(1).getId());
}
}
| mit |
laiis/ViewFramework | library/src/main/java/idv/laiis/viewframework/adapters/impl/ViewFrameworkCommonAdapter.java | 1395 | package idv.laiis.viewframework.adapters.impl;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import idv.laiis.viewframework.adapters.AbstractCommonAdapter;
import idv.laiis.viewframework.factories.ViewHolderFactory;
import idv.laiis.viewframework.viewholders.AbstractViewHolder;
public final class ViewFrameworkCommonAdapter<T> extends AbstractCommonAdapter<T> {
public ViewFrameworkCommonAdapter(Context context, Class<?> cls) {
this(context, null, cls);
}
public ViewFrameworkCommonAdapter(Context context, Fragment fragment, Class<?> cls) {
super(context, fragment, cls);
}
@Override
public final View getView(int position, View convertView, ViewGroup parent) {
AbstractViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = ViewHolderFactory.newInstance().getViewHolder(mContext, mCls);
convertView = viewHolder.initialViewHolder(mContext, mFragment, this, parent, position);
convertView.setTag(viewHolder);
} else {
viewHolder = (AbstractViewHolder) convertView.getTag();
}
viewHolder.filloutViewHolderContent(mContext, mFragment, getItem(position), getData(), position);
viewHolder.playAnimationOrAnimator();
return convertView;
}
}
| mit |
dirtyfilthy/dirtyfilthy-bouncycastle | net/dirtyfilthy/bouncycastle/asn1/x509/ExtendedKeyUsage.java | 3264 | package net.dirtyfilthy.bouncycastle.asn1.x509;
import net.dirtyfilthy.bouncycastle.asn1.ASN1Encodable;
import net.dirtyfilthy.bouncycastle.asn1.ASN1EncodableVector;
import net.dirtyfilthy.bouncycastle.asn1.ASN1Sequence;
import net.dirtyfilthy.bouncycastle.asn1.ASN1TaggedObject;
import net.dirtyfilthy.bouncycastle.asn1.DERObject;
import net.dirtyfilthy.bouncycastle.asn1.DERObjectIdentifier;
import net.dirtyfilthy.bouncycastle.asn1.DERSequence;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* The extendedKeyUsage object.
* <pre>
* extendedKeyUsage ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
* </pre>
*/
public class ExtendedKeyUsage
extends ASN1Encodable
{
Hashtable usageTable = new Hashtable();
ASN1Sequence seq;
public static ExtendedKeyUsage getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
return getInstance(ASN1Sequence.getInstance(obj, explicit));
}
public static ExtendedKeyUsage getInstance(
Object obj)
{
if (obj instanceof ExtendedKeyUsage)
{
return (ExtendedKeyUsage)obj;
}
if(obj instanceof ASN1Sequence)
{
return new ExtendedKeyUsage((ASN1Sequence)obj);
}
if (obj instanceof X509Extension)
{
return getInstance(X509Extension.convertValueToObject((X509Extension)obj));
}
throw new IllegalArgumentException("Invalid ExtendedKeyUsage: " + obj.getClass().getName());
}
public ExtendedKeyUsage(
KeyPurposeId usage)
{
this.seq = new DERSequence(usage);
this.usageTable.put(usage, usage);
}
public ExtendedKeyUsage(
ASN1Sequence seq)
{
this.seq = seq;
Enumeration e = seq.getObjects();
while (e.hasMoreElements())
{
Object o = e.nextElement();
if (!(o instanceof DERObjectIdentifier))
{
throw new IllegalArgumentException("Only DERObjectIdentifiers allowed in ExtendedKeyUsage.");
}
this.usageTable.put(o, o);
}
}
public ExtendedKeyUsage(
Vector usages)
{
ASN1EncodableVector v = new ASN1EncodableVector();
Enumeration e = usages.elements();
while (e.hasMoreElements())
{
DERObject o = (DERObject)e.nextElement();
v.add(o);
this.usageTable.put(o, o);
}
this.seq = new DERSequence(v);
}
public boolean hasKeyPurposeId(
KeyPurposeId keyPurposeId)
{
return (usageTable.get(keyPurposeId) != null);
}
/**
* Returns all extended key usages.
* The returned vector contains DERObjectIdentifiers.
* @return A vector with all key purposes.
*/
public Vector getUsages()
{
Vector temp = new Vector();
for (Enumeration it = usageTable.elements(); it.hasMoreElements();)
{
temp.addElement(it.nextElement());
}
return temp;
}
public int size()
{
return usageTable.size();
}
public DERObject toASN1Object()
{
return seq;
}
}
| mit |
nmuzychuk/sample-apps | prime-number/src/main/java/com/nmuzychuk/PrimeNumber.java | 573 | package com.nmuzychuk;
public final class PrimeNumber {
private PrimeNumber() {
}
public static boolean isPrime(final int number) {
if (number < 2) {
return false;
}
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public static void printPrimes(final int upTo) {
for (int i = 2; i < upTo; i++) {
if (isPrime(i)) {
System.out.printf("%d ", i);
}
}
}
}
| mit |
yw1234/pcap4j | pcap4j-core/src/main/java/org/pcap4j/core/PcapHandle.java | 50953 | /*_##########################################################################
_##
_## Copyright (C) 2011-2015 Pcap4J.org
_##
_##########################################################################
*/
package org.pcap4j.core;
import java.io.EOFException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.pcap4j.core.BpfProgram.BpfCompileMode;
import org.pcap4j.core.NativeMappings.PcapErrbuf;
import org.pcap4j.core.NativeMappings.PcapLibrary;
import org.pcap4j.core.NativeMappings.bpf_program;
import org.pcap4j.core.NativeMappings.pcap_pkthdr;
import org.pcap4j.core.NativeMappings.pcap_stat;
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode;
import org.pcap4j.packet.Packet;
import org.pcap4j.packet.factory.PacketFactories;
import org.pcap4j.packet.namednumber.DataLinkType;
import org.pcap4j.util.ByteArrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
/**
* A wrapper class for struct pcap_t.
*
* @author Kaito Yamada
* @since pcap4j 0.9.1
*/
public final class PcapHandle {
private static final Logger logger = LoggerFactory.getLogger(PcapHandle.class);
private volatile DataLinkType dlt;
private final TimestampPrecision timestampPrecision;
private final Pointer handle;
private final ThreadLocal<Timestamp> timestamps
= new ThreadLocal<Timestamp>();
private final ReentrantReadWriteLock handleLock = new ReentrantReadWriteLock(true);
private static final Object compileLock = new Object();
private volatile boolean open = true;
private volatile String filteringExpression = "";
private static final Inet4Address WILDCARD_MASK;
static {
try {
WILDCARD_MASK = (Inet4Address)InetAddress.getByName("0.0.0.0");
} catch (UnknownHostException e) {
throw new AssertionError("never get here");
}
}
PcapHandle(Pointer handle, TimestampPrecision timestampPrecision) {
this.handle = handle;
this.dlt = getDltByNative();
this.timestampPrecision = timestampPrecision;
}
private PcapHandle(Builder builder) throws PcapNativeException {
PcapErrbuf errbuf = new PcapErrbuf();
this.handle
= NativeMappings.pcap_create(
builder.deviceName,
errbuf
);
if (handle == null || errbuf.length() != 0) {
throw new PcapNativeException(errbuf.toString());
}
try {
if (builder.isSnaplenSet) {
int rc = NativeMappings.pcap_set_snaplen(handle, builder.snaplen);
if (rc != 0) {
throw new PcapNativeException(getError(), rc);
}
}
if (builder.promiscuousMode != null) {
int rc = NativeMappings.pcap_set_promisc(handle, builder.promiscuousMode.getValue());
if (rc != 0) {
throw new PcapNativeException(getError(), rc);
}
}
if (builder.isRfmonSet) {
try {
int rc = PcapLibrary.INSTANCE.pcap_set_rfmon(handle, builder.rfmon ? 1 : 0);
if (rc != 0) {
throw new PcapNativeException(getError(), rc);
}
} catch (UnsatisfiedLinkError e) {
logger.error("Failed to instantiate PcapHandle object.", e);
throw new PcapNativeException("Monitor mode is not supported on this platform.");
}
}
if (builder.isTimeoutMillisSet) {
int rc = NativeMappings.pcap_set_timeout(handle, builder.timeoutMillis);
if (rc != 0) {
throw new PcapNativeException(getError(), rc);
}
}
if (builder.isBufferSizeSet) {
int rc = NativeMappings.pcap_set_buffer_size(handle, builder.bufferSize);
if (rc != 0) {
throw new PcapNativeException(getError(), rc);
}
}
if (builder.timestampPrecision != null) {
try {
int rc = PcapLibrary.INSTANCE.pcap_set_tstamp_precision(
handle,
builder.timestampPrecision.getValue()
);
if (rc == 0) {
this.timestampPrecision = builder.timestampPrecision;
}
else {
StringBuilder sb
= new StringBuilder(100)
.append("The specified timestamp precision ")
.append(builder.timestampPrecision)
.append(" is not supported on this platform. ")
.append(TimestampPrecision.MICRO)
.append(" is set instead.");
logger.error(sb.toString());
this.timestampPrecision = TimestampPrecision.MICRO;
}
} catch (UnsatisfiedLinkError e) {
throw new PcapNativeException(
"pcap_set_tstamp_precision is not supported by the pcap library"
+ " installed in this environment."
);
}
}
else {
this.timestampPrecision = TimestampPrecision.MICRO;
}
int rc = NativeMappings.pcap_activate(handle);
if (rc < 0) {
throw new PcapNativeException(getError(), rc);
}
} catch (NotOpenException e) {
throw new AssertionError("Never get here.");
}
this.dlt = getDltByNative();
}
private DataLinkType getDltByNative() {
return DataLinkType.getInstance(
NativeMappings.pcap_datalink(handle)
);
}
/**
*
* @return the Data Link Type of this PcapHandle
*/
public DataLinkType getDlt() { return dlt; }
/**
* @param dlt a {@link org.pcap4j.packet.namednumber.DataLinkType DataLinkType}
* object to set
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
*/
public void setDlt(DataLinkType dlt) throws PcapNativeException, NotOpenException {
if (dlt == null) {
throw new NullPointerException("dlt must not be null.");
}
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
int rc = NativeMappings.pcap_set_datalink(handle, dlt.value());
if (rc < 0) {
throw new PcapNativeException(getError(), rc);
}
} finally {
handleLock.readLock().unlock();
}
this.dlt = dlt;
}
/**
*
* @return true if this PcapHandle object is open (i.e. not yet closed by {@link #close() close()});
* false otherwise.
*/
public boolean isOpen() { return open; }
/**
*
* @return the filtering expression of this PcapHandle
*/
public String getFilteringExpression() {return filteringExpression; }
/**
* @return Timestamp precision
*/
public TimestampPrecision getTimestampPrecision() {
return timestampPrecision;
}
/**
* @return the timestamp of the last packet captured by this handle in the current thread.
*/
public Timestamp getTimestamp() { return timestamps.get(); }
/**
*
* @return the dimension of the packet portion (in bytes) that is delivered to the application.
* @throws NotOpenException if this PcapHandle is not open.
*/
public int getSnapshot() throws NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
return NativeMappings.pcap_snapshot(handle);
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @return a {@link org.pcap4j.core.PcapHandle.SwappedType SwappedType} object.
* @throws NotOpenException if this PcapHandle is not open.
*/
public SwappedType isSwapped() throws NotOpenException {
if (!open) {
throw new NotOpenException();
}
int rc;
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
rc = NativeMappings.pcap_is_swapped(handle);
} finally {
handleLock.readLock().unlock();
}
switch (rc) {
case 0:
return SwappedType.NOT_SWAPPED;
case 1:
return SwappedType.SWAPPED;
case 2:
return SwappedType.MAYBE_SWAPPED;
default:
logger.warn("pcap_snapshot returned an unexpected code: " + rc);
return SwappedType.MAYBE_SWAPPED;
}
}
/**
*
* @return the major version number of the pcap library used to write the savefile.
* @throws NotOpenException if this PcapHandle is not open.
*/
public int getMajorVersion() throws NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
return NativeMappings.pcap_major_version(handle);
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @return the minor version number of the pcap library used to write the savefile.
* @throws NotOpenException if this PcapHandle is not open.
*/
public int getMinorVersion() throws NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
return NativeMappings.pcap_minor_version(handle);
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @param bpfExpression bpfExpression
* @param mode mode
* @param netmask netmask
* @return a {@link org.pcap4j.core.BpfProgram BpfProgram} object.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
*/
public BpfProgram compileFilter(
String bpfExpression, BpfCompileMode mode, Inet4Address netmask
) throws PcapNativeException, NotOpenException {
if (
bpfExpression == null
|| mode == null
|| netmask == null
) {
StringBuilder sb = new StringBuilder();
sb.append("bpfExpression: ").append(bpfExpression)
.append(" mode: ").append(mode)
.append(" netmask: ").append(netmask);
throw new NullPointerException(sb.toString());
}
if (!open) {
throw new NotOpenException();
}
bpf_program prog;
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
prog = new bpf_program();
int rc;
synchronized (compileLock) {
rc = NativeMappings.pcap_compile(
handle, prog, bpfExpression, mode.getValue(),
ByteArrays.getInt(ByteArrays.toByteArray(netmask), 0)
);
}
if (rc < 0) {
throw new PcapNativeException(getError(), rc);
}
} finally {
handleLock.readLock().unlock();
}
return new BpfProgram(prog, bpfExpression);
}
/**
*
* @param bpfExpression bpfExpression
* @param mode mode
* @param netmask netmask
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
* @throws NullPointerException if any of arguments are null.
*/
public void setFilter(
String bpfExpression, BpfCompileMode mode, Inet4Address netmask
) throws PcapNativeException, NotOpenException {
if (
bpfExpression == null
|| mode == null
|| netmask == null
) {
StringBuilder sb = new StringBuilder();
sb.append("bpfExpression: ").append(bpfExpression)
.append(" mode: ").append(mode)
.append(" netmask: ").append(netmask);
throw new NullPointerException(sb.toString());
}
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
bpf_program prog = new bpf_program();
try {
int mask = ByteArrays.getInt(ByteArrays.toByteArray(netmask), 0);
int rc;
synchronized (compileLock) {
rc = NativeMappings.pcap_compile(
handle, prog, bpfExpression, mode.getValue(), mask
);
}
if (rc < 0) {
throw new PcapNativeException(
"Error occured in pcap_compile: " + getError(),
rc
);
}
rc = NativeMappings.pcap_setfilter(handle, prog);
if (rc < 0) {
throw new PcapNativeException(
"Error occured in pcap_setfilger: " + getError(),
rc
);
}
this.filteringExpression = bpfExpression;
} finally {
NativeMappings.pcap_freecode(prog);
}
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @param bpfExpression bpfExpression
* @param mode mode
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
* @throws NullPointerException if any of arguments are null.
*/
public void setFilter(
String bpfExpression, BpfCompileMode mode
) throws PcapNativeException, NotOpenException {
setFilter(bpfExpression, mode, WILDCARD_MASK);
}
/**
*
* @param prog prog
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
* @throws NullPointerException if any of arguments are null.
*/
public void setFilter(BpfProgram prog) throws PcapNativeException, NotOpenException {
if (prog == null) {
throw new NullPointerException("prog is null.");
}
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
int rc = NativeMappings.pcap_setfilter(handle, prog.getProgram());
if (rc < 0) {
throw new PcapNativeException("Failed to set filter: " + getError(), rc);
}
} finally {
handleLock.readLock().unlock();
}
this.filteringExpression = prog.getExpression();
}
/**
*
* @param mode mode
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
*/
public void setBlockingMode(BlockingMode mode) throws PcapNativeException, NotOpenException {
if (mode == null) {
StringBuilder sb = new StringBuilder();
sb.append(" mode: ").append(mode);
throw new NullPointerException(sb.toString());
}
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
PcapErrbuf errbuf = new PcapErrbuf();
int rc = NativeMappings.pcap_setnonblock(handle, mode.getValue(), errbuf);
if (rc < 0) {
throw new PcapNativeException(errbuf.toString(), rc);
}
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @return blocking mode
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
*/
public BlockingMode getBlockingMode() throws PcapNativeException, NotOpenException {
if (!open) {
throw new NotOpenException();
}
PcapErrbuf errbuf = new PcapErrbuf();
int rc;
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
rc = NativeMappings.pcap_getnonblock(handle, errbuf);
} finally {
handleLock.readLock().unlock();
}
if (rc == 0) {
return BlockingMode.BLOCKING;
}
else if (rc > 0) {
return BlockingMode.NONBLOCKING;
}
else {
throw new PcapNativeException(errbuf.toString(), rc);
}
}
/**
* @return a Packet object created from a captured packet using the packet factory. May be null.
* @throws NotOpenException if this PcapHandle is not open.
*/
public Packet getNextPacket() throws NotOpenException {
byte[] ba = getNextRawPacket();
if (ba == null) {
return null;
}
return PacketFactories.getFactory(Packet.class, DataLinkType.class)
.newInstance(ba, 0, ba.length, dlt);
}
/**
*
* @return a captured packet. May be null.
* @throws NotOpenException if this PcapHandle is not open.
*/
public byte[] getNextRawPacket() throws NotOpenException {
if (!open) {
throw new NotOpenException();
}
pcap_pkthdr header = new pcap_pkthdr();
header.setAutoSynch(false);
Pointer packet;
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
packet = NativeMappings.pcap_next(handle, header);
} finally {
handleLock.readLock().unlock();
}
if (packet != null) {
Pointer headerP = header.getPointer();
timestamps.set(buildTimestamp(headerP));
return packet.getByteArray(0, pcap_pkthdr.getCaplen(headerP));
}
else {
return null;
}
}
/**
* @return a Packet object created from a captured packet using the packet factory. Not null.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws EOFException if packets are being read from a pcap file
* and there are no more packets to read from the file.
* @throws TimeoutException if packets are being read from a live capture
* and the timeout expired.
* @throws NotOpenException if this PcapHandle is not open.
*/
public Packet getNextPacketEx()
throws PcapNativeException, EOFException, TimeoutException, NotOpenException {
byte[] ba = getNextRawPacketEx();
return PacketFactories.getFactory(Packet.class, DataLinkType.class)
.newInstance(ba, 0, ba.length, dlt);
}
/**
*
* @return a captured packet. Not null.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws EOFException if packets are being read from a pcap file
* and there are no more packets to read from the file.
* @throws TimeoutException if packets are being read from a live capture
* and the timeout expired.
* @throws NotOpenException if this PcapHandle is not open.
*/
public byte[] getNextRawPacketEx()
throws PcapNativeException, EOFException, TimeoutException, NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
PointerByReference headerPP = new PointerByReference();
PointerByReference dataPP = new PointerByReference();
int rc = NativeMappings.pcap_next_ex(handle, headerPP, dataPP);
switch (rc) {
case 0:
throw new TimeoutException();
case 1:
Pointer headerP = headerPP.getValue();
Pointer dataP = dataPP.getValue();
if (headerP == null || dataP == null) {
throw new PcapNativeException(
"Failed to get packet. *header: "
+ headerP + " *data: " + dataP
);
}
timestamps.set(buildTimestamp(headerP));
return dataP.getByteArray(0, pcap_pkthdr.getCaplen(headerP));
case -1:
throw new PcapNativeException(
"Error occured in pcap_next_ex(): " + getError(), rc
);
case -2:
throw new EOFException();
default:
throw new PcapNativeException(
"Unexpected error occured: " + getError(), rc
);
}
} finally {
handleLock.readLock().unlock();
}
}
/**
* A wrapper method for <code>int pcap_loop(pcap_t *, int, pcap_handler, u_char *)</code>.
* This method creates a Packet object from a captured packet using the packet factory and
* passes it to <code>listener.gotPacket(Packet)</code>.
* When a packet is captured, <code>listener.gotPacket(Packet)</code> is called in
* the thread which called the <code>loop()</code>. And then this PcapHandle waits for
* the thread to return from the <code>gotPacket()</code> before it retrieves the next
* packet from the pcap buffer.
*
* @param packetCount the number of packets to capture. -1 is equivalent to infinity.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public void loop(
int packetCount, PacketListener listener
) throws PcapNativeException, InterruptedException, NotOpenException {
loop(
packetCount,
listener,
SimpleExecutor.getInstance()
);
}
/**
* A wrapper method for <code>int pcap_loop(pcap_t *, int, pcap_handler, u_char *)</code>.
* This method creates a Packet object from a captured packet using the packet factory and
* passes it to <code>listener.gotPacket(Packet)</code>.
* When a packet is captured, the
* {@link java.util.concurrent.Executor#execute(Runnable) executor.execute()} is called
* with a Runnable object in the thread which called the <code>loop()</code>.
* Then, the Runnable object calls <code>listener.gotPacket(Packet)</code>.
* If <code>listener.gotPacket(Packet)</code> is expected to take a long time to
* process a packet, this method should be used with a proper executor instead of
* {@link #loop(int, PacketListener)} in order to prevent the pcap buffer from overflowing.
*
* @param packetCount the number of packets to capture. -1 is equivalent to infinity.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @param executor executor
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public void loop(
int packetCount, PacketListener listener, Executor executor
) throws PcapNativeException, InterruptedException, NotOpenException {
if (listener == null || executor == null) {
StringBuilder sb = new StringBuilder();
sb.append("listener: ").append(listener)
.append(" executor: ").append(executor);
throw new NullPointerException(sb.toString());
}
doLoop(packetCount, new GotPacketFuncExecutor(listener, dlt, executor));
}
/**
* A wrapper method for <code>int pcap_loop(pcap_t *, int, pcap_handler, u_char *)</code>.
* When a packet is captured, <code>listener.gotPacket(byte[])</code> is called in
* the thread which called the <code>loop()</code>. And then this PcapHandle waits for
* the thread to return from the <code>gotPacket()</code> before it retrieves the next
* packet from the pcap buffer.
*
* @param packetCount the number of packets to capture. -1 is equivalent to infinity.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public void loop(
int packetCount, RawPacketListener listener
) throws PcapNativeException, InterruptedException, NotOpenException {
loop(
packetCount,
listener,
SimpleExecutor.getInstance()
);
}
/**
* A wrapper method for <code>int pcap_loop(pcap_t *, int, pcap_handler, u_char *)</code>.
* When a packet is captured, the
* {@link java.util.concurrent.Executor#execute(Runnable) executor.execute()} is called
* with a Runnable object in the thread which called the <code>loop()</code>.
* Then, the Runnable object calls <code>listener.gotPacket(byte[])</code>.
* If <code>listener.gotPacket(byte[])</code> is expected to take a long time to
* process a packet, this method should be used with a proper executor instead of
* {@link #loop(int, RawPacketListener)} in order to prevent the pcap buffer from overflowing.
*
* @param packetCount the number of packets to capture. -1 is equivalent to infinity.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @param executor executor
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public void loop(
int packetCount, RawPacketListener listener, Executor executor
) throws PcapNativeException, InterruptedException, NotOpenException {
if (listener == null || executor == null) {
StringBuilder sb = new StringBuilder();
sb.append("listener: ").append(listener)
.append(" executor: ").append(executor);
throw new NullPointerException(sb.toString());
}
doLoop(packetCount, new GotRawPacketFuncExecutor(listener, executor));
}
private void doLoop(
int packetCount, NativeMappings.pcap_handler handler
) throws PcapNativeException, InterruptedException, NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
logger.info("Starting loop.");
int rc = NativeMappings.pcap_loop(
handle,
packetCount,
handler,
null
);
switch (rc) {
case 0:
logger.info("Finished loop.");
break;
case -1:
throw new PcapNativeException(
"Error occured: " + getError(), rc
);
case -2:
logger.info("Broken.");
throw new InterruptedException();
default:
throw new PcapNativeException(
"Unexpected error occured: " + getError(), rc
);
}
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @param packetCount the maximum number of packets to process.
* If -1 is specified, all the packets in the pcap buffer or pcap file
* will be processed before returning.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @return the number of captured packets.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public int dispatch(
int packetCount, PacketListener listener
) throws PcapNativeException, InterruptedException, NotOpenException {
return dispatch(
packetCount,
listener,
SimpleExecutor.getInstance()
);
}
/**
*
* @param packetCount the maximum number of packets to process.
* If -1 is specified, all the packets in the pcap buffer or pcap file
* will be processed before returning.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @param executor executor
* @return the number of captured packets.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public int dispatch(
int packetCount, PacketListener listener, Executor executor
) throws PcapNativeException, InterruptedException, NotOpenException {
if (listener == null || executor == null) {
StringBuilder sb = new StringBuilder();
sb.append("listener: ").append(listener)
.append(" executor: ").append(executor);
throw new NullPointerException(sb.toString());
}
return doDispatch(packetCount, new GotPacketFuncExecutor(listener, dlt, executor));
}
/**
*
* @param packetCount the maximum number of packets to process.
* If -1 is specified, all the packets in the pcap buffer or pcap file
* will be processed before returning.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @return the number of captured packets.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public int dispatch(
int packetCount, RawPacketListener listener
) throws PcapNativeException, InterruptedException, NotOpenException {
return dispatch(
packetCount,
listener,
SimpleExecutor.getInstance()
);
}
/**
*
* @param packetCount the maximum number of packets to process.
* If -1 is specified, all the packets in the pcap buffer or pcap file
* will be processed before returning.
* 0 may result in different behaviors between platforms
* and pcap library versions.
* @param listener listener
* @param executor executor
* @return the number of captured packets.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public int dispatch(
int packetCount, RawPacketListener listener, Executor executor
) throws PcapNativeException, InterruptedException, NotOpenException {
if (listener == null || executor == null) {
StringBuilder sb = new StringBuilder();
sb.append("listener: ").append(listener)
.append(" executor: ").append(executor);
throw new NullPointerException(sb.toString());
}
return doDispatch(packetCount, new GotRawPacketFuncExecutor(listener, executor));
}
private int doDispatch(
int packetCount, NativeMappings.pcap_handler handler
) throws PcapNativeException, InterruptedException, NotOpenException {
if (!open) {
throw new NotOpenException();
}
int rc;
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
logger.info("Starting dispatch.");
rc = NativeMappings.pcap_dispatch(
handle,
packetCount,
handler,
null
);
if (rc < 0) {
switch (rc) {
case -1:
throw new PcapNativeException(
"Error occured: " + getError(),
rc
);
case -2:
logger.info("Broken.");
throw new InterruptedException();
default:
throw new PcapNativeException(
"Unexpected error occured: " + getError(),
rc
);
}
}
} finally {
handleLock.readLock().unlock();
}
logger.info("Finish dispatch.");
return rc;
}
/**
*
* @param filePath "-" means stdout.
* The dlt of the PcapHandle which captured the packets you want to dump
* must be the same as this dlt.
* @return an opened PcapDumper.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
*/
public PcapDumper dumpOpen(String filePath) throws PcapNativeException, NotOpenException {
if (filePath == null) {
throw new NullPointerException("filePath must not be null.");
}
if (!open) {
throw new NotOpenException();
}
Pointer dumper;
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
dumper = NativeMappings.pcap_dump_open(handle, filePath);
if (dumper == null) {
throw new PcapNativeException(getError());
}
} finally {
handleLock.readLock().unlock();
}
return new PcapDumper(dumper, timestampPrecision);
}
/**
*
* @param packetCount packetCount
* @param dumper dumper
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws InterruptedException if the loop terminated due to a call to {@link #breakLoop()}.
* @throws NotOpenException if this PcapHandle is not open.
*/
public
void loop(int packetCount, PcapDumper dumper)
throws PcapNativeException, InterruptedException, NotOpenException {
if (dumper == null) {
throw new NullPointerException("dumper must not be null.");
}
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
logger.info("Starting dump loop.");
int rc = NativeMappings.pcap_loop(
handle,
packetCount,
NativeMappings.PCAP_DUMP,
dumper.getDumper()
);
switch (rc) {
case 0:
logger.info("Finished dump loop.");
break;
case -1:
throw new PcapNativeException(
"Error occured: " + getError(), rc
);
case -2:
logger.info("Broken.");
throw new InterruptedException();
default:
throw new PcapNativeException(
"Unexpected error occured: " + getError(), rc
);
}
} finally {
handleLock.readLock().unlock();
}
}
/**
* Breaks a loop which this handle is working on.
*
* The loop may not be broken immediately on some OSes
* because of buffering or something.
* As a workaround, letting this capture some bogus packets
* after calling this method may work.
* @throws NotOpenException if this PcapHandle is not open.
*/
public void breakLoop() throws NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
logger.info("Break loop.");
NativeMappings.pcap_breakloop(handle);
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @param packet packet
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
* @throws NullPointerException if any of arguments are null.
*/
public void sendPacket(Packet packet) throws PcapNativeException, NotOpenException {
if (packet == null) {
throw new NullPointerException("packet may not be null");
}
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
int rc = NativeMappings.pcap_sendpacket(
handle, packet.getRawData(), packet.length()
);
if (rc < 0) {
throw new PcapNativeException(
"Error occured in pcap_sendpacket(): " + getError(),
rc
);
}
} finally {
handleLock.readLock().unlock();
}
}
/**
*
* @return a {@link org.pcap4j.core.PcapStat PcapStat} object.
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
*/
public PcapStat getStats() throws PcapNativeException, NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
if (Platform.isWindows()) {
IntByReference pcapStatSize = new IntByReference();
Pointer psp = PcapLibrary.INSTANCE.win_pcap_stats_ex(handle, pcapStatSize);
if (pcapStatSize.getValue() != 24) {
throw new PcapNativeException(getError());
}
if (psp == null) {
throw new PcapNativeException(getError());
}
return new PcapStat(psp, true);
}
else {
pcap_stat ps = new pcap_stat();
ps.setAutoSynch(false);
int rc = NativeMappings.pcap_stats(handle, ps);
if (rc < 0) {
throw new PcapNativeException(getError(), rc);
}
return new PcapStat(ps.getPointer(), false);
}
} finally {
handleLock.readLock().unlock();
}
}
// /**
// *
// * @return a {@link org.pcap4j.core.PcapStatEx PcapStatEx} object.
// * @throws PcapNativeException if an error occurs in the pcap native library.
// * @throws NotOpenException if this PcapHandle is not open.
// */
// public PcapStatEx getStatsEx() throws PcapNativeException, NotOpenException {
// if (!Platform.isWindows()) {
// throw new UnsupportedOperationException("This method is only for Windows.");
// }
//
// pcap_stat_ex ps = new pcap_stat_ex();
// int rc = PcapLibrary.INSTANCE.dos_pcap_stats_ex(handle, ps);
// if (rc < 0) {
// throw new PcapNativeException(getError(), rc);
// }
//
// return new PcapStatEx(ps);
// }
/**
* @return a list of {@link org.pcap4j.packet.namednumber.DataLinkType DataLinkType}
* @throws PcapNativeException if an error occurs in the pcap native library.
* @throws NotOpenException if this PcapHandle is not open.
*/
public List<DataLinkType> listDatalinks()
throws PcapNativeException, NotOpenException {
if (!open) {
throw new NotOpenException();
}
List<DataLinkType> list;
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
PointerByReference dltBufPP = new PointerByReference();
int rc = NativeMappings.pcap_list_datalinks(handle, dltBufPP);
if (rc < 0) {
throw new PcapNativeException(getError(), rc);
}
Pointer dltBufP = dltBufPP.getValue();
list = new ArrayList<DataLinkType>(rc);
for (int i: dltBufP.getIntArray(0, rc)) {
list.add(DataLinkType.getInstance(i));
}
NativeMappings.pcap_free_datalinks(dltBufP);
} finally {
handleLock.readLock().unlock();
}
return list;
}
/**
*
* @return an error message.
* @throws NotOpenException if this PcapHandle is not open.
*/
public String getError() throws NotOpenException {
if (!open) {
throw new NotOpenException();
}
if (!handleLock.readLock().tryLock()) {
throw new NotOpenException();
}
try {
if (!open) {
throw new NotOpenException();
}
return NativeMappings.pcap_geterr(handle).getString(0);
} finally {
handleLock.readLock().unlock();
}
}
/**
* Closes this PcapHandle.
*/
public void close() {
if (!open) {
logger.warn("Already closed.");
return;
}
handleLock.writeLock().lock();
try {
if (!open) {
logger.warn("Already closed.");
return;
}
open = false;
} finally {
handleLock.writeLock().unlock();
}
NativeMappings.pcap_close(handle);
logger.info("Closed.");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(60);
sb.append("Link type: [").append(dlt)
.append("] handle: [").append(handle)
.append("] Open: [").append(open)
.append("] Filtering Expression: [").append(filteringExpression)
.append("]");
return sb.toString();
}
private static final class SimpleExecutor implements Executor {
private SimpleExecutor() {}
private static final SimpleExecutor INSTANCE = new SimpleExecutor();
public static SimpleExecutor getInstance() { return INSTANCE; }
@Override
public void execute(Runnable command) {
command.run();
}
}
private final class GotPacketFuncExecutor implements NativeMappings.pcap_handler {
private final DataLinkType dlt;
private final PacketListener listener;
private final Executor executor;
public GotPacketFuncExecutor(
PacketListener listener, DataLinkType dlt, Executor executor
) {
this.dlt = dlt;
this.listener = listener;
this.executor = executor;
}
@Override
public void got_packet(
Pointer args, Pointer header, final Pointer packet
) {
final Timestamp ts = buildTimestamp(header);
final byte[] ba = packet.getByteArray(0, pcap_pkthdr.getCaplen(header));
try {
executor.execute(
new Runnable() {
@Override
public void run() {
timestamps.set(ts);
listener.gotPacket(
PacketFactories.getFactory(Packet.class, DataLinkType.class)
.newInstance(ba, 0, ba.length, dlt)
);
}
}
);
} catch (Throwable e) {
logger.error("The executor has thrown an exception.", e);
}
}
}
private final class GotRawPacketFuncExecutor implements NativeMappings.pcap_handler {
private final RawPacketListener listener;
private final Executor executor;
public GotRawPacketFuncExecutor(
RawPacketListener listener, Executor executor
) {
this.listener = listener;
this.executor = executor;
}
@Override
public void got_packet(
Pointer args, Pointer header, final Pointer packet
) {
final Timestamp ts = buildTimestamp(header);
final byte[] ba = packet.getByteArray(0, pcap_pkthdr.getCaplen(header));
try {
executor.execute(
new Runnable() {
@Override
public void run() {
timestamps.set(ts);
listener.gotPacket(ba);
}
}
);
} catch (Throwable e) {
logger.error("The executor has thrown an exception.", e);
}
}
}
private Timestamp buildTimestamp(Pointer header) {
Timestamp ts = new Timestamp(pcap_pkthdr.getTvSec(header).longValue() * 1000L);
switch (timestampPrecision) {
case MICRO:
ts.setNanos(pcap_pkthdr.getTvUsec(header).intValue() * 1000);
break;
case NANO:
ts.setNanos(pcap_pkthdr.getTvUsec(header).intValue());
break;
default:
throw new AssertionError("Never get here.");
}
return ts;
}
/**
* This class is used to open (i.e. create and activate) a live capture handle
* as {@link PcapNetworkInterface#openLive(int, PromiscuousMode, int) PcapNetworkInterface#openLive}
* does but with more parameters.
*
* @author Kaito Yamada
* @since pcap4j 1.2.0
*/
public static final class Builder {
private final String deviceName;
private int snaplen;
private boolean isSnaplenSet = false;
private PromiscuousMode promiscuousMode = null;
private boolean rfmon;
private boolean isRfmonSet = false;
private int timeoutMillis;
private boolean isTimeoutMillisSet = false;
private int bufferSize;
private boolean isBufferSizeSet = false;
private TimestampPrecision timestampPrecision = null;
/**
*
* @param deviceName A value {@link PcapNetworkInterface#getName()} returns.
*/
public Builder(String deviceName) {
if (deviceName == null || deviceName.length() == 0) {
throw new IllegalArgumentException("deviceName: " + deviceName);
}
this.deviceName = deviceName;
}
/**
* @param snaplen Snapshot length, which is the number of bytes captured for each packet.
* If this method isn't called, the platform's default snaplen will be applied
* at {@link #build()}.
* @return this Builder object for method chaining.
*/
public Builder snaplen(int snaplen) {
this.snaplen = snaplen;
this.isSnaplenSet = true;
return this;
}
/**
* @param promiscuousMode Promiscuous mode.
* If this method isn't called,
* the platform's default mode will be used
* at {@link #build()}.
* @return this Builder object for method chaining.
*/
public Builder promiscuousMode(PromiscuousMode promiscuousMode) {
this.promiscuousMode = promiscuousMode;
return this;
}
/**
* @param rfmon Whether monitor mode should be set on a PcapHandle
* when it is built. If true, monitor mode will be set,
* otherwise it will not be set.
* Some platforms don't support setting monitor mode.
* Calling this method on such platforms may cause PcapNativeException
* at {@link #build()}.
* If this method isn't called, the platform's default mode will be applied
* at {@link #build()} (if supported).
* @return this Builder object for method chaining.
*/
public Builder rfmon(boolean rfmon) {
this.rfmon = rfmon;
this.isRfmonSet = true;
return this;
}
/**
* @param timeoutMillis Read timeout. Most OSs buffer packets.
* The OSs pass the packets to Pcap4j after the buffer gets full
* or the read timeout expires.
* Must be non-negative. May be ignored by some OSs.
* 0 means disable buffering on Solaris.
* 0 means infinite on the other OSs.
* 1 through 9 means infinite on Solaris.
* If this method isn't called, the platform's default timeout will be applied
* at {@link #build()}.
* @return this Builder object for method chaining.
*/
public Builder timeoutMillis(int timeoutMillis) {
this.timeoutMillis = timeoutMillis;
this.isTimeoutMillisSet = true;
return this;
}
/**
* @param bufferSize The buffer size, which is in units of bytes.
* If this method isn't called,
* the platform's default buffer size will be applied
* at {@link #build()}.
* @return this Builder object for method chaining.
*/
public Builder bufferSize(int bufferSize) {
this.bufferSize = bufferSize;
this.isBufferSizeSet = true;
return this;
}
/**
* @param timestampPrecision The timestamp precision.
* If this method isn't called,
* microsecond precision will be applied
* at {@link #build()}.
* @return this Builder object for method chaining.
*/
public Builder timestampPrecision(TimestampPrecision timestampPrecision) {
this.timestampPrecision = timestampPrecision;
return this;
}
/**
* @return a new PcapHandle object representing a live capture handle.
* @throws PcapNativeException if an error occurs in the pcap native library.
*/
public PcapHandle build() throws PcapNativeException {
return new PcapHandle(this);
}
}
/**
*
* @author Kaito Yamada
* @version pcap4j 0.9.16
*/
public static enum SwappedType {
/**
*
*/
NOT_SWAPPED(0),
/**
*
*/
SWAPPED(1),
/**
*
*/
MAYBE_SWAPPED(2);
private final int value;
private SwappedType(int value) {
this.value = value;
}
/**
*
* @return value
*/
public int getValue() {
return value;
}
}
/**
*
* @author Kaito Yamada
* @version pcap4j 0.9.15
*/
public static enum BlockingMode {
/**
*
*/
BLOCKING(0),
/**
*
*/
NONBLOCKING(1);
private final int value;
private BlockingMode(int value) {
this.value = value;
}
/**
*
* @return value
*/
public int getValue() {
return value;
}
}
/**
* @author Kaito Yamada
* @version pcap4j 1.5.1
*/
public static enum TimestampPrecision {
/**
* use timestamps with microsecond precision, default
*/
MICRO(0),
/**
* use timestamps with nanosecond precision
*/
NANO(1);
private final int value;
private TimestampPrecision(int value) {
this.value = value;
}
/**
*
* @return value
*/
public int getValue() {
return value;
}
}
}
| mit |
Alex-BusNet/InfiniteStratos | src/main/java/com/sparta/is/core/reference/EnumUnitState.java | 778 | package com.sparta.is.core.reference;
import com.sparta.is.block.IEnumMeta;
public enum EnumUnitState implements IEnumMeta, Comparable<EnumUnitState>
{
DEFAULT,
STANDBY_STATE,
PARTIAL_DEPLOY_STATE,
FULL_DEPLOY_STATE,
SECOND_SHIFT;
private int meta;
protected static final EnumUnitState[] VARIANTS = values();
EnumUnitState() { meta = ordinal(); }
@Override
public int getMeta() { return meta; }
@Override
public String getName()
{
if(this != DEFAULT && this != SECOND_SHIFT)
{
return this.name().split("_S")[0].toLowerCase();
}
return this.name().toLowerCase();
}
public static EnumUnitState byMeta(int meta) { return VARIANTS[Math.abs(meta) & VARIANTS.length]; }
}
| mit |
sunjiesh/wechat | wechat-core/src/main/java/cn/com/sunjiesh/wechat/model/request/message/WechatNormalTextMessageRequest.java | 835 | package cn.com.sunjiesh.wechat.model.request.message;
/**
* 微信接收普通文本消息請求
*
* @author tom
*/
public class WechatNormalTextMessageRequest extends WechatNormalMessageBaseRequest {
/**
*
*/
private static final long serialVersionUID = -7827750283495814733L;
/**
* 文本消息内容
*/
private String content;
public WechatNormalTextMessageRequest() {
}
public WechatNormalTextMessageRequest(String toUserName, String fromUserName, String msgType) {
super(toUserName, fromUserName, msgType);
}
public WechatNormalTextMessageRequest(String toUserName, String fromUserName, String msgType, String msgId) {
super(toUserName, fromUserName, msgType, msgId);
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| mit |
oOXuOo/ACM | CountNumber.java | 1628 | import java.util.Scanner;
/**
* Created by Zahi on 15/5/3.
*
* @描述
* 我们平时数数都是喜欢从左向右数的,但是我们的小白同学最近听说德国人数数和我们有些不同,
* 他们正好和我们相反,是从右向左数的。因此当他看到123时会说“321”。
* 现在有一位德国来的教授在郑州大学进行关于ACM的讲座。现在他聘请你来担任他的助理,
* 他给你一些资料让你找到这些资料在书中的页数。现在你已经找到了对应的页码,要用英文把页码告诉他。
* 为了简化我们的问题,你只需要返回单词的大写的首字母。(数字0读成字母O)
* 注意:每个数字式单独读取的,因此不会出现11读成double one的情况。
* @输入
* 输入分两部分:
* 第一部分:一个整数T(1<=T<=1000)
* 第二部分:一共T行,每行为一个数字。每个数的长度不超过10位。
* @输出
* 每组输出单独占一行,输出对应的返回给德国教授的页码缩写。
*/
public class CountNumber {
static final char[] NUMBER_TABLE = {'O', 'O', 'T', 'T', 'F', 'F', 'S', 'S', 'E', 'N'};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
while (N-- != 0) {
char[] numAry = sc.nextLine().toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numAry.length; i++)
sb.append(NUMBER_TABLE[numAry[numAry.length - i - 1] - '0']);
System.out.println(sb);
}
}
}
| mit |
ali-salman/Aspose_Words_Java | Examples/src/main/java/com/aspose/words/examples/linq/Sender.java | 419 | package com.aspose.words.examples.linq;
public class Sender {
private String Name;
public final String getName()
{
return Name;
}
public final void setName(String value)
{
Name = value;
}
private String Message;
public final String getMessage()
{
return Message;
}
public final void setMessage(String value)
{
Message = value;
}
}
| mit |
mikroskeem/Shuriken | common/src/main/java/eu/mikroskeem/shuriken/common/collections/CollectionUtilities.java | 1516 | package eu.mikroskeem.shuriken.common.collections;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Collection utilities
*
* @author Mark Vainomaa
*/
public final class CollectionUtilities {
/**
* Gets first item from iterator
*
* @param iterator Iterator
* @param <T> Iterable type
* @return First or null
*/
@Nullable
public static <T> T firstOrNull(@NotNull Iterator<T> iterator) {
return iterator.hasNext() ? iterator.next() : null;
}
/**
* Gets first item from iterable, using {@link CollectionUtilities#firstOrNull(Iterator)}
*
* @param iterable Iterable
* @param <T> Iterable type
* @return First or null
*/
@Nullable
public static <T> T firstOrNull(@NotNull Iterable<T> iterable) {
return firstOrNull(iterable.iterator());
}
/**
* Gets first item from list
*
* @param list List
* @param <T> List type
* @return First or null
*/
@Nullable
public static <T> T firstOrNull(@NotNull List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
/**
* Gets first item from set
*
* @param set Set
* @param <T> Set type
* @return First or null
*/
@Nullable
public static <T> T firstOrNull(@NotNull Set<T> set) {
return set.isEmpty() ? null : firstOrNull(set.iterator());
}
}
| mit |
jgaltidor/VarJ | analyzed_libs/jdk1.6.0_06_src/java/awt/HeadlessException.java | 1106 | /*
* @(#)HeadlessException.java 1.9 05/11/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.awt;
/**
* Thrown when code that is dependent on a keyboard, display, or mouse
* is called in an environment that does not support a keyboard, display,
* or mouse.
*
* @since 1.4
* @author Michael Martak
*/
public class HeadlessException extends UnsupportedOperationException {
/*
* JDK 1.4 serialVersionUID
*/
private static final long serialVersionUID = 167183644944358563L;
public HeadlessException() {}
public HeadlessException(String msg) {
super(msg);
}
public String getMessage() {
String superMessage = super.getMessage();
String headlessMessage = GraphicsEnvironment.getHeadlessMessage();
if (superMessage == null) {
return headlessMessage;
} else if (headlessMessage == null) {
return superMessage;
} else {
return superMessage + headlessMessage;
}
}
}
| mit |
Microsoft/vso-httpclient-java | Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/testmanagement/webapi/TestResultSummary.java | 1913 | // @formatter:off
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license. See License.txt in the project root.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*
* See following wiki page for instructions on how to regenerate:
* https://vsowiki.com/index.php?title=Rest_Client_Generation
*/
package com.microsoft.alm.teamfoundation.testmanagement.webapi;
import com.microsoft.alm.teamfoundation.core.webapi.TeamProjectReference;
/**
*/
public class TestResultSummary {
private AggregatedResultsAnalysis aggregatedResultsAnalysis;
private TeamProjectReference teamProject;
private TestFailuresAnalysis testFailures;
private TestResultsContext testResultsContext;
public AggregatedResultsAnalysis getAggregatedResultsAnalysis() {
return aggregatedResultsAnalysis;
}
public void setAggregatedResultsAnalysis(final AggregatedResultsAnalysis aggregatedResultsAnalysis) {
this.aggregatedResultsAnalysis = aggregatedResultsAnalysis;
}
public TeamProjectReference getTeamProject() {
return teamProject;
}
public void setTeamProject(final TeamProjectReference teamProject) {
this.teamProject = teamProject;
}
public TestFailuresAnalysis getTestFailures() {
return testFailures;
}
public void setTestFailures(final TestFailuresAnalysis testFailures) {
this.testFailures = testFailures;
}
public TestResultsContext getTestResultsContext() {
return testResultsContext;
}
public void setTestResultsContext(final TestResultsContext testResultsContext) {
this.testResultsContext = testResultsContext;
}
}
| mit |
sequarius/SequariusToys | MicroBlog/src/main/java/com/sequarius/microblog/entities/Post.java | 1890 | package com.sequarius.microblog.entities;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sequarius on 2015/6/7.
*/
@Entity
@Table(name="post")
public class Post {
@Id
@GenericGenerator(name="generator",strategy="increment")
@GeneratedValue(generator="generator")
private long id;
@Column(length = 140)
@Length(max = 140,message = "{comment.content.length.illegal}")
@NotEmpty(message = "{comment.content.empty.illegal}")
private String content;
@OneToOne
private User user;
@Column(name="post_time")
private long postTime;
@OneToMany(fetch = FetchType.EAGER)
private List<Comment> comments=new ArrayList<Comment>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public long getPostTime() {
return postTime;
}
public void setPostTime(long postTime) {
this.postTime = postTime;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
@Override
public String toString() {
return "Post{" +
"id=" + id +
", content='" + content + '\'' +
", user=" + user +
", postTime=" + postTime +
", comments=" + comments +
'}';
}
}
| mit |
lbehnke/spring-rest-doc | src/main/java/com/apporiented/rest/apidoc/ApiDocConstants.java | 327 | package com.apporiented.rest.apidoc;
/**
* Constants of the API documentation module.
*
* @author Lars Behnke
*/
public final class ApiDocConstants {
public static final String UNDEFINED = "undefined";
public static final String WILDCARD = "wildcard";
public static final String DEPRECATED = "deprecated";
}
| mit |
BIGjuevos/bossy | src/Logger/Logish.java | 262 | package Logger;
/**
* Created by BIGjuevos on 7/24/14.
*
* base class for anything that wants to use the logger facility
*/
public class Logish {
protected Logger logger;
public void setLogger(Logger logger) {
this.logger = logger;
}
}
| mit |
ihepda/di-date-dimension-plugin | src/main/java/it/claudio/dangelo/kettle/plugin/date/DateDimStepDataInterface.java | 886 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package it.claudio.dangelo.kettle.plugin.date;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.BaseStepData;
import org.pentaho.di.trans.step.StepDataInterface;
/**
*
* @author claudio
*/
public class DateDimStepDataInterface extends BaseStepData implements StepDataInterface {
public Database database;
public RowMetaInterface columnsRowMeta;
public String sqlLoad;
public String sqlInsert;
public Map<DateDimensionColumn, String> columnNamesForSQL;
public List<String> sqlLoadColumns;
public List<String> sqlInsertColumns;
public boolean isCanceled;
public Statement pstmtInsert;
public Statement pstmtLoad;
}
| mit |
comboent/project-factory | src/main/java/org/combo/app/service/JspService.java | 385 | package org.combo.app.service;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
@Service
public class JspService {
public ModelAndView hello(String name) {
throw new RuntimeException("yoyoyo");
// ModelAndView mav = new ModelAndView("index");
// mav.addObject("name", name);
// return mav;
}
}
| mit |
Alec-WAM/CrystalMod | src/main/java/alec_wam/CrystalMod/client/model/CustomBakedModel.java | 702 | package alec_wam.CrystalMod.client.model;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
public class CustomBakedModel {
private ModelResourceLocation modelLoc;
private IBakedModel model;
public CustomBakedModel(ModelResourceLocation loc, IBakedModel model){
this.modelLoc = loc;
this.model = model;
}
/**
* @return the modelLoc
*/
public ModelResourceLocation getModelLoc() {
return modelLoc;
}
/**
* @return the model
*/
public IBakedModel getModel() {
return model;
}
public void preModelRegister(){}
public void postModelRegister(){}
}
| mit |
yuandong1234/yuandong-demo | app/src/main/java/yd/miwu/testdemo/AutoLoadXlListViewActivity.java | 9889 | package yd.miwu.testdemo;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.limxing.xlistview.view.XListView;
import java.util.ArrayList;
import yd.miwu.R;
import yd.miwu.base.NetBaseActivity;
import yd.miwu.util.ListViewPageHelper;
public class AutoLoadXlListViewActivity extends NetBaseActivity {
@ViewInject(R.id.xListView)
private XListView xListView;
private ListViewPageHelper helper;
private ArrayList<String> list=new ArrayList<>();
private MyAdapter adapter;
private boolean requestSuccess=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_load_xl_list_view);
ViewUtils.inject(this);
adapter=new MyAdapter(this,list);
helper=new ListViewPageHelper<String>(this,list,xListView){
@Override
protected void onPage(int page) {
super.onPage(page);
loadData(page);
}
};
xListView.setXListViewListener(helper);
xListView.setAdapter(adapter);
}
private void loadData(int page){
Log.e("**********", "page: " + page);
int start = (page - 1) * 10;
int end = page * 10 - 1;
if(start>=images.length){
return;
}
ArrayList<String> urlList = new ArrayList<>();
for (int i = start; i <= end; i++) {
if(i<images.length){
urlList.add(images[i]);
}
}
helper.onFinishPage(urlList, adapter, images.length, requestSuccess);
}
class MyAdapter extends BaseAdapter {
private ArrayList<String> datelist;
private Context context;
private LayoutInflater inflater;
BitmapUtils utils;
public MyAdapter(Context context, ArrayList<String> list) {
this.context = context;
this.datelist = list;
this.inflater = LayoutInflater.from(context);
this.utils = new BitmapUtils(context);
}
@Override
public int getCount() {
return datelist.size();
}
@Override
public Object getItem(int position) {
return datelist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh = null;
if (convertView == null) {
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.item_demo_gridview, null);
vh.pic = (ImageView) convertView.findViewById(R.id.pic);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
utils.display(vh.pic, datelist.get(position));
return convertView;
}
class ViewHolder {
ImageView pic;
}
}
private String[] images = {
"http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383242_9576.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383172_4577.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383166_3407.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383166_2224.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383166_7301.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383165_7197.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383150_8410.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383131_3736.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383130_5094.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383130_7393.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383129_8813.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383100_3554.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383093_7894.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383092_2432.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383092_3071.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383091_3119.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383059_6589.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383059_8814.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383059_2237.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383058_4330.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383038_3602.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382942_3079.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382942_8125.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382942_4881.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382941_4559.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382941_3845.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382924_8955.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382923_2141.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382923_8437.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382922_6166.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382922_4843.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382905_5804.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382904_3362.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382904_2312.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382904_4960.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382900_2418.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382881_4490.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382881_5935.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382880_3865.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382880_4662.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382879_2553.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382862_5375.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382862_1748.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382861_7618.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382861_8606.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382861_8949.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382841_9821.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382840_6603.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382840_2405.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382840_6354.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382839_5779.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382810_7578.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382810_2436.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382809_3883.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382809_6269.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382808_4179.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382790_8326.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382789_7174.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382789_5170.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382789_4118.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382788_9532.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382767_3184.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382767_4772.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382766_4924.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382766_5762.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg"
};
}
| mit |
heisedebaise/ranch | ranch-editor/src/main/java/org/lpw/ranch/editor/screenshot/ScreenshotService.java | 1924 | package org.lpw.ranch.editor.screenshot;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.lpw.ranch.editor.EditorModel;
import org.lpw.ranch.editor.element.ElementModel;
import java.io.File;
import java.util.List;
/**
* @author lpw
*/
public interface ScreenshotService {
/**
* 检索截图集。
*
* @param editor 编辑器ID值。
* @return 截图集;不存在则返回空集。
*/
JSONArray query(String editor);
/**
* 查找截图信息。
*
* @param editor 编辑器ID值。
* @param page 页面。
* @return 截图信息;不存在则返回空JSON。
*/
JSONObject find(String editor, String page);
/**
* 截图。
*
* @param sid Session ID。
* @param editor 编辑器。
* @param elements 根元素集。
* @param nomark 无水印。
* @param save 保存。
* @return 文件集。
*/
List<File> capture(String sid, EditorModel editor, List<ElementModel> elements, boolean nomark, boolean save);
/**
* 截图。
*
* @param sid Session ID。
* @param editor 编辑器。
* @param page 页面。
* @param width 宽。
* @param height 高。
* @return 图片文件;截图失败返回null。
*/
File capture(String sid, String editor, String page, int width, int height);
/**
* 创建。
*
* @param editor 编辑器ID值。
* @param index 序号。
* @param page 页面。
* @param uri 资源URI地址。
*/
void create(String editor, int index, String page, String uri);
/**
* 设置URI。
*
* @param id ID值。
* @param uri URI。
*/
void uri(String id, String uri);
/**
* 删除。
*
* @param editor 编辑器ID值。
*/
void delete(String editor);
}
| mit |
cdai/interview | 1-algorithm/13-leetcode/java/src/buildingblock/sorting/merge/lc313_superuglynumber/Solution.java | 5141 | package buildingblock.sorting.merge.lc313_superuglynumber;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Write a program to find the nth super ugly number.
* Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
* For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.
* Note:
* (1) 1 is a super ugly number for any given primes.
* (2) The given numbers in primes are in ascending order.
* (3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
*/
public class Solution {
// O(NlogK) heap solution.
public int nthSuperUglyNumber(int n, int[] primes) {
Queue<Pair> q = new PriorityQueue<>(Comparator.comparingInt(p -> p.num)); // (p1,p2)->Integer.compare(p1.num,p2.num)
for (int prm : primes)
q.offer(new Pair(prm, prm, 1));
int[] ugly = new int[n + 1];
ugly[1] = 1;
for (int i = 2; i <= n; i++) {
ugly[i] = q.peek().num;
while (q.peek().num == ugly[i]) { // q is not empty
Pair p = q.poll();
p.num = ugly[++p.idx] * p.prm;
q.offer(p);
}
}
return ugly[n];
}
class Pair {
int num, prm, idx;
Pair(int num, int prm, int idx) {
this.num = num;
this.prm = prm;
this.idx = idx;
}
}
// My 2nd: try lambda, but too slow
public int nthSuperUglyNumber2(int n, int[] primes) {
if (n <= 0 || primes.length == 0) {
return 0;
}
int[] ugly = new int[n];
int[] index = new int[primes.length];
int[] candidate = Arrays.copyOf(primes, primes.length);
ugly[0] = 1;
for (int i = 1; i < n; i++) {
// Pick min of K candidates as next ugly number
//int min = Arrays.stream(candidate).min().getAsInt();
int min = Integer.MAX_VALUE;
for (int c : candidate) {
min = Math.min(min, c);
}
ugly[i] = min;
// Only re-compute candidate equals to picked min
for (int j = 0; j < candidate.length; j++) {
if (candidate[j] == min) {
candidate[j] = primes[j] * ugly[++index[j]];
}
}
}
return ugly[n - 1];
}
// My 1st
public int nthSuperUglyNumber1(int n, int[] primes) {
int[] uglyNums = new int[n]; // Optimize-1: replace ArrayList with int[], since length is known
int[] pos = new int[primes.length];
uglyNums[0] = 1;
for (int i = 1; i < n; i++) {
int min = Integer.MAX_VALUE; // Optimize-2: heap is unnecessary
for (int j = 0; j < primes.length; j++) {
min = Math.min(min, primes[j] * uglyNums[pos[j]]);
}
uglyNums[i] = min;
for (int j = 0; j < primes.length; j++) {
if (primes[j] * uglyNums[pos[j]] == min) {
pos[j]++;
}
}
}
return uglyNums[n - 1];
}
public int nthSuperUglyNumber_12(int n, int[] primes) {
int[] uglyNums = new int[n]; // Optimize-1: replace ArrayList with int[], since length is known
int[] pos = new int[primes.length];
int[] candidates = new int[primes.length]; // Optimize-2:
uglyNums[0] = 1;
for (int i = 1; i < n; i++) {
int min = Integer.MAX_VALUE; // Optimize-3: heap is unnecessary
for (int j = 0; j < primes.length; j++) {
if (candidates[j] == 0) {
candidates[j] = primes[j] * uglyNums[pos[j]];
}
min = Math.min(min, candidates[j]);
}
uglyNums[i] = min;
for (int j = 0; j < primes.length; j++) {
if (candidates[j] == min) {
pos[j]++;
candidates[j] = 0;
}
}
}
return uglyNums[n - 1];
}
// heap is not required, we only need min...
public int nthSuperUglyNumber3(int n, int[] primes) {
List<Integer> uglyNums = new ArrayList<>();
Queue<Integer> heap = new PriorityQueue<>();
int[] pos = new int[primes.length];
uglyNums.add(1);
while (uglyNums.size() < n) {
for (int i = 0; i < primes.length; i++) {
heap.offer(primes[i] * uglyNums.get(pos[i]));
}
int min = heap.poll();
uglyNums.add(min);
heap.clear(); // it's hard to reuse heap (remind who changed last round is required)
for (int i = 0; i < primes.length; i++) {
if (primes[i] * uglyNums.get(pos[i]) == min) {
pos[i]++;
}
}
}
return uglyNums.get(n - 1);
}
}
| mit |
zkkz/OrientalExpress | source/openfast/src/org/openfast/extensions/MapFieldParser.java | 993 | package org.openfast.extensions;
import org.openfast.QName;
import org.openfast.template.Field;
import org.openfast.template.loader.FieldParser;
import org.openfast.template.loader.ParsingContext;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class MapFieldParser implements FieldParser {
public boolean canParse(Element element, ParsingContext context) {
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
String nodeName = children.item(i).getNodeName();
if (nodeName.equals("map"))
return true;
}
return false;
}
public Field parse(Element fieldNode, ParsingContext context) {
String key = fieldNode.hasAttribute("key") ? fieldNode.getAttribute("key") : null;
boolean optional = "optional".equals(fieldNode.getAttribute("presence"));
String name = fieldNode.getAttribute("name");
QName qname = new QName(name, context.getNamespace());
return new MapScalar(qname, optional, new QName(key));
}
}
| mit |
AuHau/Home-Myo | app/src/main/java/cz/cvut/uhlirad1/homemyo/knx/TelegramFactory.java | 327 | package cz.cvut.uhlirad1.homemyo.knx;
import cz.cvut.uhlirad1.homemyo.knx.cat.CatTelegram;
/**
* Author: Adam Uhlíř <uhlir.a@gmail.com>
* Date: 20.12.14
*/
public final class TelegramFactory {
private TelegramFactory() {
}
public static ITelegram createTelegram(){
return new CatTelegram();
}
}
| mit |
rafaelmss/WebHipster | src/main/java/br/com/rafael/webhipster/config/audit/AuditEventConverter.java | 3339 | package br.com.rafael.webhipster.config.audit;
import br.com.rafael.webhipster.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
public class AuditEventConverter {
/**
* Convert a list of PersistentAuditEvent to a list of AuditEvent
*
* @param persistentAuditEvents the list to convert
* @return the converted list.
*/
public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
if (persistentAuditEvents == null) {
return Collections.emptyList();
}
List<AuditEvent> auditEvents = new ArrayList<>();
for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
auditEvents.add(convertToAuditEvent(persistentAuditEvent));
}
return auditEvents;
}
/**
* Convert a PersistentAuditEvent to an AuditEvent
*
* @param persistentAuditEvent the event to convert
* @return the converted list.
*/
public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
if (persistentAuditEvent == null) {
return null;
}
return new AuditEvent(Date.from(persistentAuditEvent.getAuditEventDate()), persistentAuditEvent.getPrincipal(),
persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
}
/**
* Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
*
* @param data the data to convert
* @return a map of String, Object
*/
public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
results.put(entry.getKey(), entry.getValue());
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string
*
* @param data the data to convert
* @return a map of String, String
*/
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
Object object = entry.getValue();
// Extract the data that will be saved.
if (object instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else if (object != null) {
results.put(entry.getKey(), object.toString());
} else {
results.put(entry.getKey(), "null");
}
}
}
return results;
}
}
| mit |
mikelynch/iphone2email | iphone2email/src/main/java/iphone2email/ContactReader.java | 2451 | package iphone2email;
import java.util.HashMap;
import java.util.Map;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import iphone2email.model.Contact;
import iphone2email.model.Handle;
public class ContactReader {
public Map<String, Contact> getContacts(String databasePath) {
Connection c = null;
HashMap<Integer, Contact> contactsById = new HashMap<Integer, Contact>();
HashMap<String, Contact> contacts = new HashMap<String, Contact>();
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not load SQLite JDBC types. " + e.getMessage());
}
try {
c = DriverManager.getConnection("jdbc:sqlite:" +
databasePath);
c.setAutoCommit(false);
Statement s = c.createStatement();
ResultSet results = s.executeQuery("SELECT p.ROWID AS contactId, v.value, v.property, p.First, p.Last FROM ABPerson p INNER JOIN ABMultiValue v ON p.ROWID = v.record_id WHERE v.property IN (3, 4);");
while (results.next()) {
Integer contactId = results.getInt("contactId");
String firstName = results.getString("First");
String lastName = results.getString("Last");
String handle = results.getString("value");
Integer type = results.getInt("property");
if (handle == null) {
System.err.println("handle is null");
System.err.println(firstName + " " + lastName);
}
// Generate display name.
String displayName = "";
if (firstName != null) {
displayName = firstName;
}
if (lastName != null) {
if (displayName != "") {
displayName = displayName + " " + lastName;
} else {
displayName = lastName;
}
}
if (displayName.isEmpty()) {
displayName = handle;
}
// Try finding this contact ID from already processed ones.
Contact contact = contactsById.get(contactId);
if (contact == null) {
// If contact ID doesn't already exist, create a new one, and add it to the map.
contact = new Contact(contactId, displayName);
contactsById.put(contactId, contact);
}
Handle h = new Handle(handle);
// Either way, add the handle to the contact.
contact.addHandle(h);
contacts.put(h.getHandle(), contact);
}
} catch (SQLException e) {
throw new RuntimeException("SQL error: " + e.getMessage());
}
return contacts;
}
}
| mit |
project-recoin/googlenews | src/main/java/test/Main.java | 6667 | package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static String endPoint = "https://ajax.googleapis.com/ajax/services/search/news?";
public static final String[] TOPICS = { "h", "w", "b", "n", "t", "el", "p",
"e", "s", "m" };
public static final String[] TOPICSDes = { "headlines", "world",
"business", "nation", "technology", "elections", "politics",
"entertainment", "sports", "health" };
public static final String[] NED = { "uk", "au", "in", "en_il", "en_my",
"nz", "en_pk", "en_ph", "en_sg", "ar_me", "ar_ae", "ar_lb",
"ar_sa", "cn", "hk", "hi_in", "ta_in", "ml_in", "te_in", "iw_il",
"jp", "kr", "tw", "vi_vn", "nl_be", "fr_be", "en_bw", "cs_cz",
"de", "es", "en_et", "fr", "en_gh", "en_ie", "it", "en_ke",
"hu_hu", "fr_ma", "en_na", "nl_nl", "en_ng", "no_no", "de_at",
"pl_pl", "pt-PT_pt", "de_ch", "fr_sn", "en_za", "fr_ch", "sv_se",
"en_tz", "tr_tr", "en_ug", "en_zw", "ar_eg", "el_gr", "ru_ru",
"sr_rs", "ru_ua", "uk_ua", "es_ar", "pt-BR_br", "ca", "fr_ca",
"es_cl", "es_co", "es_cu", "es_us", "es_mx", "es_pe", "us", "es_ve" };
public static final String version = "1.0";
public static String userip;
public static final int maxWait = 50; // In seconds
public static final int minWait = 20; // In seconds
public static final int wholeProcessIsRepeated = 12; // In hours
public static final int ResultLimit = 8;
public static final int rsz = 8;
public static final int Start = 8;
public static final String dirName = "googleNews";
public static int GlobalErrorCounter = 0;
public static void usage() {
System.out
.println("The program accepts only one arg which is the IP address");
System.out.println("java IP address");
}
public static void main(String[] args) {
if (args.length != 1) {
usage();
System.exit(-1);
}
userip = args[0];
StringBuilder urlWithIntialParams = new StringBuilder();
urlWithIntialParams.append(endPoint);
urlWithIntialParams.append("v=" + version);
urlWithIntialParams.append("&userip=" + userip);
urlWithIntialParams.append("&rsz=" + rsz);
try {
// Repeat every some hours!! See end of this block
while (true) {
// upper level counter for waiting a bit more time
GlobalErrorCounter = 0;
Date date = new Date();
// dir is printed with the time and date of creation
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd_HH-mm-ss");
String DirFullName = dirName + dateFormat.format(date);
File file = new File(DirFullName);
file.mkdirs();
// looping through countries and versions
for (int l = 0; l < NED.length; l++) {
String urlWithCountryParam = urlWithIntialParams + "&ned="
+ NED[l];
// looping through the 10 topics
for (int i = 0; i < TOPICS.length; i++) {
String urlWithTopicParam = urlWithCountryParam
+ "&topic=" + TOPICS[i];
// loop throguh the 8 pages
for (int j = 0; j < Start * ResultLimit; j += ResultLimit) {
String urlWithPageParam = urlWithTopicParam
+ "&start=" + j;
// inner counter level
int counterToExitLoop = 0;
// doing the same request over until it passed or
// countenue failong
// and therefore exiting the app
while (true) {
if (counterToExitLoop > 5) {
System.out
.println("403 error is being encountered 5 times");
if (GlobalErrorCounter < 5) {
GlobalErrorCounter++;
Thread.sleep(3600000);
// System.out.println("chainging the topic!");
// break topicLoop;
} else {
System.out
.println("Keep getting the error!");
System.out
.println("Exiting the crawler");
System.exit(1);
}
}
// time between reqests is randomised between
// max and min time
Random rn = new Random();
int randomWait = rn
.nextInt((maxWait - minWait) + 1)
+ minWait;
Thread.sleep(randomWait + 1000);
JSONObject json = runJson(urlWithPageParam);
if (json == null) {
continue;
}
int responseStatus = json
.getInt("responseStatus");
if (responseStatus == 200) {
// Reset the global error to 0 which means
// the
// crawler is back to work normally!
GlobalErrorCounter = 0;
System.out.println("Processed " + NED[l]
+ "_" + TOPICSDes[i] + "_"
+ ((j / 8) + 1) + "_" + ".json");
PrintWriter writer = new PrintWriter(
DirFullName + "/" + NED[l] + "_"
+ TOPICSDes[i] + "_"
+ ((j / 8) + 1) + "_"
+ ".json", "UTF-8");
writer.println(json.toString());
writer.close();
break;
// if Suspected Terms of Service Abuse
} else if (responseStatus == 403) {
System.out
.println("403 error is encountered with "
+ NED[l]
+ "_"
+ TOPICSDes[i]
+ "_"
+ ((j / 8) + 1));
counterToExitLoop++;
Thread.sleep(300000);
}
}
}
}
}
System.out.println("Sleeping for " + wholeProcessIsRepeated
+ " Hours");
System.out.println("Leave me alone (*!*)");
Thread.sleep(wholeProcessIsRepeated * 60 * 60 * 1000);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static JSONObject runJson(String stringurl) {
JSONObject json = null;
try {
URL url = new URL(stringurl);
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
json = new JSONObject(builder.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
| mit |
iontorrent/Torrent-Variant-Caller-stable | public/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/DiploidGenotype.java | 4495 | /*
* Copyright (c) 2010 The Broad Institute
*
* 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.broadinstitute.sting.gatk.walkers.genotyper;
import org.broadinstitute.sting.utils.BaseUtils;
public enum DiploidGenotype {
AA ('A', 'A'),
AC ('A', 'C'),
AG ('A', 'G'),
AT ('A', 'T'),
CC ('C', 'C'),
CG ('C', 'G'),
CT ('C', 'T'),
GG ('G', 'G'),
GT ('G', 'T'),
TT ('T', 'T');
public byte base1, base2;
@Deprecated
private DiploidGenotype(char base1, char base2) {
this((byte)base1, (byte)base2);
}
private DiploidGenotype(byte base1, byte base2) {
this.base1 = base1;
this.base2 = base2;
}
public boolean isHomRef(byte r) {
return isHom() && r == base1;
}
public boolean isHomVar(byte r) {
return isHom() && r != base1;
}
public boolean isHetRef(byte r) {
if ( base1 == r )
return r != base2;
else
return base2 == r;
}
public boolean isHom() {
return ! isHet();
}
public boolean isHet() {
return base1 != base2;
}
/**
* create a diploid genotype, given a character to make into a hom genotype
* @param hom the character to turn into a hom genotype, i.e. if it is A, then returned will be AA
* @return the diploid genotype
*/
public static DiploidGenotype createHomGenotype(byte hom) {
int index = BaseUtils.simpleBaseToBaseIndex(hom);
if ( index == -1 )
throw new IllegalArgumentException(hom + " is not a valid base character");
return conversionMatrix[index][index];
}
/**
* create a diploid genotype, given 2 chars which may not necessarily be ordered correctly
* @param base1 base1
* @param base2 base2
* @return the diploid genotype
*/
public static DiploidGenotype createDiploidGenotype(byte base1, byte base2) {
int index1 = BaseUtils.simpleBaseToBaseIndex(base1);
if ( index1 == -1 )
throw new IllegalArgumentException(base1 + " is not a valid base character");
int index2 = BaseUtils.simpleBaseToBaseIndex(base2);
if ( index2 == -1 )
throw new IllegalArgumentException(base2 + " is not a valid base character");
return conversionMatrix[index1][index2];
}
/**
* create a diploid genotype, given 2 base indexes which may not necessarily be ordered correctly
* @param baseIndex1 base1
* @param baseIndex2 base2
* @return the diploid genotype
*/
public static DiploidGenotype createDiploidGenotype(int baseIndex1, int baseIndex2) {
if ( baseIndex1 == -1 )
throw new IllegalArgumentException(baseIndex1 + " does not represent a valid base character");
if ( baseIndex2 == -1 )
throw new IllegalArgumentException(baseIndex2 + " does not represent a valid base character");
return conversionMatrix[baseIndex1][baseIndex2];
}
private static final DiploidGenotype[][] conversionMatrix = {
{ DiploidGenotype.AA, DiploidGenotype.AC, DiploidGenotype.AG, DiploidGenotype.AT },
{ DiploidGenotype.AC, DiploidGenotype.CC, DiploidGenotype.CG, DiploidGenotype.CT },
{ DiploidGenotype.AG, DiploidGenotype.CG, DiploidGenotype.GG, DiploidGenotype.GT },
{ DiploidGenotype.AT, DiploidGenotype.CT, DiploidGenotype.GT, DiploidGenotype.TT }
};
} | mit |
selvasingh/azure-sdk-for-java | sdk/cosmos/mgmt-v2019_12_12/src/main/java/com/microsoft/azure/management/cosmosdb/v2019_12_12/implementation/GremlinDatabaseGetResultsImpl.java | 5977 | /**
* 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.cosmosdb.v2019_12_12.implementation;
import com.microsoft.azure.management.cosmosdb.v2019_12_12.GremlinDatabaseGetResults;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import com.microsoft.azure.management.cosmosdb.v2019_12_12.GremlinDatabaseCreateUpdateParameters;
import com.microsoft.azure.management.cosmosdb.v2019_12_12.GremlinDatabaseGetPropertiesResource;
import java.util.Map;
import com.microsoft.azure.management.cosmosdb.v2019_12_12.CreateUpdateOptions;
import com.microsoft.azure.management.cosmosdb.v2019_12_12.GremlinDatabaseResource;
import rx.functions.Func1;
class GremlinDatabaseGetResultsImpl extends CreatableUpdatableImpl<GremlinDatabaseGetResults, GremlinDatabaseGetResultsInner, GremlinDatabaseGetResultsImpl> implements GremlinDatabaseGetResults, GremlinDatabaseGetResults.Definition, GremlinDatabaseGetResults.Update {
private final CosmosDBManager manager;
private String resourceGroupName;
private String accountName;
private String databaseName;
private GremlinDatabaseCreateUpdateParameters createOrUpdateParameter;
GremlinDatabaseGetResultsImpl(String name, CosmosDBManager manager) {
super(name, new GremlinDatabaseGetResultsInner());
this.manager = manager;
// Set resource name
this.databaseName = name;
//
this.createOrUpdateParameter = new GremlinDatabaseCreateUpdateParameters();
}
GremlinDatabaseGetResultsImpl(GremlinDatabaseGetResultsInner inner, CosmosDBManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.databaseName = inner.name();
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.accountName = IdParsingUtils.getValueFromIdByName(inner.id(), "databaseAccounts");
this.databaseName = IdParsingUtils.getValueFromIdByName(inner.id(), "gremlinDatabases");
//
this.createOrUpdateParameter = new GremlinDatabaseCreateUpdateParameters();
}
@Override
public CosmosDBManager manager() {
return this.manager;
}
@Override
public Observable<GremlinDatabaseGetResults> createResourceAsync() {
GremlinResourcesInner client = this.manager().inner().gremlinResources();
return client.createUpdateGremlinDatabaseAsync(this.resourceGroupName, this.accountName, this.databaseName, this.createOrUpdateParameter)
.map(new Func1<GremlinDatabaseGetResultsInner, GremlinDatabaseGetResultsInner>() {
@Override
public GremlinDatabaseGetResultsInner call(GremlinDatabaseGetResultsInner resource) {
resetCreateUpdateParameters();
return resource;
}
})
.map(innerToFluentMap(this));
}
@Override
public Observable<GremlinDatabaseGetResults> updateResourceAsync() {
GremlinResourcesInner client = this.manager().inner().gremlinResources();
return client.createUpdateGremlinDatabaseAsync(this.resourceGroupName, this.accountName, this.databaseName, this.createOrUpdateParameter)
.map(new Func1<GremlinDatabaseGetResultsInner, GremlinDatabaseGetResultsInner>() {
@Override
public GremlinDatabaseGetResultsInner call(GremlinDatabaseGetResultsInner resource) {
resetCreateUpdateParameters();
return resource;
}
})
.map(innerToFluentMap(this));
}
@Override
protected Observable<GremlinDatabaseGetResultsInner> getInnerAsync() {
GremlinResourcesInner client = this.manager().inner().gremlinResources();
return client.getGremlinDatabaseAsync(this.resourceGroupName, this.accountName, this.databaseName);
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
private void resetCreateUpdateParameters() {
this.createOrUpdateParameter = new GremlinDatabaseCreateUpdateParameters();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String location() {
return this.inner().location();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public GremlinDatabaseGetPropertiesResource resource() {
return this.inner().resource();
}
@Override
public Map<String, String> tags() {
return this.inner().getTags();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public GremlinDatabaseGetResultsImpl withExistingDatabaseAccount(String resourceGroupName, String accountName) {
this.resourceGroupName = resourceGroupName;
this.accountName = accountName;
return this;
}
@Override
public GremlinDatabaseGetResultsImpl withLocation(String location) {
this.createOrUpdateParameter.withLocation(location);
return this;
}
@Override
public GremlinDatabaseGetResultsImpl withOptions(CreateUpdateOptions options) {
this.createOrUpdateParameter.withOptions(options);
return this;
}
@Override
public GremlinDatabaseGetResultsImpl withResource(GremlinDatabaseResource resource) {
this.createOrUpdateParameter.withResource(resource);
return this;
}
@Override
public GremlinDatabaseGetResultsImpl withTags(Map<String, String> tags) {
this.createOrUpdateParameter.withTags(tags);
return this;
}
}
| mit |
jamesdbaker/Advent-of-Code-2015 | parent/day6/src/main/java/jamesbaker/adventofcode/day6/Part2.java | 2119 | package jamesbaker.adventofcode.day6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Part2 {
public static void main(String[] args) throws IOException {
int[][] grid = new int[1000][1000];
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(Part2.class.getResourceAsStream("input.txt")))) {
String line;
while((line = buffer.readLine()) != null){
if(line.startsWith("turn on ")){
int[] corners = parseRect(line.substring(8));
increaseGrid(grid, 1, corners[0], corners[1], corners[2], corners[3]);
}else if(line.startsWith("turn off ")){
int[] corners = parseRect(line.substring(9));
decreaseGrid(grid, 1, corners[0], corners[1], corners[2], corners[3]);
}else if(line.startsWith("toggle ")){
int[] corners = parseRect(line.substring(7));
increaseGrid(grid, 2, corners[0], corners[1], corners[2], corners[3]);
}else{
System.err.println("Unexpected input: "+line);
}
}
}
System.out.println(countLights(grid));
}
private static int[] parseRect(String s){
int[] ret = new int[4]; //x1, y1, x2, y2
String[] corners = s.split(" through ");
String[] one = corners[0].split(",");
String[] two = corners[1].split(",");
ret[0] = Integer.valueOf(one[0]);
ret[1] = Integer.valueOf(one[1]);
ret[2] = Integer.valueOf(two[0]);
ret[3] = Integer.valueOf(two[1]);
return ret;
}
private static int countLights(int[][] grid){
int count = 0;
for (int x = 0; x < grid.length; x++){
for (int y = 0; y < grid[x].length; y++){
count += grid[x][y];
}
}
return count;
}
private static void increaseGrid(int[][] grid, int amount, int x1, int y1, int x2, int y2){
for (int x = x1; x <= x2; x++){
for (int y = y1; y <= y2; y++){
grid[x][y] += amount;
}
}
}
private static void decreaseGrid(int[][] grid, int amount, int x1, int y1, int x2, int y2){
for (int x = x1; x <= x2; x++){
for (int y = y1; y <= y2; y++){
grid[x][y] -= amount;
if(grid[x][y] < 0){
grid[x][y] = 0;
}
}
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/cognitiveservices/mgmt-v2017_04_18/src/main/java/com/microsoft/azure/management/cognitiveservices/v2017_04_18/implementation/OperationsImpl.java | 1676 | /**
* 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.
* abc
*/
package com.microsoft.azure.management.cognitiveservices.v2017_04_18.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.cognitiveservices.v2017_04_18.Operations;
import rx.functions.Func1;
import rx.Observable;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.cognitiveservices.v2017_04_18.OperationEntity;
class OperationsImpl extends WrapperImpl<OperationsInner> implements Operations {
private final CognitiveServicesManager manager;
OperationsImpl(CognitiveServicesManager manager) {
super(manager.inner().operations());
this.manager = manager;
}
public CognitiveServicesManager manager() {
return this.manager;
}
@Override
public Observable<OperationEntity> listAsync() {
OperationsInner client = this.inner();
return client.listAsync()
.flatMapIterable(new Func1<Page<OperationEntityInner>, Iterable<OperationEntityInner>>() {
@Override
public Iterable<OperationEntityInner> call(Page<OperationEntityInner> page) {
return page.items();
}
})
.map(new Func1<OperationEntityInner, OperationEntity>() {
@Override
public OperationEntity call(OperationEntityInner inner) {
return new OperationEntityImpl(inner, manager());
}
});
}
}
| mit |
gmarciani/gmparser | test/com/gmarciani/gmparser/automaton/base/TestState.java | 2200 | /* The MIT License (MIT)
*
* Copyright (c) 2014 Giacomo Marciani
*
* 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.gmarciani.gmparser.automaton.base;
import static org.junit.Assert.*;
import org.junit.Test;
import com.gmarciani.gmparser.models.automaton.state.State;
import com.gmarciani.gmparser.models.commons.set.GSet;
public class TestState {
@Test public void equal() {
State<Object> stateOne = new State<Object>(1);
State<Object> stateTwo = new State<Object>(2);
assertEquals("Uncorrect state equality. Should be equals: " + stateOne + " and " + stateOne,
stateOne, stateOne);
assertNotEquals("Uncorrect state equality. Should not be equals: " + stateOne + " and " + stateTwo,
stateOne, stateTwo);
}
@Test public void represent() {
State<String> stateOne = new State<String>(1, "one");
State<String> stateTwo = new State<String>(2, "two");
GSet<State<String>> states = new GSet<State<String>>();
states.add(stateOne);
states.add(stateTwo);
for (State<String> state : states)
System.out.println(state);
for (State<String> state : states)
System.out.println(state.toExtendedString());
}
}
| mit |
maxkolotilin/Task-Manager | app/src/main/java/com/maximka/taskmanager/ui/screens/details/TaskDetailsFragment.java | 5991 | package com.maximka.taskmanager.ui.screens.details;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import com.maximka.taskmanager.R;
import com.maximka.taskmanager.data.Percent;
import com.maximka.taskmanager.formatters.ProgressPercentFormatter;
import com.maximka.taskmanager.formatters.TaskStateFormatter;
import com.maximka.taskmanager.formatters.TimeIntervalFormatter;
import com.maximka.taskmanager.ui.base.BaseFragment;
import com.maximka.taskmanager.ui.data.TaskViewData;
import com.maximka.taskmanager.ui.navigation.Navigator;
import com.maximka.taskmanager.utils.Assertion;
public final class TaskDetailsFragment extends BaseFragment<TaskDetailsPresenter> implements TaskDetailsView {
private static final String TASK_ID_ARG = "taskId";
private TextView mTitleTextView;
private TextView mDescriptionTextView;
private TextView mStartDateTextView;
private TextView mDueDateTextView;
private TextView mEstimatedTimeTextView;
private TextView mStateTextView;
private TextView mProgressTextView;
private SeekBar mProgressSeekBar;
public static TaskDetailsFragment newInstance(@NonNull final String taskId) {
Assertion.nonNull(taskId);
final Bundle arguments = new Bundle();
arguments.putString(TASK_ID_ARG, taskId);
final TaskDetailsFragment fragment = new TaskDetailsFragment();
fragment.setArguments(arguments);
return fragment;
}
@Override
protected int getLayoutResId() {
return R.layout.task_details_fragment;
}
@Override
protected int getFloatingButtonIcon() {
return R.drawable.ic_fab_edit;
}
@Override
protected View.OnClickListener getOnFloatingButtonClickListener() {
return v -> getPresenter().onEditButtonClicked();
}
@Override
protected boolean showToolbarBackArrow() {
return true;
}
@NonNull
@Override
protected TaskDetailsPresenter createPresenter() {
return new TaskDetailsPresenter(this,
new Navigator(getFragmentManager()),
getStringArgument(TASK_ID_ARG).orElseThrow(IllegalArgumentException::new));
}
@NonNull
@Override
public View onCreateView(@NonNull final LayoutInflater inflater,
@Nullable final ViewGroup container,
@Nullable final Bundle savedInstanceState) {
final View rootView = super.onCreateView(inflater, container, savedInstanceState);
mTitleTextView = (TextView) rootView.findViewById(R.id.title);
mDescriptionTextView = (TextView) rootView.findViewById(R.id.description);
mStartDateTextView = (TextView) rootView.findViewById(R.id.start_date);
mDueDateTextView = (TextView) rootView.findViewById(R.id.due_date);
mEstimatedTimeTextView = (TextView) rootView.findViewById(R.id.estimated_time);
mStateTextView = (TextView) rootView.findViewById(R.id.state);
mProgressTextView = (TextView) rootView.findViewById(R.id.progress);
mProgressSeekBar = (SeekBar) rootView.findViewById(R.id.progress_bar);
Assertion.nonNull(mTitleTextView,
mDescriptionTextView,
mStartDateTextView,
mDueDateTextView,
mEstimatedTimeTextView,
mStateTextView,
mProgressSeekBar,
mProgressTextView);
return rootView;
}
@Override
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mProgressSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(@NonNull final SeekBar seekBar, final int progress, final boolean fromUser) {
mProgressTextView.setText(getString(R.string.task_progress_format_string, progress));
}
@Override
public void onStartTrackingTouch(@NonNull final SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(@NonNull final SeekBar seekBar) {
getPresenter().updateTaskProgress(new Percent(seekBar.getProgress()));
}
});
}
@Override
public void showErrorMessage() {
showToast(R.string.detail_task_load_error);
}
@Override
public void updateTaskDataViews(@NonNull final TaskViewData taskData) {
Assertion.nonNull(taskData);
final Context context = getActivity();
final Percent progress = taskData.getProgress();
mTitleTextView.setText(taskData.getTitle());
mDescriptionTextView.setText(taskData.getDescription());
mStartDateTextView.setText(getString(R.string.details_start_date_format_string,
taskData.getFormattedStartDate()));
mDueDateTextView.setText(getString(R.string.details_due_date_format_string,
taskData.getFormattedDueDate()));
mEstimatedTimeTextView.setText(getString(R.string.details_estimated_time_format_string,
TimeIntervalFormatter.format(taskData.getEstimatedTime(),
context)));
mStateTextView.setText(TaskStateFormatter.format(taskData.getState(), context));
mProgressTextView.setText(ProgressPercentFormatter.format(progress, context));
mProgressSeekBar.setProgress(progress.asInt());
}
}
| mit |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/resources/commerce/shipping/admin/profiles/ProductHandlingFeeRulesResource.java | 22853 | /**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.resources.commerce.shipping.admin.profiles;
import com.mozu.api.ApiContext;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;
import com.mozu.api.DataViewMode;
/** <summary>
* Use the ProductHandlingFeeRules sub-resource to manage your product handling fee rules that are associated with a specific shipping profile.
* </summary>
*/
public class ProductHandlingFeeRulesResource {
///
/// <see cref="Mozu.Api.ApiContext"/>
///
private ApiContext _apiContext;
private DataViewMode _dataViewMode;
public ProductHandlingFeeRulesResource(ApiContext apiContext)
{
_apiContext = apiContext;
_dataViewMode = DataViewMode.Live;
}
public ProductHandlingFeeRulesResource(ApiContext apiContext, DataViewMode dataViewMode)
{
_apiContext = apiContext;
_dataViewMode = dataViewMode;
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRule handlingFeeRule = producthandlingfeerules.getProductHandlingFeeRule( profilecode, id);
* </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule getProductHandlingFeeRule(String profilecode, String id) throws Exception
{
return getProductHandlingFeeRule( profilecode, id, null);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.getProductHandlingFeeRule( profilecode, id, callback );
* latch.await() * </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public CountDownLatch getProductHandlingFeeRuleAsync(String profilecode, String id, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> callback) throws Exception
{
return getProductHandlingFeeRuleAsync( profilecode, id, null, callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRule handlingFeeRule = producthandlingfeerules.getProductHandlingFeeRule( profilecode, id, responseFields);
* </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule getProductHandlingFeeRule(String profilecode, String id, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.getProductHandlingFeeRuleClient(_dataViewMode, profilecode, id, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.getProductHandlingFeeRule( profilecode, id, responseFields, callback );
* latch.await() * </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public CountDownLatch getProductHandlingFeeRuleAsync(String profilecode, String id, String responseFields, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> callback) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.getProductHandlingFeeRuleClient(_dataViewMode, profilecode, id, responseFields);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRuleCollection handlingFeeRuleCollection = producthandlingfeerules.getProductHandlingFeeRules( profilecode);
* </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection getProductHandlingFeeRules(String profilecode) throws Exception
{
return getProductHandlingFeeRules( profilecode, null);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.getProductHandlingFeeRules( profilecode, callback );
* latch.await() * </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
*/
public CountDownLatch getProductHandlingFeeRulesAsync(String profilecode, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection> callback) throws Exception
{
return getProductHandlingFeeRulesAsync( profilecode, null, callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRuleCollection handlingFeeRuleCollection = producthandlingfeerules.getProductHandlingFeeRules( profilecode, responseFields);
* </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection getProductHandlingFeeRules(String profilecode, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.getProductHandlingFeeRulesClient(_dataViewMode, profilecode, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.getProductHandlingFeeRules( profilecode, responseFields, callback );
* latch.await() * </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection
*/
public CountDownLatch getProductHandlingFeeRulesAsync(String profilecode, String responseFields, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection> callback) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRuleCollection> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.getProductHandlingFeeRulesClient(_dataViewMode, profilecode, responseFields);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRule handlingFeeRule = producthandlingfeerules.createProductHandlingFeeRule( rule, profilecode);
* </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param dataViewMode DataViewMode
* @param rule The details of the new product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule createProductHandlingFeeRule(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode) throws Exception
{
return createProductHandlingFeeRule( rule, profilecode, null);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.createProductHandlingFeeRule( rule, profilecode, callback );
* latch.await() * </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param rule The details of the new product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public CountDownLatch createProductHandlingFeeRuleAsync(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> callback) throws Exception
{
return createProductHandlingFeeRuleAsync( rule, profilecode, null, callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRule handlingFeeRule = producthandlingfeerules.createProductHandlingFeeRule( rule, profilecode, responseFields);
* </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param dataViewMode DataViewMode
* @param rule The details of the new product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule createProductHandlingFeeRule(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.createProductHandlingFeeRuleClient( rule, profilecode, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.createProductHandlingFeeRule( rule, profilecode, responseFields, callback );
* latch.await() * </code></pre></p>
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param rule The details of the new product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public CountDownLatch createProductHandlingFeeRuleAsync(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode, String responseFields, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> callback) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.createProductHandlingFeeRuleClient( rule, profilecode, responseFields);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRule handlingFeeRule = producthandlingfeerules.updateProductHandlingFeeRule( rule, profilecode, id);
* </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param dataViewMode DataViewMode
* @param rule The updated details of the product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule updateProductHandlingFeeRule(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode, String id) throws Exception
{
return updateProductHandlingFeeRule( rule, profilecode, id, null);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.updateProductHandlingFeeRule( rule, profilecode, id, callback );
* latch.await() * </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param rule The updated details of the product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public CountDownLatch updateProductHandlingFeeRuleAsync(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode, String id, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> callback) throws Exception
{
return updateProductHandlingFeeRuleAsync( rule, profilecode, id, null, callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* HandlingFeeRule handlingFeeRule = producthandlingfeerules.updateProductHandlingFeeRule( rule, profilecode, id, responseFields);
* </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param dataViewMode DataViewMode
* @param rule The updated details of the product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule updateProductHandlingFeeRule(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode, String id, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.updateProductHandlingFeeRuleClient(_dataViewMode, rule, profilecode, id, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* CountDownLatch latch = producthandlingfeerules.updateProductHandlingFeeRule( rule, profilecode, id, responseFields, callback );
* latch.await() * </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param rule The updated details of the product handling fee rule.
* @return com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
* @see com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule
*/
public CountDownLatch updateProductHandlingFeeRuleAsync(com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule rule, String profilecode, String id, String responseFields, AsyncCallback<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> callback) throws Exception
{
MozuClient<com.mozu.api.contracts.shippingadmin.profile.HandlingFeeRule> client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.updateProductHandlingFeeRuleClient(_dataViewMode, rule, profilecode, id, responseFields);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductHandlingFeeRules producthandlingfeerules = new ProductHandlingFeeRules();
* producthandlingfeerules.deleteProductHandlingFeeRule( profilecode, id);
* </code></pre></p>
* @param id Unique identifier of the customer segment to retrieve.
* @param profilecode The unique, user-defined code of the profile with which the product handling fee rule is associated.
* @param dataViewMode DataViewMode
* @return
*/
public void deleteProductHandlingFeeRule(String profilecode, String id) throws Exception
{
MozuClient client = com.mozu.api.clients.commerce.shipping.admin.profiles.ProductHandlingFeeRulesClient.deleteProductHandlingFeeRuleClient(_dataViewMode, profilecode, id);
client.setContext(_apiContext);
client.executeRequest();
client.cleanupHttpConnection();
}
}
| mit |
ZzJing/ugrad-algorithm-practice | greedy/MultiStockTrader.java | 416 |
public class MultiStockTrader {
public int maxProfit(int[] prices) {
int maxPrft = 0;
for (int i = 0; i < prices.length - 1; i++) {
// check if we should sell the current stock
if (prices[i + 1] > prices[i]) {
int profit = prices[i + 1] - prices[i];
maxPrft += profit;
}
}
return maxPrft;
}
}
| mit |
josepfranco/university-oop-projects | src/domain/interfaces/ICreateCategoryHandler.java | 380 | package domain.interfaces;
/**
* The interface with the create category use case
*
* @author fmartins
*
*/
public interface ICreateCategoryHandler extends IObtainCategoriesHandler {
/**
* Start the use case for the new category
*/
void newCategory();
/**
* @return True if the category was created.
*/
boolean createCategory(String name);
}
| mit |
angelozerr/textmate.java | org.eclipse.tm4e.registry/src/main/java/org/eclipse/tm4e/registry/internal/GrammarCache.java | 3608 | /**
* Copyright (c) 2015-2017 Angelo ZERR.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package org.eclipse.tm4e.registry.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.eclipse.tm4e.registry.IGrammarDefinition;
/**
* Grammar cache.
*
*/
public class GrammarCache {
private final Map<String /* Scope name */, IGrammarDefinition> definitions;
private final Map<String /* Scope name */, Collection<String>> injections;
private final Map<String /* IContentType Id */ , String /* Scope name */> scopeNameBindings;
public GrammarCache() {
this.definitions = new HashMap<>();
this.injections = new HashMap<>();
this.scopeNameBindings = new HashMap<>();
}
/**
* Register a grammar definition.
*
* @param definition
* the grammar definition to register.
*/
public void registerGrammarDefinition(IGrammarDefinition definition) {
definitions.put(definition.getScopeName(), definition);
}
public void unregisterGrammarDefinition(IGrammarDefinition definition) {
definitions.remove(definition.getScopeName());
}
/**
* Returns the whole registered grammar definition.
*
* @return
*/
public Collection<IGrammarDefinition> getDefinitions() {
return this.definitions.values();
}
/**
* Returns the grammar definition from the given <code>scopeName</code> and
* null otherwise.
*
* @param scopeName
* @return the grammar definition from the given <code>scopeName</code> and
* null otherwise.
*/
public IGrammarDefinition getDefinition(String scopeName) {
return definitions.get(scopeName);
}
/**
* Returns list of scope names to inject for the given
* <code>scopeName</code> and null otheriwse.
*
* @param scopeName
* @return list of scope names to inject for the given
* <code>scopeName</code> and null otheriwse.
*/
public Collection<String> getInjections(String scopeName) {
return injections.get(scopeName);
}
/**
* Register the given <code>scopeName</code> to inject to the given scope
* name <code>injectTo</code>.
*
* @param scopeName
* @param injectTo
*/
public void registerInjection(String scopeName, String injectTo) {
Collection<String> injections = getInjections(injectTo);
if (injections == null) {
injections = new ArrayList<>();
this.injections.put(injectTo, injections);
}
injections.add(scopeName);
}
/**
* Returns scope name bound with the given content type and null otherwise.
*
* @param contentTypeId
* @return scope name bound with the given content type and null otherwise.
*/
public String getScopeNameForContentType(String contentTypeId) {
return scopeNameBindings.get(contentTypeId);
}
public String[] getContentTypesForScope(String scopeName) {
if (scopeName == null) {
return null;
}
return scopeNameBindings.entrySet().stream().filter(map -> scopeName.equals(map.getValue()))
.map(map -> map.getKey()).collect(Collectors.toList()).toArray(new String[0]);
}
public void registerContentTypeBinding(String contentTypeId, String scopeName) {
scopeNameBindings.put(contentTypeId, scopeName);
}
}
| mit |
Blacktron/SimpleChat | src/bg/sap/utils/Constants.java | 1098 | package bg.sap.utils;
/**
* @Created by Terrax on 12.04.2015.
*/
public class Constants {
public static final int PORT = 4444;
public static final int SINGLE_BYTE = 1;
public static final int BUFFER_SIZE = 64;
public static final int FRAME_WIDTH = 300;
public static final int FRAME_HEIGHT = 400;
public static final int TEXT_FIELD_WIDTH = 100;
public static final int TEXT_FIELD_HEIGHT = 30;
public static final int FILE_FRAGMENT_SIZE = 1024 * 1024;
public static final String UTF_ENCODING = "UTF-8";
public static final String FILE_DIR = "C:\\Users\\Terrax\\Documents\\IntelliJ Projects\\SimpleChat\\Files\\";
public static final String FILE_UPLOAD = "*File upload";
public static final String FILE_DOWNLOAD = "*File download";
public static final String LOGOUT = "*Logout";
public static final String GET_FILE_LIST = "*Get file list";
public static final String FILE_NOT_FOUND = "File not found";
public static final String INVALID_USER = "Invalid user";
public static final String MESSAGE_SENT = "Message sent to users";
}
| mit |
dominique-debert/Emby.ApiClient.JAva | src/mediabrowser/model/results/RecordingInfoDtoResult.java | 257 | package mediabrowser.model.results;
import mediabrowser.model.livetv.RecordingInfoDto;
import mediabrowser.model.querying.QueryResult;
/**
* Created by Luke on 10/22/2014.
*/
public class RecordingInfoDtoResult extends QueryResult<RecordingInfoDto> {
}
| mit |
absentm/Demo | Android-demo/RecyclerView-demo/app/src/main/java/com/dm/recyclerviewdemo/utils/SystemUtils.java | 1940 | package com.dm.recyclerviewdemo.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* SystemUtils
* Created by dm on 16-11-17.
*/
public class SystemUtils {
private static final String apiKey = "9bc54988bf1086d45f54cad7e82669d0";
public static boolean checkNetworkConnection(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activityNetwork = cm.getActiveNetworkInfo();
return activityNetwork != null && activityNetwork.isConnected();
}
/**
* 获取ApiStore的新闻数据
*/
public static String getNewsJsonStr() {
String httpUrl = "http://apis.baidu.com/txapi/huabian/newtop";
String httpArg = "num=10&page=1";
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("apikey", apiKey);
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
| mit |
yht-fand/cardone-platform-usercenter | consumer-bak/src/test/java/top/cardone/func/v1/usercenter/openUser/U0004FuncTest.java | 3249 | package top.cardone.func.v1.usercenter.openUser;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import top.cardone.ConsumerApplication;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.CollectionUtils;
import top.cardone.context.ApplicationContextHolder;
import java.util.Map;
@Log4j2
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class U0004FuncTest {
@Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/v1/usercenter/openUser/u0004.json")
private String funcUrl;
@Value("file:src/test/resources/top/cardone/func/v1/usercenter/openUser/U0004FuncTest.func.input.json")
private Resource funcInputResource;
@Value("file:src/test/resources/top/cardone/func/v1/usercenter/openUser/U0004FuncTest.func.output.json")
private Resource funcOutputResource;
@Test
public void func() throws Exception {
if (!funcInputResource.exists()) {
FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8);
}
val input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8);
Map<String, Object> parametersMap = ApplicationContextHolder.getBean(Gson.class).fromJson(input, Map.class);
Assert.assertFalse("输入未配置", CollectionUtils.isEmpty(parametersMap));
Map<String, Object> output = Maps.newLinkedHashMap();
for (val parametersEntry : parametersMap.entrySet()) {
val body = ApplicationContextHolder.getBean(Gson.class).toJson(parametersEntry.getValue());
val headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.set("collectionStationCodeForToken", parametersEntry.getKey().split(":")[0]);
headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword(headers.get("collectionStationCodeForToken").get(0)));
val httpEntity = new HttpEntity<>(body, headers);
val json = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class);
val value = ApplicationContextHolder.getBean(Gson.class).fromJson(json, Map.class);
output.put(parametersEntry.getKey(), value);
}
FileUtils.write(funcOutputResource.getFile(), ApplicationContextHolder.getBean(Gson.class).toJson(output), Charsets.UTF_8);
}
} | mit |
Alec-WAM/CrystalMod | src/main/java/alec_wam/CrystalMod/tiles/machine/specialengines/TileInfiniteEngine.java | 7015 | package alec_wam.CrystalMod.tiles.machine.specialengines;
import alec_wam.CrystalMod.api.energy.CapabilityCrystalEnergy;
import alec_wam.CrystalMod.api.energy.ICEnergyStorage;
import alec_wam.CrystalMod.handler.EventHandler;
import alec_wam.CrystalMod.network.CrystalModNetwork;
import alec_wam.CrystalMod.network.IMessageHandler;
import alec_wam.CrystalMod.network.packets.PacketTileMessage;
import alec_wam.CrystalMod.tiles.TileEntityMod;
import alec_wam.CrystalMod.tiles.machine.power.CustomEnergyStorage;
import alec_wam.CrystalMod.tiles.machine.power.converter.PowerUnits;
import alec_wam.CrystalMod.util.BlockUtil;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.energy.CapabilityEnergy;
public class TileInfiniteEngine extends TileEntityMod implements IMessageHandler {
public CustomEnergyStorage energyStorage;
protected int lastSyncPowerStored = -1;
public boolean isRunning;
public boolean lastIsRunning;
public TileInfiniteEngine() {
energyStorage = new CustomEnergyStorage(100000, 200, 200){
@Override
public boolean canExtract(){
return false;
}
};
}
@Override
public void writeCustomNBT(NBTTagCompound nbt){
super.writeCustomNBT(nbt);
energyStorage.writeToNBT(nbt);
}
@Override
public void readCustomNBT(NBTTagCompound nbt){
super.readCustomNBT(nbt);
energyStorage.readFromNBT(nbt);
}
@Override
public void update(){
super.update();
if(!getWorld().isRemote){
boolean powerChanged = (lastSyncPowerStored != energyStorage.getEnergyStored() && shouldDoWorkThisTick(5));
if(powerChanged) {
lastSyncPowerStored = energyStorage.getEnergyStored();
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("Power", energyStorage.getEnergyStored());
CrystalModNetwork.sendToAllAround(new PacketTileMessage(getPos(), "UpdatePower", nbt), this);
}
boolean runningChanged = (lastIsRunning != isRunning && shouldDoWorkThisTick(5));
if(runningChanged) {
lastIsRunning = isRunning;
NBTTagCompound nbt = new NBTTagCompound();
nbt.setBoolean("Running", isRunning);
CrystalModNetwork.sendToAllAround(new PacketTileMessage(getPos(), "UpdateRunning", nbt), this);
}
if(getWorld().isBlockPowered(getPos())){
if(energyStorage.getEnergyStored() >= 100){
energyStorage.setEnergyStored(energyStorage.getEnergyStored()-100);
isRunning = true;
EventHandler.addInfiniteEngine(getWorld().provider.getDimension(), getPos());
if(lastIsRunning !=isRunning){
BlockUtil.markBlockForUpdate(getWorld(), getPos());
}
} else {
isRunning = false;
EventHandler.removeInfiniteEngine(getWorld().provider.getDimension(), getPos());
if(lastIsRunning !=isRunning){
BlockUtil.markBlockForUpdate(getWorld(), getPos());
}
}
} else {
isRunning = false;
EventHandler.removeInfiniteEngine(getWorld().provider.getDimension(), getPos());
if(lastIsRunning !=isRunning){
BlockUtil.markBlockForUpdate(getWorld(), getPos());
}
}
}
}
@Override
public void invalidate(){
super.invalidate();
if(getWorld() !=null && getWorld().provider !=null)EventHandler.removeInfiniteEngine(getWorld().provider.getDimension(), getPos());
}
@Override
public void handleMessage(String messageId, NBTTagCompound messageData, boolean client) {
if(messageId.equalsIgnoreCase("UpdatePower")){
int newPower = messageData.getInteger("Power");
energyStorage.setEnergyStored(newPower);
}
if(messageId.equalsIgnoreCase("UpdateRunning")){
boolean newRunning = messageData.getBoolean("Running");
lastIsRunning = isRunning;
isRunning = newRunning;
if(lastIsRunning !=isRunning){
BlockUtil.markBlockForUpdate(getWorld(), getPos());
}
}
}
@Override
public boolean hasCapability(net.minecraftforge.common.capabilities.Capability<?> capability, net.minecraft.util.EnumFacing facing)
{
return capability == CapabilityEnergy.ENERGY || capability == CapabilityCrystalEnergy.CENERGY || super.hasCapability(capability, facing);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, net.minecraft.util.EnumFacing facing)
{
if (facing != null && capability == CapabilityEnergy.ENERGY){
return (T) energyStorage;
}
if(capability == CapabilityCrystalEnergy.CENERGY){
return (T) new ICEnergyStorage(){
@Override
public int fillCEnergy(int maxReceive, boolean simulate) {
final int cuDemand = (int) Math.floor(getPowerNeeded( PowerUnits.CU, maxReceive ));
final int usedCU = Math.min( maxReceive, cuDemand );
if( !simulate )
{
injectExternalPower( PowerUnits.CU, usedCU );
}
return usedCU;
}
@Override
public int drainCEnergy(int maxExtract, boolean simulate) {
return 0;
}
@Override
public int getCEnergyStored() {
return (int) Math.floor( PowerUnits.RF.convertTo( PowerUnits.CU, energyStorage.getEnergyStored() ) );
}
@Override
public int getMaxCEnergyStored() {
return (int) Math.floor( PowerUnits.RF.convertTo( PowerUnits.CU, energyStorage.getMaxEnergyStored() ) );
}
@Override
public boolean canExtract() {
return false;
}
@Override
public boolean canReceive() {
return true;
}
};
}
return super.getCapability(capability, facing);
}
protected final int getPowerNeeded( final PowerUnits externalUnit, final int maxPowerRequired )
{
return PowerUnits.RF.convertTo( externalUnit, Math.max( 0, getFunnelPowerNeeded( externalUnit.convertTo( PowerUnits.RF, maxPowerRequired ) ) ) );
}
protected int getFunnelPowerNeeded( final double maxRequired )
{
return energyStorage.getMaxEnergyStored() - energyStorage.getEnergyStored();
}
public final int injectExternalPower( final PowerUnits input, final int amt )
{
return PowerUnits.RF.convertTo( input, this.funnelPowerIntoStorage( input.convertTo( PowerUnits.RF, amt ), false ) );
}
protected int funnelPowerIntoStorage( int amt, final boolean sim )
{
if( sim )
{
final int fakeBattery = energyStorage.getEnergyStored() + amt;
if( fakeBattery > energyStorage.getMaxEnergyStored() )
{
return fakeBattery - energyStorage.getMaxEnergyStored();
}
return 0;
}
else
{
final int old = energyStorage.getEnergyStored();
energyStorage.setEnergyStored( energyStorage.getEnergyStored() + amt );
if( old+amt > energyStorage.getMaxEnergyStored() )
{
amt = old - energyStorage.getMaxEnergyStored();
return amt;
}
return 0;
}
}
}
| mit |
Microsoft/vso-httpclient-java | Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/build/webapi/ContinuousDeploymentDefinition.java | 3599 | // @formatter:off
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license. See License.txt in the project root.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*
* See following wiki page for instructions on how to regenerate:
* https://vsowiki.com/index.php?title=Rest_Client_Generation
*/
package com.microsoft.alm.teamfoundation.build.webapi;
import com.microsoft.alm.teamfoundation.core.webapi.TeamProjectReference;
import com.microsoft.alm.teamfoundation.core.webapi.WebApiConnectedServiceRef;
/**
*/
public class ContinuousDeploymentDefinition {
/**
* The connected service associated with the continuous deployment
*/
private WebApiConnectedServiceRef connectedService;
/**
* The definition associated with the continuous deployment
*/
private ShallowReference definition;
private String gitBranch;
private String hostedServiceName;
private TeamProjectReference project;
private String repositoryId;
private String storageAccountName;
private String subscriptionId;
private String website;
private String webspace;
/**
* The connected service associated with the continuous deployment
*/
public WebApiConnectedServiceRef getConnectedService() {
return connectedService;
}
/**
* The connected service associated with the continuous deployment
*/
public void setConnectedService(final WebApiConnectedServiceRef connectedService) {
this.connectedService = connectedService;
}
/**
* The definition associated with the continuous deployment
*/
public ShallowReference getDefinition() {
return definition;
}
/**
* The definition associated with the continuous deployment
*/
public void setDefinition(final ShallowReference definition) {
this.definition = definition;
}
public String getGitBranch() {
return gitBranch;
}
public void setGitBranch(final String gitBranch) {
this.gitBranch = gitBranch;
}
public String getHostedServiceName() {
return hostedServiceName;
}
public void setHostedServiceName(final String hostedServiceName) {
this.hostedServiceName = hostedServiceName;
}
public TeamProjectReference getProject() {
return project;
}
public void setProject(final TeamProjectReference project) {
this.project = project;
}
public String getRepositoryId() {
return repositoryId;
}
public void setRepositoryId(final String repositoryId) {
this.repositoryId = repositoryId;
}
public String getStorageAccountName() {
return storageAccountName;
}
public void setStorageAccountName(final String storageAccountName) {
this.storageAccountName = storageAccountName;
}
public String getSubscriptionId() {
return subscriptionId;
}
public void setSubscriptionId(final String subscriptionId) {
this.subscriptionId = subscriptionId;
}
public String getWebsite() {
return website;
}
public void setWebsite(final String website) {
this.website = website;
}
public String getWebspace() {
return webspace;
}
public void setWebspace(final String webspace) {
this.webspace = webspace;
}
}
| mit |
gochaorg/lang2 | src/test/java/xyz/cofe/lang2/samples/SumItf.java | 2605 | /*
* The MIT License
*
* Copyright 2014 Kamnev Georgiy (nt.gocha@gmail.com).
*
* Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного
* обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"),
* использовать Программное Обеспечение без ограничений, включая неограниченное право на
* использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование
* и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется
* данное Программное Обеспечение, при соблюдении следующих условий:
*
* Вышеупомянутый копирайт и данные условия должны быть включены во все копии
* или значимые части данного Программного Обеспечения.
*
* ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ,
* ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ,
* СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ
* ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ
* ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ
* ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
* ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
*/
package xyz.cofe.lang2.samples;
/**
* @author Kamnev Georgiy (nt.gocha@gmail.com)
*/
public interface SumItf {
public int summa( int a, int b );
}
| mit |
AaricChen/qxcmp-framework | qxcmp-core/src/main/java/com/qxcmp/statistics/SearchKeywords.java | 499 | package com.qxcmp.statistics;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
/**
* 搜索关键字实体
*
* 用于保存用户搜索关键字信息
*
* @author Aaric
*/
@Entity
@Table
@Data
public class SearchKeywords {
@Id
@GeneratedValue
private Long id;
private Date dateCreated;
private String title;
private String userId;
}
| mit |
Duanjiadong/AndroidBasicDJD | viewhelper/src/main/java/cn/djd/ui/view/ClearEditText.java | 4483 | package cn.djd.ui.view;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import cn.djd.ui.R;
/**自定义EditText
* author:ZhouYuChao on 2016/6/21 17:32
*/
public class ClearEditText extends EditText implements View.OnFocusChangeListener,
TextWatcher {
//EditText右侧的删除按钮
private Drawable mClearDrawable;
private boolean hasFoucs;
public ClearEditText(Context context) {
this(context, null);
}
public ClearEditText(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.editTextStyle);
}
public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,获取图片的顺序是左上右下(0,1,2,3,)
mClearDrawable = getCompoundDrawables()[2];
if (mClearDrawable == null) {
mClearDrawable = getResources().getDrawable(
R.drawable.del_s_g);
}
mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(),
mClearDrawable.getIntrinsicHeight());
// 默认设置隐藏图标
setClearIconVisible(false);
// 设置焦点改变的监听
setOnFocusChangeListener(this);
// 设置输入框里面内容发生改变的监听
addTextChangedListener(this);
}
/* @说明:isInnerWidth, isInnerHeight为ture,触摸点在删除图标之内,则视为点击了删除图标
* event.getX() 获取相对应自身左上角的X坐标
* event.getY() 获取相对应自身左上角的Y坐标
* getWidth() 获取控件的宽度
* getHeight() 获取控件的高度
* getTotalPaddingRight() 获取删除图标左边缘到控件右边缘的距离
* getPaddingRight() 获取删除图标右边缘到控件右边缘的距离
* isInnerWidth:
* getWidth() - getTotalPaddingRight() 计算删除图标左边缘到控件左边缘的距离
* getWidth() - getPaddingRight() 计算删除图标右边缘到控件左边缘的距离
* isInnerHeight:
* distance 删除图标顶部边缘到控件顶部边缘的距离
* distance + height 删除图标底部边缘到控件顶部边缘的距离
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (getCompoundDrawables()[2] != null) {
int x = (int)event.getX();
int y = (int)event.getY();
Rect rect = getCompoundDrawables()[2].getBounds();
int height = rect.height();
int distance = (getHeight() - height)/2;
boolean isInnerWidth = x > (getWidth() - getTotalPaddingRight()) && x < (getWidth() - getPaddingRight());
boolean isInnerHeight = y > distance && y <(distance + height);
if (isInnerWidth && isInnerHeight) {
this.setText("");
}
}
}
return super.onTouchEvent(event);
}
/**
* 当ClearEditText焦点发生变化的时候,
* 输入长度为零,隐藏删除图标,否则,显示删除图标
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
this.hasFoucs = hasFocus;
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
}
protected void setClearIconVisible(boolean visible) {
Drawable right = visible ? mClearDrawable : null;
setCompoundDrawables(getCompoundDrawables()[0],
getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
}
@Override
public void onTextChanged(CharSequence s, int start, int count, int after) {
if (hasFoucs) {
setClearIconVisible(s.length() > 0);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
| mit |
tbepler/LRPaGe | src/com/sun/codemodel/JCase.java | 3273 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.codemodel;
/**
* Case statement
*/
public final class JCase implements JStatement {
/**
* label part of the case statement
*/
private JExpression label;
/**
* JBlock of statements which makes up body of this While statement
*/
private JBlock body = null;
/**
* is this a regular case statement or a default case statement?
*/
private boolean isDefaultCase = false;
/**
* Construct a case statement
*/
JCase(JExpression label) {
this(label, false);
}
/**
* Construct a case statement. If isDefaultCase is true, then
* label should be null since default cases don't have a label.
*/
JCase(JExpression label, boolean isDefaultCase) {
this.label = label;
this.isDefaultCase = isDefaultCase;
}
public JExpression label() {
return label;
}
public JBlock body() {
if (body == null) body=new JBlock( false, true );
return body;
}
public void state(JFormatter f) {
f.i();
if( !isDefaultCase ) {
f.p("case ").g(label).p(':').nl();
} else {
f.p("default:").nl();
}
if (body != null)
f.s(body);
f.o();
}
}
| mit |
Ledningskollen/ledningskollen-ws-java | src/se/ledningskollen/api/cableowner/DeleteAreaOfInterestResponse.java | 1771 |
package se.ledningskollen.api.cableowner;
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.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="DeleteAreaOfInterestResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"deleteAreaOfInterestResult"
})
@XmlRootElement(name = "DeleteAreaOfInterestResponse")
public class DeleteAreaOfInterestResponse {
@XmlElement(name = "DeleteAreaOfInterestResult")
protected String deleteAreaOfInterestResult;
/**
* Gets the value of the deleteAreaOfInterestResult property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDeleteAreaOfInterestResult() {
return deleteAreaOfInterestResult;
}
/**
* Sets the value of the deleteAreaOfInterestResult property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDeleteAreaOfInterestResult(String value) {
this.deleteAreaOfInterestResult = value;
}
}
| cc0-1.0 |
varocarbas/FlexibleParser_Java | all_code/UnitParser/src_Internal/InternalUnitParser/Operations/Equals.java | 3222 | package InternalUnitParser.Operations;
import InternalUnitParser.Classes.*;
import InternalUnitParser.CSharpAdaptation.*;
import UnitParser.*;
import UnitParser.UnitP.*;
import java.util.ArrayList;
public class Equals
{
public static boolean UnitPVarsAreEqual(UnitP first, UnitP second)
{
return
(
UnitPNonUnitInfoAreEqual(first, second) &&
UnitPUnitInfoAreEqual(first, second)
);
}
static boolean UnitPNonUnitInfoAreEqual(UnitP first, UnitP second)
{
return
(
first.getError().equals(second.getError())
);
}
static boolean UnitPUnitInfoAreEqual(UnitP first, UnitP second)
{
return UnitInfosAreEqual
(
ExceptionInstantiation.NewUnitInfo
(
first.getValue(), first.getUnit(), first.getUnitPrefix()
),
ExceptionInstantiation.NewUnitInfo
(
second.getValue(), second.getUnit(), second.getUnitPrefix()
)
);
}
public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo)
{
return UnitInfosAreEqual(firstInfo, secondInfo, false);
}
public static boolean UnitInfosAreEqual(UnitInfo firstInfo, UnitInfo secondInfo, boolean ignoreValues)
{
if (firstInfo.Error.getType() == ErrorTypes.None || secondInfo.Error.getType() == ErrorTypes.None)
{
return firstInfo.Error.getType() == secondInfo.Error.getType();
}
UnitInfo firstInfo2 = Managed.NormaliseUnitInfo(firstInfo);
UnitInfo secondInfo2 = Managed.NormaliseUnitInfo(secondInfo);
return
(
(ignoreValues || UnitInfoValuesAreEqual(firstInfo2, secondInfo2)) &&
UnitInfoUnitsAreEqual(firstInfo2, secondInfo2)
);
}
//This method assumes that both inputs are normalised.
static boolean UnitInfoValuesAreEqual(UnitInfo firstInfo, UnitInfo secondInfo)
{
return
(
firstInfo.BaseTenExponent == secondInfo.BaseTenExponent &&
firstInfo.Value == secondInfo.Value
);
}
public static boolean UnitInfoUnitsAreEqual(UnitInfo firstUnit, UnitInfo secondUnit)
{
return UnitPartListsAreEqual(firstUnit.Parts, secondUnit.Parts);
}
//This method expects fully expanded/simplified unit parts.
static boolean UnitPartListsAreEqual(ArrayList<UnitPart> firstParts, ArrayList<UnitPart> secondParts)
{
if (firstParts.size() != secondParts.size()) return false;
for (UnitPart firstPart: firstParts)
{
if (Linq.FirstOrDefault(secondParts, x -> x.equals(firstPart), null) == null)
{
return false;
}
}
return true;
}
public static boolean PrefixesAreEqual(Prefix first, Prefix second)
{
return
(
first.getType() == second.getType() &&
first.getFactor() == second.getFactor()
);
}
public static boolean UnitPartsAreEqual(UnitPart first, UnitPart second)
{
return
(
first.Exponent == second.Exponent &&
first.getUnit() == second.getUnit() &&
first.getPrefix().getFactor() == second.getPrefix().getFactor()
);
}
public static boolean ErrorsAreEqual(ErrorInfo first, ErrorInfo second)
{
return
(
first.getExceptionHandling() == second.getExceptionHandling() &&
first.getType() == second.getType()
);
}
public static boolean CompoundPartsAreEqual(CompoundPart first, CompoundPart second)
{
return
(
first.Exponent == second.Exponent &&
first.Type == second.Type
);
}
} | cc0-1.0 |
CodeFX-org/demo-junit-5 | src/main/java/org/codefx/demo/junit5/RandomIntegerResolver.java | 1031 | package org.codefx.demo.junit5;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import java.util.Random;
public class RandomIntegerResolver implements ParameterResolver {
private static final Random RANDOM = new Random();
@Override
public boolean supportsParameter(
ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
// don't blindly support a common type like `Integer`
// instead it should be annotated with `@Randomized` or something
Class<?> targetType = parameterContext.getParameter().getType();
return targetType == Integer.class || targetType == int.class;
}
@Override
public Object resolveParameter(
ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return RANDOM.nextInt();
}
}
| cc0-1.0 |
e3r8ick/urSQL | urSQL/src/objects/datatypes/URSQL_Varchar.java | 320 | package objects.datatypes;
/**
* @author maikol_beto
*/
public class URSQL_Varchar extends DataType implements utils.Constants {
public URSQL_Varchar() {
type = VARCHAR;
size = VARCHAR_SIZE;
}
@Override
public String toString ()
{
return "VARCHAR (25)";
}
}
| cc0-1.0 |
rgonzaleztec/icsscREDES | Verano2016-17/SistemaSeguridad/SEGURITEC-Android/core/src/main/java/ibmmobileappbuilder/ui/MenuFragment.java | 5106 | /*
* Copyright 2016.
* This code is part of IBM Mobile UI Builder
*/
package ibmmobileappbuilder.ui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import ibmmobileappbuilder.MenuItem;
import ibmmobileappbuilder.actions.Action;
import ibmmobileappbuilder.behaviors.Behavior;
import ibmmobileappbuilder.core.R;
import ibmmobileappbuilder.util.image.ImageLoader;
import ibmmobileappbuilder.util.image.PicassoImageLoader;
import static ibmmobileappbuilder.util.image.ImageLoaderRequest.Builder.imageLoaderRequest;
/**
* These fragments has 3 possible layouts: list, list with image and grid (2-cols)
*/
public abstract class MenuFragment extends BaseFragment implements AbsListView.OnItemClickListener {
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private List<MenuItem> mMenuItems;
private AbsListView mList;
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
mMenuItems = getMenuItems();
}
@Override
@SuppressWarnings("unchecked")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(getLayout(), container, false);
mList = (AbsListView) view.findViewById(android.R.id.list);
if (mList == null) {
throw new IllegalStateException("Layout is not a menu layout");
}
// set adapter
((AdapterView) mList).setAdapter(getAdapter());
// bind clicklistener
mList.setOnItemClickListener(this);
mList.setEmptyView(view.findViewById(android.R.id.empty));
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mList = null;
}
@Override
public void onDestroy() {
super.onDestroy();
mMenuItems = null;
}
private ArrayAdapter<MenuItem> getAdapter() {
MenuItem[] pagesArr = mMenuItems.toArray(new MenuItem[mMenuItems.size()]);
return new ArrayAdapter<MenuItem>(getActivity(),
getItemLayout(),
android.R.id.text1, // all layouts have a TextView field with id "text1"
pagesArr
) {
@Override
public View getView(int position, View convertView, ViewGroup container) {
View v; // = super.getView(position, convertView, container);
if (convertView != null) {
v = convertView;
} else {
v = getActivity().getLayoutInflater()
.inflate(getItemLayout(), container, false);
}
defaultItemBinding(getItem(position), v);
return v;
}
};
}
// specific bindings for menu pages
private void defaultItemBinding(MenuItem item, View view) {
ImageView image = (ImageView) view.findViewById(R.id.image);
if (image != null) {
if (item.getIconUrl() != null) {
ImageLoader imageLoader = new PicassoImageLoader(image.getContext());
imageLoader.load(imageLoaderRequest()
.withPath(item.getIconUrl())
.withTargetView(image)
.build()
);
} else {
image.setImageResource(item.getIcon());
}
}
TextView text = (TextView) view.findViewById(R.id.title);
if (text != null) {
text.setText(item.getLabel());
}
}
// OnItemClickListener interface
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// execute local action
executeAction(mMenuItems.get(position));
}
/**
* invoke the action to execute when an item is selected
*
* @param item the menu item
*/
public void executeAction(MenuItem item) {
Action cmd = item.getAction();
if (cmd != null) {
cmd.execute(getActivity());
for (Behavior behavior : behaviors) {
behavior.onActionClick(cmd.getAnalyticsInfo());
}
}
}
// delegates
/**
* get this menu's items. Only Page label is used, since the layout is inferred from parent
*
* @return the list of menu items
*/
public abstract List<MenuItem> getMenuItems();
/**
* Gets the layout for this fragment
*
* @return a valid layout for menus
*/
public abstract int getLayout();
/**
* Gets the layout for this menu items
*
* @return the resource id for item layouts
*/
public abstract int getItemLayout();
}
| cc0-1.0 |
opendaylight/netvirt | bgpmanager/impl/src/main/java/org/opendaylight/netvirt/bgpmanager/DisplayBgpConfigCli.java | 4098 | /*
* Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others. 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
*/
package org.opendaylight.netvirt.bgpmanager;
import java.io.PrintStream;
import java.util.Date;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.apache.thrift.transport.TTransport;
import org.opendaylight.netvirt.bgpmanager.commands.Cache;
import org.opendaylight.ovsdb.utils.mdsal.utils.TransactionHistory;
@Command(scope = "odl", name = "display-bgp-config", description = "")
public class DisplayBgpConfigCli extends OsgiCommandSupport {
@Option(name = "--debug", description = "print debug time stamps",
required = false, multiValued = false)
Boolean debug = false;
@Option(name = "--history", description = "print bgp updates",
required = false, multiValued = false)
Boolean showHistory = false;
private final BgpManager bgpManager;
public DisplayBgpConfigCli(BgpManager bgpManager) {
this.bgpManager = bgpManager;
}
@SuppressWarnings("checkstyle:RegexpSinglelineJava")
@Override
protected Object doExecute() throws Exception {
PrintStream ps = System.out;
if (debug) {
ps.printf("%nis ODL Connected to Q-BGP: %s%n", bgpManager.isBgpConnected() ? "TRUE" : "FALSE");
final TTransport transport = bgpManager.getBgpConfigurationManager().getTransport();
if (transport != null) {
ps.printf("%nODL BGP Router transport is open: %s%n",
transport.isOpen() ? "TRUE" : "FALSE");
} else {
ps.printf("%nODL BGP Router transport is NULL%n");
}
//last ODL connection attempted TS
ps.printf("Last ODL connection attempt TS: %s%n", new Date(bgpManager.getConnectTS()));
//last successful connected TS
ps.printf("Last Successful connection TS: %s%n", new Date(bgpManager.getLastConnectedTS()));
//last ODL started BGP due to configuration trigger TS
ps.printf("Last ODL started BGP at: %s%n", new Date(bgpManager.getStartTS()));
//last Quagga attempted to RESTART the connection
ps.printf("Last Quagga BGP, sent reSync at: %s%n", new Date(bgpManager.getQbgprestartTS()));
//stale cleanup start - end TS
ps.printf("Time taken to create stale fib : %s ms%n",
bgpManager.getStaleEndTime() - bgpManager.getStaleStartTime());
//Config replay start - end TS
ps.printf("Time taken to create replay configuration : %s ms%n",
bgpManager.getCfgReplayEndTime() - bgpManager.getCfgReplayStartTime());
//Stale cleanup time
ps.printf("Time taken for Stale FIB cleanup : %s ms%n", bgpManager.getStaleCleanupTime());
ps.printf("Total stale entries created %d %n",
bgpManager.getBgpConfigurationManager().getTotalStaledCount());
ps.printf("Total stale entries cleared %d %n",
bgpManager.getBgpConfigurationManager().getTotalCleared());
ps.printf("Am I Owner %s %n",
bgpManager.getBgpConfigurationManager().isBGPEntityOwner() ? "True" : "False");
}
if (showHistory) {
TransactionHistory bgpUpdatesHistory = bgpManager.getBgpConfigurationManager().getBgpUpdatesHistory();
bgpUpdatesHistory.getElements().forEach(update -> {
Date date = new Date(update.getDate());
ps.println(date);
ps.print(update.getData());
ps.println();
});
}
Cache cache = new Cache(bgpManager);
return cache.show(session);
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | utils/eclipselink.utils.workbench.test/scplugin/source/org/eclipse/persistence/tools/workbench/test/scplugin/model/adapter/DefaultSessionLogAdapterTest.java | 2661 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.test.scplugin.model.adapter;
import org.eclipse.persistence.tools.workbench.test.scplugin.AllSCTests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.persistence.tools.workbench.scplugin.SCProblemsConstants;
import org.eclipse.persistence.tools.workbench.scplugin.model.adapter.DataSource;
import org.eclipse.persistence.tools.workbench.scplugin.model.adapter.DatabaseSessionAdapter;
import org.eclipse.persistence.tools.workbench.scplugin.model.adapter.DefaultSessionLogAdapter;
import org.eclipse.persistence.tools.workbench.scplugin.model.adapter.TopLinkSessionsAdapter;
public class DefaultSessionLogAdapterTest extends AbstractAdapterTest
{
public DefaultSessionLogAdapterTest(String name)
{
super(name);
}
public static Test suite()
{
return new TestSuite(DefaultSessionLogAdapterTest.class, "DefaultSessionLogAdapter Test");
}
public void testVerifyProblemMappingProject() throws Exception
{
TopLinkSessionsAdapter sessions = AllSCTests.createNewSessions();
DataSource ds = buildOracleDataSource();
DatabaseSessionAdapter session = sessions.addDatabaseSessionNamed("MyDatabaseSession", noServerPlatform(), ds);
DefaultSessionLogAdapter log = session.setDefaultLogging();
// File Name should fail
log.setFileName("");
assertTrue("File Name - Should have problem",
hasProblem(SCProblemsConstants.DEFAULT_LOGGING_FILE_NAME, log));
// Fix File Name
log.setFileName("/toplink-dd.log");
assertFalse("Has a File Name - Should not have problem",
hasProblem(SCProblemsConstants.DEFAULT_LOGGING_FILE_NAME, log));
// Fix Name should fail
log.setFileName(DefaultSessionLogAdapter.DEFAULT_LOG_FILE);
assertFalse("Has a File Name - Should not have problem",
hasProblem(SCProblemsConstants.DEFAULT_LOGGING_FILE_NAME, log));
}
}
| epl-1.0 |
Axellience/emfgwt | emf-edit/src/main/java/org/eclipse/emf/edit/provider/WrapperItemProvider.java | 27521 | /**
* Copyright (c) 2004-2010 IBM Corporation and others.
* 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:
* IBM - Initial API and implementation
*/
package org.eclipse.emf.edit.provider;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandWrapper;
import org.eclipse.emf.common.command.UnexecutableCommand;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.EMFEditPlugin;
import org.eclipse.emf.edit.command.AbstractOverrideableCommand;
import org.eclipse.emf.edit.command.CommandParameter;
import org.eclipse.emf.edit.command.CopyCommand;
import org.eclipse.emf.edit.command.DragAndDropCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.edit.domain.EditingDomain;
/**
* A basic implementation of <code>IWrapperProvider</code> from which others can extend. This class provides
* all the methods required to implement the following item provider interfaces:
* <ul>
* <li>{@link IStructuredItemContentProvider}
* <li>{@link ITreeItemContentProvider}
* <li>{@link IItemLabelProvider}
* <li>{@link IItemFontProvider}
* <li>{@link IItemColorProvider}
* <li>{@link IItemPropertySource}
* <li>{@link IEditingDomainItemProvider}
* </ul>
* <p>Subclasses should declare which of these interfaces they are meant to implement, and override methods as needed.
* In addition, a partial implementation for {@link IUpdateableItemText} is provided, along with additional methods and
* classes that are useful in implementing multiple subclasses.
*/
public class WrapperItemProvider implements IWrapperItemProvider
{
/**
* The wrapped value.
*/
protected Object value;
/**
* The object that owns the value.
*/
protected Object owner;
/**
* The structural feature, if applicable, through which the value can be set and retrieved.
*/
protected EStructuralFeature feature;
/**
* The index at which the value is located. If {@link #feature} is non-null, this index is within that feature.
*/
protected int index;
/**
* The adapter factory for the owner's item provider.
*/
protected AdapterFactory adapterFactory;
/**
* Creates an instance. The adapter factory of the owner's item provider may be needed for echoing notifications and
* providing property descriptors.
*/
public WrapperItemProvider(Object value, Object owner, EStructuralFeature feature, int index, AdapterFactory adapterFactory)
{
this.value = value;
this.owner = owner;
this.feature = feature;
this.index = index;
this.adapterFactory = adapterFactory;
}
/**
* Disposes the wrapper by deactivating any notification that this wrapper may provide. Since this implementation
* does not provide any notification, this method does nothing.
*/
public void dispose()
{
// Do nothing.
}
/**
* Returns the wrapped value.
*/
public Object getValue()
{
return value;
}
/**
* Returns the object that owns the value.
*/
public Object getOwner()
{
return owner;
}
/**
* Returns the structural feature through which the value can be set and retrieved, or null if the feature is
* unknown or not applicable.
*/
public EStructuralFeature getFeature()
{
return feature;
}
/**
* The index at which the value is located, or {@link org.eclipse.emf.edit.command.CommandParameter#NO_INDEX} if the
* index isn't known to the wrapper. If {@link #feature} is non-null, this index is within that feature.
*/
public int getIndex()
{
return index;
}
/**
* Sets the index. Has no effect if the index isn't known to the wrapper.
*/
public void setIndex(int index)
{
this.index = index;
}
/**
* {@link IStructuredItemContentProvider#getElements IStructuredItemContentProvider.getElements} is implemented by
* forwarding the call to {@link #getChildren getChildren}.
*/
public Collection<?> getElements(Object object)
{
return getChildren(object);
}
/**
* {@link ITreeItemContentProvider#getChildren ITreeItemContentProvider.getChildren} is implemented to return an
* empty list. Subclasses may override it to return something else.
*/
public Collection<?> getChildren(Object object)
{
return Collections.emptyList();
}
/**
* {@link ITreeItemContentProvider#hasChildren ITreeItemContentProvider.hasChildren} is implemented by testing
* whether the collection returned by {@link #getChildren getChildren} is non-empty.
*/
public boolean hasChildren(Object object)
{
return !getChildren(object).isEmpty();
}
/**
* {@link ITreeItemContentProvider#getParent ITreeItemContentProvider.getParent} is implemented by returning the
* {@link #owner}.
*/
public Object getParent(Object object)
{
return owner;
}
/**
* {@link org.eclipse.emf.edit.provider.IItemLabelProvider#getText IItemLabelProvider.getText} is implemented by returning a non-null value, as a
* string, or "null".
*/
public String getText(Object object)
{
return value != null ? value.toString() : "null";
}
/**
* {@link org.eclipse.emf.edit.provider.IItemLabelProvider#getImage IItemLabelProvider.getImage} is implemented by returning the default icon for
* an EMF.Edit item.
*/
public Object getImage(Object object)
{
return EMFEditPlugin.INSTANCE.getImage("full/obj16/Item");
}
/**
* {@link org.eclipse.emf.edit.provider.IItemFontProvider#getFont IItemFontProvider.getFont} is implemented by returning null.
*/
public Object getFont(Object object)
{
return null;
}
/**
* {@link org.eclipse.emf.edit.provider.IItemColorProvider#getForeground IItemColorProvider.getForeground} is implemented by returning null.
*/
public Object getForeground(Object object)
{
return null;
}
/**
* {@link org.eclipse.emf.edit.provider.IItemColorProvider#getBackground IItemColorProvider.getBackground} is implemented by returning null.
*/
public Object getBackground(Object object)
{
return null;
}
/**
* {@link IUpdateableItemText#getUpdateableText IUpdateableItemText.getUpdateableText} is implemented by forwarding
* the call to {@link #getText getText}.
*/
public String getUpdateableText(Object object)
{
return getText(object);
}
/**
* {@link IItemPropertySource#getPropertyDescriptors IItemPropertySource.getPropertyDescriptors} is implemented to
* return an empty list. Subclasses may override it to return something else.
*/
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object)
{
return Collections.emptyList();
}
/**
* {@link IItemPropertySource#getPropertyDescriptor IItemPropertySource.getPropertyDescriptor} is implemented by
* iterating over the descriptors returned by {@link #getPropertyDescriptors getPropertyDescriptors}, and returning
* the first descriptor whose {@link IItemPropertyDescriptor#getId(Object) ID}
* or {@link IItemPropertyDescriptor#getFeature(Object) feature} matches the specified ID,
* or <code>null</code> if none match.
*/
public IItemPropertyDescriptor getPropertyDescriptor(Object object, Object propertyId)
{
for (IItemPropertyDescriptor descriptor : getPropertyDescriptors(object))
{
if (propertyId.equals(descriptor.getId(object)) || propertyId.equals(descriptor.getFeature(object)))
{
return descriptor;
}
}
return null;
}
/**
* {@link IItemPropertySource#getEditableValue IItemPropertySource.getEditableValue} is implemented to return the
* value, itself.
*/
public Object getEditableValue(Object object)
{
return value;
}
/**
* Returns a name for a value's single property. Subclasses may use this in creating a property descriptor, and user
* subclasses may override it to provide a specific name.
*/
protected String getPropertyName()
{
return EMFEditPlugin.INSTANCE.getString("_UI_ValueProperty_name");
}
/**
* Returns a description for a value's single property. Subclasses may use this in creating a property descriptor,
* and user subclasses may override it to provide a specific name.
*/
protected String getPropertyDescription()
{
return EMFEditPlugin.INSTANCE.getString("_UI_ValueProperty_description");
}
/**
* Returns whether a value's single property is settable. By default, this returns whether the structural feature is
* {@link org.eclipse.emf.ecore.EStructuralFeature#isChangeable changeable}. Subclasses may use this in creating a
* property descriptor, and user subclasses may override it to restrict or allow setting of the property.
*/
protected boolean isPropertySettable()
{
return feature.isChangeable();
}
/**
* Returns whether value's single property consists of multi-line text. By default, false is returned. Subclasses may use this in
* creating a property descriptor, and user subclasses may override it to enable multi-line text editing.
* @since 2.2.0
*/
protected boolean isPropertyMultiLine()
{
return false;
}
/**
* Returns whether value's single property should sort its choices for selection. By default, false is returned. Subclasses
* may use this in creating a property descriptor, and user subclasses may override it to enable sorting.
* @since 2.2.0
*/
protected boolean isPropertySortChoices()
{
return false;
}
/**
* Returns an image for a value's single property. By default, a standard property icon is selected based on the type
* of the structural feature. Subclasses may use this in creating a property descriptor, and user subclasses may
* override it to select a different icon.
*/
protected Object getPropertyImage()
{
return getPropertyImage(feature.getEType().getInstanceClass());
}
/**
* Returns the property image for the specified type. Implementations of {@link #getPropertyImage() getPropertyImage}
* typically call this method.
*/
protected Object getPropertyImage(Class<?> typeClass)
{
if (typeClass == boolean.class || typeClass == Boolean.class)
{
return ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE;
}
else if (typeClass == byte.class || typeClass == Byte.class ||
typeClass == int.class || typeClass == Integer.class ||
typeClass == long.class || typeClass == Long.class ||
typeClass == short.class || typeClass == Short.class)
{
return ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE;
}
else if (typeClass == char.class || typeClass == Character.class ||
typeClass == String.class)
{
return ItemPropertyDescriptor.TEXT_VALUE_IMAGE;
}
else if (typeClass == double.class || typeClass == Double.class ||
typeClass == float.class || typeClass == Float.class)
{
return ItemPropertyDescriptor.REAL_VALUE_IMAGE;
}
return ItemPropertyDescriptor.GENERIC_VALUE_IMAGE;
}
/**
* Returns a category for a value's single property. By default, null is returned. Subclasses may use this in
* creating a property descriptor, and user subclasses may override it to actually provide a category.
*/
protected String getPropertyCategory()
{
return null;
}
/**
* Returns filter flags for a value's single property. By default, null is returned. Subclasses may use this in
* creating a property descriptor, and user subclasses may override it to actually provide filter flags.
*/
protected String[] getPropertyFilterFlags()
{
return null;
}
/**
* {@link IEditingDomainItemProvider#getNewChildDescriptors IEditingDomainItemProvider.getNewChildDescriptors} is
* implemented to return an empty list. Subclasses may override it to return something else.
*/
public Collection<?> getNewChildDescriptors(Object object, EditingDomain editingDomain, Object sibling)
{
return Collections.emptyList();
}
/**
* {IEditingDomainItemProvider#createCommand IEditingDomainItemProvider.createCommand} is implemented via {@link
* #baseCreateCommand baseCreateCommand} to create set, copy, and drag-and-drop commands, only.
*/
public Command createCommand(Object object, EditingDomain domain, Class<? extends Command> commandClass, CommandParameter commandParameter)
{
return baseCreateCommand(object, domain, commandClass, commandParameter);
}
/**
* Implements creation of a set, copy, or drag-and-drop command by calling out to {@link #createSetCommand
* createSetCommand}, {@link #createCopyCommand createCopyCommand}, or {@link #createDragAndDropCommand
* createDragAndDropCommand}.
*/
public Command baseCreateCommand(Object object, EditingDomain domain, Class<? extends Command> commandClass, CommandParameter commandParameter)
{
if (commandClass == SetCommand.class)
{
return
createSetCommand
(domain, commandParameter.getOwner(), commandParameter.getFeature(), commandParameter.getValue(), commandParameter.getIndex());
}
else if (commandClass == CopyCommand.class)
{
return createCopyCommand(domain, commandParameter.getOwner(), (CopyCommand.Helper)commandParameter.getValue());
}
else if (commandClass == DragAndDropCommand.class)
{
DragAndDropCommand.Detail detail = (DragAndDropCommand.Detail)commandParameter.getFeature();
return
createDragAndDropCommand
(domain, commandParameter.getOwner(), detail.location, detail.operations, detail.operation, commandParameter.getCollection());
}
else
{
return UnexecutableCommand.INSTANCE;
}
}
/**
* Return an {@link org.eclipse.emf.common.command.UnexecutableCommand}. Subclasses should override this to map this
* into a real set on a model object.
*/
protected Command createSetCommand(EditingDomain domain, Object owner, Object feature, Object value, int index)
{
return UnexecutableCommand.INSTANCE;
}
/**
* Returns an {@link org.eclipse.emf.common.command.UnexecutableCommand}. An ordinary {@link
* org.eclipse.emf.edit.command.CopyCommand} is only useful for copying model objects, so it would be inappropriate
* here. Subclasses should override it to return something more useful, like a concrete subclass of a {@link
* SimpleCopyCommand} or {@link WrappingCopyCommand}.
*/
protected Command createCopyCommand(EditingDomain domain, Object owner, CopyCommand.Helper helper)
{
return UnexecutableCommand.INSTANCE;
}
/**
* Creates a {@link org.eclipse.emf.edit.command.DragAndDropCommand}.
*/
protected Command createDragAndDropCommand
(EditingDomain domain, Object owner, float location, int operations, int operation, Collection<?> collection)
{
return new DragAndDropCommand(domain, owner, location, operations, operation, collection);
}
/**
* A label for copy command inner classes, the same one used by {@link org.eclipse.emf.edit.command.CopyCommand}.
*/
protected static final String COPY_COMMAND_LABEL = EMFEditPlugin.INSTANCE.getString("_UI_CopyCommand_label");
/**
* A description for copy command inner classes, the same as in {@link org.eclipse.emf.edit.command.CopyCommand}.
*/
protected static final String COPY_COMMAND_DESCRIPTION = EMFEditPlugin.INSTANCE.getString("_UI_CopyCommand_description");
/**
* A command base class for copying a simple value and the wrapper. This is useful when the value isn't able provide
* an adapter to return a copy command, itself. This class just provides the scaffolding; concrete subclasses must
* implement {@link #copy copy} to do the copying.
*/
protected abstract class SimpleCopyCommand extends AbstractOverrideableCommand
{
protected Collection<?> result = Collections.EMPTY_LIST;
protected Collection<?> affectedObjects;
/**
* Creates an instance for the given domain.
*/
public SimpleCopyCommand(EditingDomain domain)
{
super(domain, COPY_COMMAND_LABEL, COPY_COMMAND_DESCRIPTION);
}
/**
* Returns true; this command can requires now preparation and can always be executed.
*/
@Override
protected boolean prepare()
{
return true;
}
/**
* Calls {@link #copy} to do the copying, {@link IDisposable#dispose disposes} the copy, and sets it to
* be the result of the command. Since the copy has not been created within the viewed model, it should never do
* any kind of notification, which is why it is immediately disposed.
*/
@Override
public void doExecute()
{
IWrapperItemProvider copy = copy();
copy.dispose();
result = Collections.singletonList(copy);
}
/**
* Concrete subclasses must implement this to copy and return the value and wrapper.
*/
public abstract IWrapperItemProvider copy();
/**
* Does nothing.
*/
@Override
public void doUndo()
{
// no-op
}
/**
* Does nothing.
*/
@Override
public void doRedo()
{
// no-op
}
/**
* If the command has executed, returns a list containing only the copy of the wrapper.
*/
@Override
public Collection<?> doGetResult()
{
return result;
}
/**
* Returns a list containing only the original wrapper itself.
*/
@Override
public Collection<?> doGetAffectedObjects()
{
if (affectedObjects == null)
{
affectedObjects = Collections.singletonList(WrapperItemProvider.this);
}
return affectedObjects;
}
}
/**
* A command base class for copying the wrapper for a value that is partly copied by another command. This is useful
* when the value includes a model object that is able provide an adapter to return a copy command, but also includes
* an element that is not adaptable, such as a feature map entry. This command copies the non-adapter element and the
* wrapper, which ensures the copy can be copied again.
*/
protected abstract class WrappingCopyCommand extends CommandWrapper
{
protected Collection<?> result = Collections.EMPTY_LIST;
protected Collection<?> affectedObjects;
/**
* Creates an instance where some adaptable value is copied by the given command.
*/
public WrappingCopyCommand(Command command)
{
super(command);
}
/**
* Executes the adaptable-value-copying command, then calls {@link #copy copy} to copy the rest of the value and
* the wrapper, {@link IDisposable#dispose disposes} the copy, and sets it to be the result of the
* command. Since the copy has not been created within the viewed model, it should never do any kind of
* notification, which is why it is immediately disposed.
*/
@Override
public void execute()
{
super.execute();
IWrapperItemProvider copy = copy();
copy.dispose();
result = Collections.singletonList(copy);
}
/**
* Concrete subclasses must implement this to copy and return the value and wrapper. The result of the
* adaptable-value-copying command is available from <code>getCommand().getResult()</code>.
*/
public abstract IWrapperItemProvider copy();
/**
* If the command has executed, returns a list containing only the copy of the wrapper.
*/
@Override
public Collection<?> getResult()
{
return result;
}
/**
* Returns a list containing only the original wrapper itself.
*/
@Override
public Collection<?> getAffectedObjects()
{
if (affectedObjects == null)
{
affectedObjects = Collections.singletonList(WrapperItemProvider.this);
}
return affectedObjects;
}
}
/**
* Returns the {@link #adapterFactory}, if non-composeable, otherwise, returns its root adapter factory.
*/
protected AdapterFactory getRootAdapterFactory()
{
return adapterFactory instanceof ComposeableAdapterFactory ?
((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory() :
adapterFactory;
}
/**
* An item property descriptor for the single property of a wrapper for a simple value. This extends the base
* implementation and substitutes the wrapper's owner for the selected object (the wrapper itself) in the call to {@link
* #getPropertyValue getPropertyValue}. Thus, the owner must be an EObject to use this class. The property's name,
* description, settable flag, static image, category, and filter flags are obtained by calling out to various
* template methods, so can be easily changed by deriving a subclass.
*/
protected class WrapperItemPropertyDescriptor extends ItemPropertyDescriptor
{
public WrapperItemPropertyDescriptor(ResourceLocator resourceLocator, EStructuralFeature feature)
{
super(
WrapperItemProvider.this.adapterFactory,
resourceLocator,
getPropertyName(),
getPropertyDescription(),
feature,
isPropertySettable(),
isPropertyMultiLine(),
isPropertySortChoices(),
getPropertyImage(),
getPropertyCategory(),
getPropertyFilterFlags());
}
/**
* Substitutes the wrapper owner for the selected object and invokes the base implementation. The actual value
* returned depends on the implementation of {@link #getValue getValue}.
*/
@Override
public Object getPropertyValue(Object object)
{
return super.getPropertyValue(owner);
}
/**
* Substitutes the wrapper owner for the selected object and invokes the base implementation.
*/
@Override
public boolean canSetProperty(Object object)
{
return super.canSetProperty(owner);
}
/**
* Returns <code>true</code>, as the property of a value wrapper is always considered to be set.
*/
@Override
public boolean isPropertySet(Object object)
{
return true;
}
/**
* Does nothing, as resetting the property of a value wrapper is not meaningful.
*/
@Override
public void resetPropertyValue(Object object)
{
// Do nothing
}
/**
* Sets the property value. If an editing domain can be obtained, the command returned by {@link #createSetCommand
* createSetcommand} is executed; otherwise, {@link #setValue setValue} is called to set the value.
*/
@Override
public void setPropertyValue(Object object, Object value)
{
EObject eObject = (EObject)owner;
EditingDomain editingDomain = getEditingDomain(owner);
if (editingDomain == null)
{
setValue(eObject, feature, value);
}
else
{
editingDomain.getCommandStack().execute(createSetCommand(editingDomain, eObject, feature, value));
}
}
/**
* Returns a value from a model object. If the feature is multi-valued, only the single value that the wrapper
* represents is returned.
*/
@Override
protected Object getValue(EObject object, EStructuralFeature feature)
{
// When the value is changed, the property sheet page doesn't update the property sheet viewer input
// before refreshing, and this gets called on the obsolete wrapper. So, we need to read directly from the
// model object.
//
//return value;
Object result = ((EObject)owner).eGet(feature);
if (feature.isMany())
{
// If the last object was deleted and the selection was in the property sheet view, the obsolete wrapper will
// reference past the end of the list.
//
List<?> list = (List<?>)result;
result = index >= 0 && index < list.size() ? list.get(index) : value;
}
return result;
}
/**
* Sets a value on a model object. If the feature is multi-valued, only the single value that the wrapper
* represents is set.
*/
protected void setValue(EObject object, EStructuralFeature feature, Object value)
{
if (feature.isMany())
{
@SuppressWarnings("unchecked")
List<Object> list = ((List<Object>)object.eGet(feature));
list.set(index, value);
}
else
{
object.eSet(feature, value);
}
}
/**
* Returns a command that will set the value on the model object. The wrapper is used as the owner of the command,
* unless overridden, so that it can specialize the command that eventually gets created.
*/
protected Command createSetCommand(EditingDomain domain, Object owner, Object feature, Object value)
{
return SetCommand.create(domain, getCommandOwner(WrapperItemProvider.this), null, value);
}
/**
* Returns <code>false</code>, as the property only represents a single value, even if the feature is multi-valued.
*/
@Override
public boolean isMany(Object object)
{
return false;
}
/**
* Substitutes the wrapper owner for the selected object and invokes the base implementation.
*/
@Override
public Collection<?> getChoiceOfValues(Object object)
{
return super.getChoiceOfValues(owner);
}
}
/**
* A <code>ReplacementAffectedObjectCommand</code> wraps another command to return as its affected objects the single
* wrapper that replaces this wrapper. That is, it obtains the children of the wrapper's owner, and returns a
* collection containing the first wrapper whose feature and index match this one's.
*/
protected class ReplacementAffectedObjectCommand extends CommandWrapper
{
public ReplacementAffectedObjectCommand(Command command)
{
super(command);
}
/**
* Obtains the children of the wrapper's owner, and returns a collection containing the first wrapper whose feature
* and index match this one's.
*/
@Override
public Collection<?> getAffectedObjects()
{
Collection<?> children = Collections.EMPTY_LIST;
// Either the IEditingDomainItemProvider or ITreeItemContentProvider item provider interface can give us
// the children.
//
Object adapter = adapterFactory.adapt(owner, IEditingDomainItemProvider.class);
if (adapter instanceof IEditingDomainItemProvider)
{
children = ((IEditingDomainItemProvider)adapter).getChildren(owner);
}
else
{
adapter = adapterFactory.adapt(owner, ITreeItemContentProvider.class);
if (adapter instanceof ITreeItemContentProvider)
{
children = ((ITreeItemContentProvider)adapter).getChildren(owner);
}
}
for (Object child : children)
{
if (child instanceof IWrapperItemProvider)
{
IWrapperItemProvider wrapper = (IWrapperItemProvider)child;
if (wrapper.getFeature() == feature && wrapper.getIndex() == index)
{
return Collections.singletonList(child);
}
}
}
return Collections.EMPTY_LIST;
}
}
}
| epl-1.0 |
diverse-project/k3 | k3-sample/lego/robot.resource.robot/src-gen/robot/resource/robot/util/RobotEclipseProxy.java | 8338 | /**
* <copyright>
* </copyright>
*
*
*/
package robot.resource.robot.util;
/**
* A utility class that bundles all dependencies to the Eclipse platform. Clients
* of this class must check whether the Eclipse bundles are available in the
* classpath. If they are not available, this class is not used, which allows to
* run resource plug-in that are generated by EMFText in stand-alone mode. In this
* case the EMF JARs are sufficient to parse and print resources.
*/
public class RobotEclipseProxy {
/**
* Adds all registered load option provider extension to the given map. Load
* option providers can be used to set default options for loading resources (e.g.
* input stream pre-processors).
*/
public void getDefaultLoadOptionProviderExtensions(java.util.Map<Object, Object> optionsMap) {
if (org.eclipse.core.runtime.Platform.isRunning()) {
// find default load option providers
org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform.getExtensionRegistry();
org.eclipse.core.runtime.IConfigurationElement configurationElements[] = extensionRegistry.getConfigurationElementsFor(robot.resource.robot.mopp.RobotPlugin.EP_DEFAULT_LOAD_OPTIONS_ID);
for (org.eclipse.core.runtime.IConfigurationElement element : configurationElements) {
try {
robot.resource.robot.IRobotOptionProvider provider = (robot.resource.robot.IRobotOptionProvider) element.createExecutableExtension("class");
final java.util.Map<?, ?> options = provider.getOptions();
final java.util.Collection<?> keys = options.keySet();
for (Object key : keys) {
robot.resource.robot.util.RobotMapUtil.putAndMergeKeys(optionsMap, key, options.get(key));
}
} catch (org.eclipse.core.runtime.CoreException ce) {
new robot.resource.robot.util.RobotRuntimeUtil().logError("Exception while getting default options.", ce);
}
}
}
}
/**
* Adds all registered resource factory extensions to the given map. Such
* extensions can be used to register multiple resource factories for the same
* file extension.
*/
public void getResourceFactoryExtensions(java.util.Map<String, org.eclipse.emf.ecore.resource.Resource.Factory> factories) {
if (org.eclipse.core.runtime.Platform.isRunning()) {
org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform.getExtensionRegistry();
org.eclipse.core.runtime.IConfigurationElement configurationElements[] = extensionRegistry.getConfigurationElementsFor(robot.resource.robot.mopp.RobotPlugin.EP_ADDITIONAL_EXTENSION_PARSER_ID);
for (org.eclipse.core.runtime.IConfigurationElement element : configurationElements) {
try {
String type = element.getAttribute("type");
org.eclipse.emf.ecore.resource.Resource.Factory factory = (org.eclipse.emf.ecore.resource.Resource.Factory) element.createExecutableExtension("class");
if (type == null) {
type = "";
}
org.eclipse.emf.ecore.resource.Resource.Factory otherFactory = factories.get(type);
if (otherFactory != null) {
Class<?> superClass = factory.getClass().getSuperclass();
while(superClass != Object.class) {
if (superClass.equals(otherFactory.getClass())) {
factories.put(type, factory);
break;
}
superClass = superClass.getClass();
}
}
else {
factories.put(type, factory);
}
} catch (org.eclipse.core.runtime.CoreException ce) {
new robot.resource.robot.util.RobotRuntimeUtil().logError("Exception while getting default options.", ce);
}
}
}
}
/**
* Gets the resource that is contained in the give file.
*/
public robot.resource.robot.mopp.RobotResource getResource(org.eclipse.core.resources.IFile file) {
org.eclipse.emf.ecore.resource.ResourceSet rs = new org.eclipse.emf.ecore.resource.impl.ResourceSetImpl();
org.eclipse.emf.ecore.resource.Resource resource = rs.getResource(org.eclipse.emf.common.util.URI.createPlatformResourceURI(file.getFullPath().toString(),true), true);
return (robot.resource.robot.mopp.RobotResource) resource;
}
/**
* Checks all registered EMF validation constraints. Note: EMF validation does not
* work if OSGi is not running.
*/
@SuppressWarnings("restriction")
public void checkEMFValidationConstraints(robot.resource.robot.IRobotTextResource resource, org.eclipse.emf.ecore.EObject root) {
// The EMF validation framework code throws a NPE if the validation plug-in is not
// loaded. This is a bug, which is fixed in the Helios release. Nonetheless, we
// need to catch the exception here.
if (new robot.resource.robot.util.RobotRuntimeUtil().isEclipsePlatformRunning()) {
// The EMF validation framework code throws a NPE if the validation plug-in is not
// loaded. This is a workaround for bug 322079.
if (org.eclipse.emf.validation.internal.EMFModelValidationPlugin.getPlugin() != null) {
try {
org.eclipse.emf.validation.service.ModelValidationService service = org.eclipse.emf.validation.service.ModelValidationService.getInstance();
org.eclipse.emf.validation.service.IBatchValidator validator = service.<org.eclipse.emf.ecore.EObject, org.eclipse.emf.validation.service.IBatchValidator>newValidator(org.eclipse.emf.validation.model.EvaluationMode.BATCH);
validator.setIncludeLiveConstraints(true);
org.eclipse.core.runtime.IStatus status = validator.validate(root);
addStatus(status, resource, root);
} catch (Throwable t) {
new robot.resource.robot.util.RobotRuntimeUtil().logError("Exception while checking contraints provided by EMF validator classes.", t);
}
}
}
}
public void addStatus(org.eclipse.core.runtime.IStatus status, robot.resource.robot.IRobotTextResource resource, org.eclipse.emf.ecore.EObject root) {
java.util.List<org.eclipse.emf.ecore.EObject> causes = new java.util.ArrayList<org.eclipse.emf.ecore.EObject>();
causes.add(root);
if (status instanceof org.eclipse.emf.validation.model.ConstraintStatus) {
org.eclipse.emf.validation.model.ConstraintStatus constraintStatus = (org.eclipse.emf.validation.model.ConstraintStatus) status;
java.util.Set<org.eclipse.emf.ecore.EObject> resultLocus = constraintStatus.getResultLocus();
causes.clear();
causes.addAll(resultLocus);
}
boolean hasChildren = status.getChildren() != null && status.getChildren().length > 0;
// Ignore composite status objects that have children. The actual status
// information is then contained in the child objects.
if (!status.isMultiStatus() || !hasChildren) {
if (status.getSeverity() == org.eclipse.core.runtime.IStatus.ERROR) {
for (org.eclipse.emf.ecore.EObject cause : causes) {
resource.addError(status.getMessage(), robot.resource.robot.RobotEProblemType.ANALYSIS_PROBLEM, cause);
}
}
if (status.getSeverity() == org.eclipse.core.runtime.IStatus.WARNING) {
for (org.eclipse.emf.ecore.EObject cause : causes) {
resource.addWarning(status.getMessage(), robot.resource.robot.RobotEProblemType.ANALYSIS_PROBLEM, cause);
}
}
}
for (org.eclipse.core.runtime.IStatus child : status.getChildren()) {
addStatus(child, resource, root);
}
}
/**
* Returns the encoding for this resource that is specified in the workspace file
* properties or determined by the default workspace encoding in Eclipse.
*/
public String getPlatformResourceEncoding(org.eclipse.emf.common.util.URI uri) {
// We can't determine the encoding if the platform is not running.
if (!new robot.resource.robot.util.RobotRuntimeUtil().isEclipsePlatformRunning()) {
return null;
}
if (uri != null && uri.isPlatform()) {
String platformString = uri.toPlatformString(true);
org.eclipse.core.resources.IResource platformResource = org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
if (platformResource instanceof org.eclipse.core.resources.IFile) {
org.eclipse.core.resources.IFile file = (org.eclipse.core.resources.IFile) platformResource;
try {
return file.getCharset();
} catch (org.eclipse.core.runtime.CoreException ce) {
new robot.resource.robot.util.RobotRuntimeUtil().logWarning("Could not determine encoding of platform resource: " + uri.toString(), ce);
}
}
}
return null;
}
}
| epl-1.0 |
theanuradha/debrief | org.mwc.cmap.xyplot/src/org/mwc/cmap/xyplot/views/LocationCalculator.java | 5364 | /*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.mwc.cmap.xyplot.views;
import MWC.Algorithms.EarthModels.CompletelyFlatEarth;
import MWC.GUI.Shapes.LineShape;
import MWC.GenericData.Watchable;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
public class LocationCalculator implements ILocationCalculator
{
private int _units;
public LocationCalculator()
{
this(WorldDistance.DEGS);
}
public LocationCalculator(final int units)
{
setUnits(units);
}
public void setUnits(final int units)
{
this._units = units;
}
@Override
public double getDistance(final LineShape line, final Watchable watchable)
{
return getDistance(line.getLine_Start(), line.getLineEnd(),
watchable.getLocation());
}
/** find the distance from start point to the perpendicular
* line meeting the watch point
* @param start
* @param end
* @param watchableLocation
* @return
*/
private double getDistance(final WorldLocation start, final WorldLocation end,
final WorldLocation watchableLocation)
{
double rangeDegs = watchableLocation.rangeFrom(start);
final double hyp = new WorldDistance(rangeDegs, WorldDistance.DEGS).getValueIn(_units);
// angle from start to end
final double lineBrg = end.bearingFrom(start);
final double pointBrg = watchableLocation.bearingFrom(start);
final double delta = pointBrg - lineBrg;
// how far along x-section?
final double along = hyp * Math.cos(delta);
return along;
}
static public final class LocationTest extends junit.framework.TestCase
{
WorldLocation start, end, watch;
LocationCalculator calc = new LocationCalculator(WorldDistance.MINUTES);
@Override
public final void setUp()
{
// set the earth model we are expecting
MWC.GenericData.WorldLocation.setModel(new CompletelyFlatEarth());
}
public void testGetSampleDistance()
{
// NOTE: this scenario is as described here: http://i.imgur.com/26orkaR.png
start = new WorldLocation(0, 6, 0);
end = new WorldLocation(8, 8, 0);
watch = new WorldLocation(2, 4, 0);
final double lineLen = new WorldDistance(end.subtract(start))
.getValueIn(WorldDistance.DEGS);
assertEquals(8.24621, lineLen, 0.001);
final double perpendicular = watch.rangeFrom(start, end).getValueIn(WorldDistance.DEGS);
assertEquals(2.4253, perpendicular, 0.001);
LocationCalculator calc2 = new LocationCalculator(WorldDistance.DEGS);
final double d = calc2.getDistance(start, end, watch);
assertEquals(1.4552, d, 0.0001);
}
public void testGetDistanceMiddle()
{
start = new WorldLocation(0, 0, 0);
end = new WorldLocation(0, 1, 0);
watch = new WorldLocation(1, 0.5, 0);
final double lineLen = new WorldDistance(end.subtract(start))
.getValueIn(WorldDistance.MINUTES);
assertEquals(60.0, lineLen);
final double perpendicular = watch.rangeFrom(start, end).getValueIn(WorldDistance.MINUTES);
assertEquals(60.0, perpendicular);
final double d = calc.getDistance(start, end, watch);
assertEquals(30.0, d, 0.00001 /* epsilon */);
}
public void testGetDistanceQuarter()
{
start = new WorldLocation(0, 0, 0);
end = new WorldLocation(0, 2, 0);
watch = new WorldLocation(1, 1.5, 0);
final double lineLen = new WorldDistance(end.subtract(start))
.getValueIn(WorldDistance.MINUTES);
assertEquals(60.0 * 2, lineLen);
final double d = Math.abs(calc.getDistance(start, end, watch));
assertEquals(90.0, d, 0.00001 /* epsilon */);
}
public void testDistanceJump()
{
calc = new LocationCalculator(WorldDistance.KM);
start = new WorldLocation(25.0000000, 51.6889495, 0);
end = new WorldLocation(26.3595475, 51.6882503, 0);
watch = new WorldLocation(26.2152611, 51.862166, 40); //0240
System.out.println(calc.getDistance(start, end, watch));
watch = new WorldLocation(26.2144472, 51.8585917, 40);
System.out.println(calc.getDistance(start, end, watch));
watch = new WorldLocation(26.2140611, 51.8572444, 15);
System.out.println(calc.getDistance(start, end, watch));
watch = new WorldLocation(26.2137222, 51.8560667, 15); //0243
System.out.println(calc.getDistance(start, end, watch));
watch = new WorldLocation(26.2133806, 51.8548861, 15); //0244
System.out.println(calc.getDistance(start, end, watch));
//Till this moment the distance is increased.
//There is a "jump" here (the distance is decreased)
watch = new WorldLocation(26.2283833, 51.5456056, 15); //0259
System.out.println(calc.getDistance(start, end, watch));
}
}
}
| epl-1.0 |
ObeoNetwork/Conference-Designer | plugins/fr.obeo.conference.edit/src/conference/provider/LocationItemProvider.java | 5515 | /**
*/
package conference.provider;
import conference.ConferencePackage;
import conference.Location;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link conference.Location} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class LocationItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LocationItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addNamePropertyDescriptor(object);
addTalksPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Name feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addNamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Location_name_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Location_name_feature", "_UI_Location_type"),
ConferencePackage.Literals.LOCATION__NAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Talks feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addTalksPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Location_talks_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Location_talks_feature", "_UI_Location_type"),
ConferencePackage.Literals.LOCATION__TALKS,
true,
false,
true,
null,
null,
null));
}
/**
* This returns Location.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/Location"));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean shouldComposeCreationImage() {
return true;
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((Location)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_Location_type") :
getString("_UI_Location_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(Location.class)) {
case ConferencePackage.LOCATION__NAME:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return ConferenceEditPlugin.INSTANCE;
}
}
| epl-1.0 |
cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee.dongle.ember/src/main/java/com/zsmartsystems/zigbee/dongle/ember/ezsp/command/EzspSetSourceRouteResponse.java | 3281 | /**
* Copyright (c) 2016-2019 by the respective copyright holders.
* 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
*/
package com.zsmartsystems.zigbee.dongle.ember.ezsp.command;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.EzspFrameResponse;
/**
* Class to implement the Ember EZSP command <b>setSourceRoute</b>.
* <p>
* Supply a source route for the next outgoing message.
* <p>
* This class provides methods for processing EZSP commands.
* <p>
* Note that this code is autogenerated. Manual changes may be overwritten.
*
* @author Chris Jackson - Initial contribution of Java code generator
*/
public class EzspSetSourceRouteResponse extends EzspFrameResponse {
public static final int FRAME_ID = 0x5A;
/**
* The destination of the source route.
* <p>
* EZSP type is <i>EmberNodeId</i> - Java type is {@link int}
*/
private int destination;
/**
* The route record. Each relay in the list is an uint16_t node ID.
* <p>
* EZSP type is <i>uint8_t[]</i> - Java type is {@link int[]}
*/
private int[] relayList;
/**
* Response and Handler constructor
*/
public EzspSetSourceRouteResponse(int[] inputBuffer) {
// Super creates deserializer and reads header fields
super(inputBuffer);
// Deserialize the fields
destination = deserializer.deserializeUInt16();
int relayCount = deserializer.deserializeUInt8();
relayList= deserializer.deserializeUInt8Array(relayCount);
}
/**
* The destination of the source route.
* <p>
* EZSP type is <i>EmberNodeId</i> - Java type is {@link int}
*
* @return the current destination as {@link int}
*/
public int getDestination() {
return destination;
}
/**
* The destination of the source route.
*
* @param destination the destination to set as {@link int}
*/
public void setDestination(int destination) {
this.destination = destination;
}
/**
* The route record. Each relay in the list is an uint16_t node ID.
* <p>
* EZSP type is <i>uint8_t[]</i> - Java type is {@link int[]}
*
* @return the current relayList as {@link int[]}
*/
public int[] getRelayList() {
return relayList;
}
/**
* The route record. Each relay in the list is an uint16_t node ID.
*
* @param relayList the relayList to set as {@link int[]}
*/
public void setRelayList(int[] relayList) {
this.relayList = relayList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder(104);
builder.append("EzspSetSourceRouteResponse [destination=");
builder.append(destination);
builder.append(", relayList=");
for (int c = 0; c < relayList.length; c++) {
if (c > 0) {
builder.append(' ');
}
builder.append(String.format("%02X", relayList[c]));
}
builder.append(']');
return builder.toString();
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/process/ui/com.odcgroup.process.model.edit/src/generated/java/com/odcgroup/process/model/provider/ProcessItemProvider.java | 11159 | /**
* Odyssey Financial Technologies
*
* $Id$
*/
package com.odcgroup.process.model.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
import com.odcgroup.process.model.ProcessFactory;
import com.odcgroup.process.model.ProcessPackage;
/**
* This is the item provider adapter for a {@link com.odcgroup.process.model.Process} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ProcessItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final String copyright = "Odyssey Financial Technologies";
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ProcessItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public List getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addNamePropertyDescriptor(object);
addCommentPropertyDescriptor(object);
addDescriptionPropertyDescriptor(object);
addDisplayNamePropertyDescriptor(object);
addInvertedPropertyDescriptor(object);
addFilenamePropertyDescriptor(object);
addMetamodelVersionPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Name feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addNamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Process_name_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Process_name_feature", "_UI_Process_type"),
ProcessPackage.Literals.PROCESS__NAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Comment feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addCommentPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Process_comment_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Process_comment_feature", "_UI_Process_type"),
ProcessPackage.Literals.PROCESS__COMMENT,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Description feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addDescriptionPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Process_description_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Process_description_feature", "_UI_Process_type"),
ProcessPackage.Literals.PROCESS__DESCRIPTION,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Display Name feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addDisplayNamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Process_displayName_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Process_displayName_feature", "_UI_Process_type"),
ProcessPackage.Literals.PROCESS__DISPLAY_NAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Inverted feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInvertedPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Process_inverted_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Process_inverted_feature", "_UI_Process_type"),
ProcessPackage.Literals.PROCESS__INVERTED,
true,
false,
false,
ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Filename feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFilenamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Process_filename_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Process_filename_feature", "_UI_Process_type"),
ProcessPackage.Literals.PROCESS__FILENAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Metamodel Version feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addMetamodelVersionPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Process_metamodelVersion_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Process_metamodelVersion_feature", "_UI_Process_type"),
ProcessPackage.Literals.PROCESS__METAMODEL_VERSION,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Collection getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(ProcessPackage.Literals.PROCESS__POOLS);
childrenFeatures.add(ProcessPackage.Literals.PROCESS__TRANSITIONS);
childrenFeatures.add(ProcessPackage.Literals.PROCESS__TRANSLATIONS);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns Process.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/Process"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getText(Object object) {
String label = ((com.odcgroup.process.model.Process)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_Process_type") :
getString("_UI_Process_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(com.odcgroup.process.model.Process.class)) {
case ProcessPackage.PROCESS__NAME:
case ProcessPackage.PROCESS__COMMENT:
case ProcessPackage.PROCESS__DESCRIPTION:
case ProcessPackage.PROCESS__DISPLAY_NAME:
case ProcessPackage.PROCESS__INVERTED:
case ProcessPackage.PROCESS__FILENAME:
case ProcessPackage.PROCESS__METAMODEL_VERSION:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case ProcessPackage.PROCESS__POOLS:
case ProcessPackage.PROCESS__TRANSITIONS:
case ProcessPackage.PROCESS__TRANSLATIONS:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void collectNewChildDescriptors(Collection newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(ProcessPackage.Literals.PROCESS__POOLS,
ProcessFactory.eINSTANCE.createPool()));
newChildDescriptors.add
(createChildParameter
(ProcessPackage.Literals.PROCESS__TRANSITIONS,
ProcessFactory.eINSTANCE.createFlow()));
newChildDescriptors.add
(createChildParameter
(ProcessPackage.Literals.PROCESS__TRANSLATIONS,
ProcessFactory.eINSTANCE.createTranslation()));
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResourceLocator getResourceLocator() {
return ProcessEditPlugin.INSTANCE;
}
}
| epl-1.0 |