code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/* * Copyright 2016, 2018 Markus Helbig * * 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.mh.kafka.rest.proxy.resource; import org.apache.kafka.clients.consumer.Consumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_SINGLETON; /** * Created by markus on 30/09/2016. */ @Component @EnableScheduling @Scope(value = SCOPE_SINGLETON) public class TopicListInfo { @Autowired private Consumer<String, String> consumer; private List<String> topcis; public TopicListInfo() { topcis = new ArrayList<>(); } @Scheduled(fixedDelay = 2000) void updateTopicList() { Set<String> topics = consumer.listTopics().keySet(); if (!topics.isEmpty()) { topcis.clear(); topcis.addAll(topics); } } List<String> getTopcis() { return topcis; } }
markush81/kafka-rest-proxy
src/main/java/org/mh/kafka/rest/proxy/resource/TopicListInfo.java
Java
apache-2.0
1,784
package iris.audit.server.service; import iris.audit.server.entity.dao.ClientErrorRepository; import iris.audit.server.entity.dao.ClientRepository; import iris.audit.server.entity.dao.ExecutionRepository; import iris.audit.server.entity.dao.ExecutionTypeRepository; import iris.audit.server.entity.dao.JobTypeRepository; import iris.audit.server.entity.dao.LogEntryRepository; import java.security.Principal; import java.util.Date; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.mockito.Mockito.*; import static org.testng.Assert.*; public class AuditServiceImplTest extends AbstractAuditServiceImplTest { @Test public void reportClientException() throws Exception { final String details = ValueUtil.randomString(); final String userName = ValueUtil.randomString(); initializePrincipal( userName ); assertClientErrorCount( 0 ); service().reportClientException( details ); assertClientErrorCount( 1 ); assertEquals( details, s( ClientErrorRepository.class ).findAll().get( 0 ).getDetails() ); } @Test public void auditJobCall() { assertLogEntryCount( 0 ); service().auditJobCall( "X", "X", time(), time(), time(), 0, 0, "X" ); assertLogEntryCount( 1 ); } @Test public void testAuditJobLogCallUsesExistingMetadata() { assertMetadataCounts( 0 ); assertLogEntryCount( 0 ); service().auditJobCall( "User", "JobType", time(), time(), time(), 0, 0, "Message" ); assertMetadataCounts( 1 ); assertLogEntryCount( 1 ); //This removes the job entry but ensures that there is a ExecutionType about s( LogEntryRepository.class ).remove( s( LogEntryRepository.class ).findAll().get( 0 ) ); s( ClientRepository.class ).remove( s( ClientRepository.class ).findAll().get( 0 ) ); s( ExecutionRepository.class ).remove( s( ExecutionRepository.class ).findAll().get( 0 ) ); assertEquals( 1, s( ExecutionTypeRepository.class ).findAll().size() ); service().auditJobCall( "User", "JobType", time(), time(), time(), 0, 0, "Message" ); assertMetadataCounts( 1 ); assertLogEntryCount( 1 ); service().auditJobCall( "User", "JobType", time(), time(), time(), 0, 0, "Message" ); assertMetadataCounts( 1 ); assertLogEntryCount( 2 ); assertEquals( "User", s( ClientRepository.class ).findAll().get( 0 ).getUserName() ); assertEquals( "JobType", s( JobTypeRepository.class ).findAll().get( 0 ).getName() ); } private void assertMetadataCounts( final int n ) { assertEquals( n, s( ClientRepository.class ).findAll().size() ); assertEquals( n, s( JobTypeRepository.class ).findAll().size() ); assertEquals( n, s( ExecutionRepository.class ).findAll().size() ); } private void assertClientErrorCount( final int number ) { assertEquals( number, s( ClientErrorRepository.class ).findAll().size() ); } private void assertLogEntryCount( final int number ) { assertEquals( number, s( LogEntryRepository.class ).findAll().size() ); } private static Date time() { return new Date( 0 ); } private void initializePrincipal( final String userName ) { when( s( Principal.class ).getName() ).thenReturn( userName ); } }
stocksoftware/iris-audit
server/src/test/java/iris/audit/server/service/AuditServiceImplTest.java
Java
apache-2.0
3,253
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.apis.text; import android.widget.TextView; import android.content.Context; import android.text.method.ScrollingMovementMethod; import android.text.method.MovementMethod; import android.text.method.KeyListener; import android.text.method.TransformationMethod; import android.text.Editable; import android.util.AttributeSet; import java.util.Map; /** * This is a TextView that is Editable and by default scrollable, * like EditText without a cursor. * * <p> * <b>XML attributes</b> * <p> * See * {@link android.R.styleable#TextView TextView Attributes}, * {@link android.R.styleable#View View Attributes} */ public class LogTextBox extends TextView { public LogTextBox(Context context) { this(context, null); } public LogTextBox(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.textViewStyle); } public LogTextBox(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected MovementMethod getDefaultMovementMethod() { return ScrollingMovementMethod.getInstance(); } @Override public Editable getText() { return (Editable) super.getText(); } @Override public void setText(CharSequence text, BufferType type) { super.setText(text, BufferType.EDITABLE); } }
huang-qiao/ApiDemos-ASProject
app/src/main/java/com/example/android/apis/text/LogTextBox.java
Java
apache-2.0
2,002
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.features.project.intellij; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.targetgraph.impl.TargetGraphAndTargets; import com.facebook.buck.core.rules.ActionGraphBuilder; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver; import com.facebook.buck.features.project.intellij.aggregation.DefaultAggregationModuleFactory; import com.facebook.buck.features.project.intellij.lang.android.AndroidManifestParser; import com.facebook.buck.features.project.intellij.lang.java.ParsingJavaPackageFinder; import com.facebook.buck.features.project.intellij.model.IjLibraryFactory; import com.facebook.buck.features.project.intellij.model.IjModuleFactoryResolver; import com.facebook.buck.features.project.intellij.model.IjProjectConfig; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.jvm.core.JavaPackageFinder; import com.facebook.buck.jvm.java.JavaFileParser; import com.google.common.collect.ImmutableSet; import java.io.IOException; /** Top-level class for IntelliJ project generation. */ public class IjProject { private final TargetGraphAndTargets targetGraphAndTargets; private final JavaPackageFinder javaPackageFinder; private final JavaFileParser javaFileParser; private final ActionGraphBuilder graphBuilder; private final SourcePathResolver sourcePathResolver; private final SourcePathRuleFinder ruleFinder; private final ProjectFilesystem projectFilesystem; private final IjProjectConfig projectConfig; private final ProjectFilesystem outFilesystem; private final IJProjectCleaner cleaner; public IjProject( TargetGraphAndTargets targetGraphAndTargets, JavaPackageFinder javaPackageFinder, JavaFileParser javaFileParser, ActionGraphBuilder graphBuilder, ProjectFilesystem projectFilesystem, IjProjectConfig projectConfig, ProjectFilesystem outFilesystem) { this.targetGraphAndTargets = targetGraphAndTargets; this.javaPackageFinder = javaPackageFinder; this.javaFileParser = javaFileParser; this.graphBuilder = graphBuilder; this.ruleFinder = new SourcePathRuleFinder(graphBuilder); this.sourcePathResolver = DefaultSourcePathResolver.from(this.ruleFinder); this.projectFilesystem = projectFilesystem; this.projectConfig = projectConfig; this.outFilesystem = outFilesystem; cleaner = new IJProjectCleaner(outFilesystem); } /** * Write the project to disk. * * @return set of {@link BuildTarget}s which should be built in order for the project to index * correctly. * @throws IOException */ public ImmutableSet<BuildTarget> write() throws IOException { final ImmutableSet<BuildTarget> buildTargets = performWriteOrUpdate(false); clean(); return buildTargets; } /** * Write a subset of the project to disk, specified by the targets passed on the command line. * Does not perform a clean of the project space after updating. * * @return set of {@link BuildTarget}s which should be built in to allow indexing * @throws IOException */ public ImmutableSet<BuildTarget> update() throws IOException { return performWriteOrUpdate(true); } /** * Perform the write to disk. * * @param updateOnly whether to write all modules in the graph to disk, or only the ones which * correspond to the listed targets * @return set of {@link BuildTarget}s which should be built in order for the project to index * correctly. * @throws IOException */ private ImmutableSet<BuildTarget> performWriteOrUpdate(boolean updateOnly) throws IOException { final ImmutableSet.Builder<BuildTarget> requiredBuildTargets = ImmutableSet.builder(); IjLibraryFactory libraryFactory = new DefaultIjLibraryFactory( new DefaultIjLibraryFactoryResolver( projectFilesystem, sourcePathResolver, graphBuilder, ruleFinder, requiredBuildTargets)); IjModuleFactoryResolver moduleFactoryResolver = new DefaultIjModuleFactoryResolver( graphBuilder, sourcePathResolver, ruleFinder, projectFilesystem, requiredBuildTargets); SupportedTargetTypeRegistry typeRegistry = new SupportedTargetTypeRegistry( projectFilesystem, moduleFactoryResolver, projectConfig, javaPackageFinder); AndroidManifestParser androidManifestParser = new AndroidManifestParser(projectFilesystem); IjModuleGraph moduleGraph = IjModuleGraphFactory.from( projectFilesystem, projectConfig, targetGraphAndTargets.getTargetGraph(), libraryFactory, new DefaultIjModuleFactory(projectFilesystem, typeRegistry), new DefaultAggregationModuleFactory(typeRegistry)); JavaPackageFinder parsingJavaPackageFinder = ParsingJavaPackageFinder.preparse( javaFileParser, projectFilesystem, IjProjectTemplateDataPreparer.createPackageLookupPathSet(moduleGraph), javaPackageFinder); IjProjectTemplateDataPreparer templateDataPreparer = new IjProjectTemplateDataPreparer( parsingJavaPackageFinder, moduleGraph, projectFilesystem, projectConfig, androidManifestParser); IntellijModulesListParser modulesParser = new IntellijModulesListParser(); IjProjectWriter writer = new IjProjectWriter( templateDataPreparer, projectConfig, projectFilesystem, modulesParser, cleaner, outFilesystem); if (updateOnly) { writer.update(); } else { writer.write(); } PregeneratedCodeWriter pregeneratedCodeWriter = new PregeneratedCodeWriter( templateDataPreparer, projectConfig, outFilesystem, androidManifestParser, cleaner); pregeneratedCodeWriter.write(); if (projectConfig.getGeneratedFilesListFilename().isPresent()) { cleaner.writeFilesToKeepToFile(projectConfig.getGeneratedFilesListFilename().get()); } return requiredBuildTargets.build(); } /** * Run the cleaner after a successful call to write(). This removes stale project files from * previous runs. */ private void clean() throws IOException { cleaner.clean( projectConfig.getBuckConfig(), projectConfig.getProjectPaths().getIdeaConfigDir(), projectConfig.getProjectPaths().getLibrariesDir(), projectConfig.isCleanerEnabled(), projectConfig.isRemovingUnusedLibrariesEnabled()); } }
shs96c/buck
src/com/facebook/buck/features/project/intellij/IjProject.java
Java
apache-2.0
7,403
package org.eu.eark.etl.webscraping; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.jsoup.nodes.Document; /** * extract some specific information from web pages of the domain derstandard.at */ public class DerStandardWebScraper extends WebScraper { private static final String CATEGORY_SELECTOR = "*[typeof=v:Breadcrumb] a[property=v:title]"; private static final String HEADLINE_SELECTOR = "*[itemtype=http://schema.org/Article] *[itemprop=headline]"; private static final String AUTHOR_SELECTOR = "*[itemtype=http://schema.org/Article] *[itemprop=author]"; private static final String DATE_PUBLISHED_SELECTOR = "*[itemtype=http://schema.org/Article] *[itemprop=datePublished]"; private static final String ARTICLE_BODY_SELECTOR = "*[itemtype=http://schema.org/Article] *[itemprop=articleBody]"; private static final String POSTINGS_SELECTOR_OLD = "#forumbarTop .info"; private static final String POSTINGS_SELECTOR = "#weiterLesenScroll .active.light small"; private String category; private String headline; private String author; private DateTime datePublished; private String articleBody; private Integer postings; public DerStandardWebScraper(Document document) { category = new SiteElement(document, CATEGORY_SELECTOR).categoryText(); headline = new SiteElement(document, HEADLINE_SELECTOR).text(); author = new SiteElement(document, AUTHOR_SELECTOR).text(); datePublished = new SiteElement(document, DATE_PUBLISHED_SELECTOR).textAsDateTime(DateTimeFormat.forPattern( "dd. MMMM yyyy, HH:mm").withLocale(Locale.forLanguageTag("de-AT"))); articleBody = new SiteElement(document, ARTICLE_BODY_SELECTOR).text(); String postingsStringOld = new SiteElement(document, POSTINGS_SELECTOR_OLD).ownText(); if (postingsStringOld != null) { postings = 0; if (postingsStringOld.contains(" Postings")) { postings = Integer.parseInt(postingsStringOld.substring(0, postingsStringOld.indexOf(' '))); } else if (postingsStringOld.contains("von ")) { postings = Integer.parseInt(postingsStringOld.substring(postingsStringOld.indexOf("von ") + 4)); } } else { String postingsString = new SiteElement(document, POSTINGS_SELECTOR).ownText(); if (postingsString != null) postings = Integer.parseInt(postingsString.substring(1, postingsString.length()-1)); } } @Override public Object getValue(String element) { switch (element) { case CATEGORY: return category; case HEADLINE: return headline; case AUTHOR: return author; case DATE_PUBLISHED: return datePublished; case ARTICLE_BODY: return articleBody; case POSTINGS: return postings; default: throw new IllegalArgumentException("Invalid element: " + element); } } @Override public List<String> getFieldNames() { return Arrays.asList(CATEGORY, HEADLINE, AUTHOR, DATE_PUBLISHED, ARTICLE_BODY, POSTINGS); } }
eark-project/dm-etl
src/main/java/org/eu/eark/etl/webscraping/DerStandardWebScraper.java
Java
apache-2.0
2,977
package demo.repository; import java.util.List; import demo.domain.Etiqueta; public interface EtiquetaRepository { List<Etiqueta> findAll(); }
joedayz/spring-boot-samples
demo-boot-jpa/src/main/java/demo/repository/EtiquetaRepository.java
Java
apache-2.0
148
package com.java.leetCode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by mi on 17-8-7. */ public class FourSum_18 { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> re = new ArrayList<List<Integer>>(); Arrays.sort(nums); int len = nums.length; for(int i=0;i<len-3;i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } for(int j=i+1;j<len-2;j++) { if (j > i+1 && nums[j] == nums[j - 1]) { continue; } int m = j+1,n=len-1; while (m < n) { if (nums[i] + nums[j] + nums[m] + nums[n] == target) { re.add(Arrays.asList(nums[i], nums[j], nums[m], nums[n])); m++; n--; while (nums[m] == nums[m - 1] && m < n) { m++; } while (nums[n] == nums[n + 1] && m < n) { n--; } } else if (nums[i] + nums[j] + nums[m] + nums[n] > target) { n--; } else { m++; } } } } return re; } }
liushang123/java_study
src/main/java/com.java/leetCode/FourSum_18.java
Java
apache-2.0
1,422
/** * Copyright (C) 2016 Elmar Schug <elmar.schug@jayware.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jayware.gradle.osgi.ds; import org.apache.felix.scrplugin.Options; import org.apache.felix.scrplugin.SCRDescriptorException; import org.apache.felix.scrplugin.SCRDescriptorFailureException; import org.apache.felix.scrplugin.SCRDescriptorGenerator; import org.apache.felix.scrplugin.Source; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.file.FileCollection; import org.gradle.api.file.FileTree; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.TaskAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import static org.gradle.api.plugins.JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME; public class GenerateDeclarativeServicesDescriptorsTask extends DefaultTask { private final Logger log = LoggerFactory.getLogger(GenerateDeclarativeServicesDescriptorsTask.class); private final Project project; private final List<FileCollection> input = new ArrayList<>(); private File outputDirectory; public GenerateDeclarativeServicesDescriptorsTask() { project = getProject(); } @TaskAction public void generateDeclarativeServicesDescriptors() throws SCRDescriptorException, SCRDescriptorFailureException, MalformedURLException { final Options scrOptions = createOptions(); final org.apache.felix.scrplugin.Project scrProject = createProject(); final SCRDescriptorGenerator scrGenerator = new SCRDescriptorGenerator(new GradleSCRDescriptorGeneratorLoggerAdapter(log)); scrGenerator.setOptions(scrOptions); scrGenerator.setProject(scrProject); scrGenerator.execute(); } private org.apache.felix.scrplugin.Project createProject() { final org.apache.felix.scrplugin.Project scrProject = new org.apache.felix.scrplugin.Project(); final Set<File> dependencies = new HashSet<>(); final List<Source> sources = new ArrayList<>(); collectCompileDependencies(dependencies); collectGenerationSources(input, dependencies, sources); scrProject.setClassLoader(new URLClassLoader(toUrlArray(dependencies), this.getClass().getClassLoader())); scrProject.setDependencies(dependencies); scrProject.setSources(sources); return scrProject; } private void collectCompileDependencies(Set<File> dependencies) { final Configuration compileConfiguration = project.getConfigurations().getByName(COMPILE_CLASSPATH_CONFIGURATION_NAME); compileConfiguration.getResolvedConfiguration().getResolvedArtifacts().forEach(artifact -> { final File file = artifact.getFile(); dependencies.add(file); log.info("dependency added: {}", file); }); } private void collectGenerationSources(List<FileCollection> files, Set<File> dependencies, List<Source> sources) { files.forEach(collection -> { collection.forEach(dir -> { final FileTree tree = project.fileTree(dir); final Path root = dir.toPath(); tree.filter(file -> file.getName().endsWith(".class")).forEach(file -> { StringBuilder sb = new StringBuilder(); Iterator<Path> it = root.relativize(file.toPath()).iterator(); while (it.hasNext()) { String element = it.next().toString(); if (it.hasNext()) { sb.append(element).append("."); } else { sb.append(element, 0, element.length() - ".class".length()); } } final String className = sb.toString(); log.debug("Source [{}, {}]", className, file.toString()); sources.add(new GenerationSource(className, file)); dependencies.add(dir); }); }); }); } private URL[] toUrlArray(Set<File> dependencies) { final URL[] result = new URL[dependencies.size()]; int index = 0; for (File file : dependencies) { try { result[index++] = file.toURI().toURL(); } catch (MalformedURLException e) { throw new GradleException("Something went wrong!", e); } } return result; } private Options createOptions() { final Options scrOptions = new Options(); scrOptions.setOutputDirectory(outputDirectory); scrOptions.setStrictMode(false); scrOptions.setSpecVersion(null); return scrOptions; } @OutputDirectory public File getOutputDirectory() { return outputDirectory; } public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } @InputFiles public List<FileCollection> getInput() { return input; } private static class GenerationSource implements Source { private final String myClassName; private final File mySourceFile; private GenerationSource(String className, File sourceFile) { myClassName = className; mySourceFile = sourceFile; } @Override public String getClassName() { return myClassName; } @Override public File getFile() { return mySourceFile; } } }
jayware/gradle-osgi-ds
src/main/java/org/jayware/gradle/osgi/ds/GenerateDeclarativeServicesDescriptorsTask.java
Java
apache-2.0
6,623
package codeine.servlets.api_servlets.angular; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import codeine.ConfigurationManagerServer; import codeine.jsons.command.CommandInfo; import codeine.model.Constants; import codeine.servlet.AbstractApiServlet; import codeine.utils.network.RequestUtils; public class ProjectCommandsApiServlet extends AbstractApiServlet { private static final Logger log = Logger.getLogger(ProjectCommandsApiServlet.class); private static final long serialVersionUID = 1L; @Inject private ConfigurationManagerServer configurationManager; @Override protected boolean checkPermissions(HttpServletRequest request) { return canReadProject(request); } @Override protected void myGet(HttpServletRequest request, HttpServletResponse response) { log.info("ProjectCommandsApiServlet get"); String projectName = RequestUtils.getParameter(request, Constants.UrlParameters.PROJECT_NAME); List<CommandInfo> commands = configurationManager.getProjectCommands(projectName); writeResponseJson(response, commands); } }
codeine-cd/codeine
src/web_server/codeine/servlets/api_servlets/angular/ProjectCommandsApiServlet.java
Java
apache-2.0
1,190
package no.nb.nna.veidemann.chrome.client.ws; public interface ClientClosedListener { void clientClosed(String reason); }
nlnwa/broprox
veidemann-chrome-client/src/main/java/no/nb/nna/veidemann/chrome/client/ws/ClientClosedListener.java
Java
apache-2.0
127
package com.spalmalo.yweather.http; import com.squareup.okhttp.OkHttpClient; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.client.OkClient; public class RestClient { private static Api REST_CLIENT; private static String ROOT = "http://api.openweathermap.org/data/2.5"; static { setupRestClient(); } private RestClient() { } public static Api get() { return REST_CLIENT; } private static void setupRestClient() { RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade request) { request.addPathParam("APPID", "089bf92069d4a25e7835d003635d0e1f"); } }; RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(ROOT) .setClient(new OkClient(new OkHttpClient())) .setRequestInterceptor(requestInterceptor) .setLogLevel(RestAdapter.LogLevel.FULL); RestAdapter restAdapter = builder.build(); REST_CLIENT = restAdapter.create(Api.class); } }
tanuku07/YWeather
app/src/main/java/com/spalmalo/yweather/http/RestClient.java
Java
apache-2.0
1,172
package net.genesishub.gFeatures.API.Inventory; import org.bukkit.entity.Player; public class ClearInventory { public void clearInv(Player p) { for(int j=0; j<38; j++) { p.getInventory().setItem(j, null); } p.getInventory().setHelmet(null); p.getInventory().setChestplate(null); p.getInventory().setLeggings(null); p.getInventory().setBoots(null); } }
GenesisHub/gFeatures
src/net/genesishub/gFeatures/API/Inventory/ClearInventory.java
Java
apache-2.0
365
package org.bbs.apklauncher.emb.auto_gen; import java.util.List; import org.bbs.apklauncher.ReflectUtil.ActivityReflectUtil; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ActivityGroup; import android.app.Dialog; import android.app.ExpandableListActivity; import android.app.Fragment; import android.app.ListActivity; import android.app.TabActivity; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template import android.content.res.Configuration; import android.content.res.Resources.Theme; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.os.PersistableBundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ActionMode; import android.view.ActionMode.Callback; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.widget.ExpandableListView; import android.widget.ListView; import android.support.v4.app.FragmentActivity; import android.support.v7.app.ActionBarActivity; /** * delegate android framework's method call to {@link #mTargetActivity} * @author luoqii * */ @SuppressLint("NewApi") //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template public class StubBase_FragmentActivity extends FragmentActivity { private static final String TAG = StubBase_FragmentActivity.class.getSimpleName(); private static boolean LOG = true; // keep "stub" lower-case. private static boolean LOG_stub = true && LOG; private static boolean LOG_LIFECYCLE = false && LOG; private static boolean LOG_MENU = false && LOG; private static boolean LOG_CONTENT = true && LOG; private static boolean LOG_DIALOG = true && LOG; private static boolean LOG_KEY_EVENT = true && LOG; private static boolean LOG_MOTTION_EVENT = true && LOG; protected Target_FragmentActivity mTargetActivity; //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template public Target_FragmentActivity getTargetActivity(){ return mTargetActivity; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTargetActivity.onCreate(savedInstanceState);; if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onCreate(). savedInstanceState: " + savedInstanceState); } } @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template mTargetActivity.onCreate(savedInstanceState, persistentState); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onCreate(). persistentState: " + persistentState + " persistentState: " + persistentState ); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mTargetActivity.onRestoreInstanceState(savedInstanceState); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onRestoreInstanceState(). savedInstanceState: " + savedInstanceState); } } @Override public void onRestoreInstanceState(Bundle savedInstanceState, //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template PersistableBundle persistentState) { super.onRestoreInstanceState(savedInstanceState, persistentState); mTargetActivity.onRestoreInstanceState(savedInstanceState, persistentState); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onRestoreInstanceState(). persistentState: " + persistentState + " persistentState: " + persistentState ); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mTargetActivity.onPostCreate(savedInstanceState); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onPostCreate(). savedInstanceState: " + savedInstanceState); } } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onPostCreate(savedInstanceState, persistentState); mTargetActivity.onPostCreate(savedInstanceState, persistentState); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onPostCreate(). persistentState: " + persistentState + " persistentState: " + persistentState ); } } @Override protected void onStart() { super.onStart(); mTargetActivity.onStart(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onStart(). " ); } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } @Override protected void onRestart() { super.onStart(); mTargetActivity.onRestart(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onRestart(). " ); } } @Override protected void onResume() { super.onResume(); mTargetActivity.onResume(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onResume(). " ); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } } @Override protected void onPostResume() { super.onPostResume(); mTargetActivity.onPostResume(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onPostResume(). " ); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); mTargetActivity.onNewIntent(intent); if (LOG_LIFECYCLE) { //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template _log(TAG, "call mTargetActivity onNewIntent(). intent: " + intent ); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mTargetActivity.onSaveInstanceState(outState); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onSaveInstanceState(). outState: " + outState ); } } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { super.onSaveInstanceState(outState, outPersistentState); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template mTargetActivity.onSaveInstanceState(outState, outPersistentState); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onSaveInstanceState(). outState: " + outState + " outPersistentState: " + outPersistentState); } } @Override protected void onPause() { super.onPause(); mTargetActivity.onPause(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onPause(). " ); } } @Override protected void onUserLeaveHint() { //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template super.onUserLeaveHint(); mTargetActivity.onUserLeaveHint(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onUserLeaveHint(). " ); } } @Override public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) { boolean created = super.onCreateThumbnail(outBitmap, canvas); return created ? true : mTargetActivity.onCreateThumbnail(outBitmap, canvas); } @Override public CharSequence onCreateDescription() { CharSequence c = super.onCreateDescription(); return TextUtils.isEmpty(c) ? mTargetActivity.onCreateDescription() : c; //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } @Override public void onProvideAssistData(Bundle data) { super.onProvideAssistData(data); mTargetActivity.onProvideAssistData(data); } @Override protected void onStop() { super.onStop(); mTargetActivity.onStop(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onStop(). " ); } } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override protected void onDestroy() { super.onDestroy(); mTargetActivity.onDestroy(); if (LOG_LIFECYCLE) { _log(TAG, "call mTargetActivity onDestroy(). " ); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mTargetActivity.onConfigurationChanged(newConfig); if (LOG) { _log(TAG, "onConfigurationChanged(). config: " + newConfig); } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } // tag_start:No_ActionBarActivity // tag_start:No_FragmentActivity // tag_end:No_FragmentActivity // tag_end:No_ActionBarActivity @Override public void onLowMemory() { super.onLowMemory(); mTargetActivity.onLowMemory(); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); mTargetActivity.onTrimMemory(level); } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override public void onAttachFragment(Fragment fragment) { super.onAttachFragment(fragment); mTargetActivity.onAttachFragment(fragment); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean handled = super.onKeyDown(keyCode, event); return !handled ? mTargetActivity.onKeyDown(keyCode, event) : handled; } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { boolean handled = super.onKeyLongPress(keyCode, event); return !handled ? mTargetActivity.onKeyLongPress(keyCode, event) : handled; //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { boolean handled = super.onKeyUp(keyCode, event); return !handled ? mTargetActivity.onKeyUp(keyCode, event) : handled; } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { boolean handled = super.onKeyMultiple(keyCode, repeatCount, event); return !handled ? mTargetActivity.onKeyMultiple(keyCode, repeatCount, event) : handled; } @Override public void onBackPressed() { super.onBackPressed(); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template // mTargetActivity.onBackPressed(); } @Override public boolean onKeyShortcut(int keyCode, KeyEvent event) { boolean handled = super.onKeyShortcut(keyCode, event); return !handled ? mTargetActivity.onKeyShortcut(keyCode, event) : handled; } @Override public boolean onTouchEvent(MotionEvent event) { boolean handled = super.onTouchEvent(event); return !handled ? mTargetActivity.onTouchEvent(event) : handled; } @Override public boolean onTrackballEvent(MotionEvent event) { //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template boolean handled = super.onTrackballEvent(event); return !handled ? mTargetActivity.onTrackballEvent(event) : handled; } @Override public boolean onGenericMotionEvent(MotionEvent event) { boolean handled = super.onGenericMotionEvent(event); return !handled ? mTargetActivity.onGenericMotionEvent(event) : handled; } @Override public void onUserInteraction() { super.onUserInteraction(); mTargetActivity.onUserInteraction(); } @Override //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template public void onWindowAttributesChanged( android.view.WindowManager.LayoutParams params) { super.onWindowAttributesChanged(params); mTargetActivity.onWindowAttributesChanged(params); } // tag_start:No_ActionBarActivity @Override public void onContentChanged() { super.onContentChanged(); mTargetActivity.onContentChanged(); } // tag_end:No_ActionBarActivity @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template mTargetActivity.onWindowFocusChanged(hasFocus); } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); mTargetActivity.onAttachedToWindow(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); mTargetActivity.onDetachedFromWindow(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template return super.dispatchKeyEvent(event); } @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) { boolean handled = super.dispatchKeyShortcutEvent(event); return !handled ? mTargetActivity.dispatchKeyShortcutEvent(event) : handled; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { boolean handled = super.dispatchTouchEvent(ev); return !handled ? mTargetActivity.dispatchTouchEvent(ev) : handled; } @Override public boolean dispatchTrackballEvent(MotionEvent ev) { //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template boolean handled = super.dispatchTouchEvent(ev); return !handled ? mTargetActivity.dispatchTrackballEvent(ev) : handled; } @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) { boolean handled = super.dispatchGenericMotionEvent(ev); return !handled ? mTargetActivity.dispatchGenericMotionEvent(ev) : handled; } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { boolean handled = super.dispatchPopulateAccessibilityEvent(event); return !handled ? mTargetActivity.dispatchPopulateAccessibilityEvent(event) : handled; } @Override //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template public View onCreatePanelView(int featureId) { View view = mTargetActivity.onCreatePanelView(featureId); return view != null ? view : super.onCreatePanelView(featureId); } @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { boolean show = mTargetActivity.onCreatePanelMenu(featureId, menu); return show ? true : super.onCreatePanelMenu(featureId, menu); } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { boolean show = mTargetActivity.onPreparePanel(featureId, view, menu); return show ? true : super.onPreparePanel(featureId, view, menu); } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override public boolean onMenuOpened(int featureId, Menu menu) { boolean show = mTargetActivity.onMenuOpened(featureId, menu); return show ? true : super.onMenuOpened(featureId, menu); } // tag_start:No_ActionBarActivity @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { boolean finish = mTargetActivity.onMenuItemSelected(featureId, item); return finish ? true : super.onMenuItemSelected(featureId, item); } // tag_end:No_ActionBarActivity @Override public void onPanelClosed(int featureId, Menu menu) { mTargetActivity.onPanelClosed(featureId, menu); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean show = mTargetActivity.onCreateOptionsMenu(menu); return show ? true : super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean show = mTargetActivity.onPrepareOptionsMenu(menu); return show ? true : super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = mTargetActivity.onOptionsItemSelected(item); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template return handled ? true : super.onOptionsItemSelected(item); } @Override public boolean onNavigateUp() { boolean todo = mTargetActivity.onNavigateUp(); return todo ? true : super.onNavigateUp(); } @Override public boolean onNavigateUpFromChild(Activity child) { boolean todo = mTargetActivity.onNavigateUpFromChild(child); return todo ? true : super.onNavigateUpFromChild(child); } @Override public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) { //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template mTargetActivity.onCreateNavigateUpTaskStack(builder); super.onCreateNavigateUpTaskStack(builder); } @Override public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) { mTargetActivity.onPrepareNavigateUpTaskStack(builder); super.onPrepareNavigateUpTaskStack(builder); } @Override public void onOptionsMenuClosed(Menu menu) { mTargetActivity.onOptionsMenuClosed(menu); super.onOptionsMenuClosed(menu); } @Override //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template public void openOptionsMenu() { mTargetActivity.openOptionsMenu(); super.openOptionsMenu(); } @Override public void closeOptionsMenu() { mTargetActivity.closeOptionsMenu(); super.closeOptionsMenu(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { mTargetActivity.onCreateContextMenu(menu, v, menuInfo); super.onCreateContextMenu(menu, v, menuInfo); } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override public boolean onContextItemSelected(MenuItem item) { boolean consumed = mTargetActivity.onContextItemSelected(item); return consumed ? true : super.onContextItemSelected(item); } @Override public void onContextMenuClosed(Menu menu) { mTargetActivity.onContextMenuClosed(menu); super.onContextMenuClosed(menu); } @Override protected Dialog onCreateDialog(int id) { Dialog dia = mTargetActivity.onCreateDialog(id); return dia != null ? dia : super.onCreateDialog(id); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } @Override protected Dialog onCreateDialog(int id, Bundle args) { Dialog dia = mTargetActivity.onCreateDialog(id, args); return dia != null ? dia : super.onCreateDialog(id, args); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); mTargetActivity.onPrepareDialog(id, dialog); } @Override protected void onPrepareDialog(int id, Dialog dialog, Bundle args) { super.onPrepareDialog(id, dialog, args); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template // mTargetActivity.onPrepareDialog(id, dialog, args); } @Override public boolean onSearchRequested() { boolean launched = mTargetActivity.onSearchRequested(); return launched ? true : super.onSearchRequested(); } @Override protected void onApplyThemeResource(Theme theme, int resid, boolean first) { super.onApplyThemeResource(theme, resid, first); if (null != mTargetActivity) { mTargetActivity.onApplyThemeResource(theme, resid, first); } } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override public void overridePendingTransition(int enterAnim, int exitAnim) { super.overridePendingTransition(enterAnim, exitAnim); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mTargetActivity.onActivityResult(requestCode, resultCode, data); } @Override public void onActivityReenter(int resultCode, Intent data) { super.onActivityReenter(resultCode, data); mTargetActivity.onActivityReenter(resultCode, data); } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); mTargetActivity.onTitleChanged(title, color); } @Override protected void onChildTitleChanged(Activity childActivity, CharSequence title) { super.onChildTitleChanged(childActivity, title); mTargetActivity.onChildTitleChanged(childActivity, title); } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { View view = mTargetActivity.onCreateView(name, context, attrs); return view != null ? view : super.onCreateView(name, context, attrs); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { View view = mTargetActivity.onCreateView(parent, name, context, attrs); return view != null ? view : super.onCreateView(parent, name, context, attrs); } @Override public void onVisibleBehindCanceled() { super.onVisibleBehindCanceled(); mTargetActivity.onVisibleBehindCanceled(); } @Override public void onEnterAnimationComplete() { //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template super.onEnterAnimationComplete(); mTargetActivity.onEnterAnimationComplete(); } @Override public ActionMode onWindowStartingActionMode(Callback callback) { return super.onWindowStartingActionMode(callback); } @Override public void onActionModeStarted(ActionMode mode) { super.onActionModeStarted(mode); } @Override public void onActionModeFinished(ActionMode mode) { super.onActionModeFinished(mode); //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template } // tag_start:ListActivity // tag_end:ListActivity // tag_start:FragmentActivity @Override public void onAttachFragment(android.support.v4.app.Fragment fragment) { super.onAttachFragment(fragment); mTargetActivity.onAttachFragment(fragment); } @Override protected void onResumeFragments() { super.onResumeFragments(); mTargetActivity.onResumeFragments(); } //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template @Override public Object onRetainCustomNonConfigurationInstance() { Object o = mTargetActivity.onRetainCustomNonConfigurationInstance(); return o != null ? o : super.onRetainCustomNonConfigurationInstance(); } // tag_end:FragmentActivity // tag_start:PreferenceActivity // tag_end:PreferenceActivity // tag_start:ExpandableListActivity // tag_end:ExpandableListActivity // tag_start:ActionBarActivity // tag_end:ActionBarActivity //do NOT edit this file, auto-generated by host_target.groovy from StubBase_Activity.java.template // auxiliary function private void _log(String tag, String message) { logD(tag, message); if (LOG_stub) { logD(tag, "mTargetActivity: " + mTargetActivity); } } protected void logD(String tag, String message) { android.util.Log.d(tag, message); } }
luoqii/ApkLauncher
library/src/org/bbs/apklauncher/emb/auto_gen/StubBase_FragmentActivity.java
Java
apache-2.0
23,512
package com.serenegiant.mediaeffect; /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2021 saki t_saki@serenegiant.com * * 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. */ import android.media.effect.EffectContext; import android.media.effect.EffectFactory; public class MediaEffectCrop extends MediaEffect { /** * コンストラクタ * GLコンテキスト内で生成すること * * @param effect_context * @param x The origin's x-value. between 0 and width of the image. * @param y The origin's y-value. between 0 and height of the image. * @param width The width of the cropped image. * between 1 and the width of the image minus xorigin. * @param height The height of the cropped image. * between 1 and the height of the image minus yorigin. */ public MediaEffectCrop(final EffectContext effect_context, final int x, final int y, final int width, final int height) { super(effect_context, EffectFactory.EFFECT_CROP); setParameter(x, y, width, height); } /** * @param x The origin's x-value. between 0 and width of the image. * @param y The origin's y-value. between 0 and height of the image. * @param width The width of the cropped image. * between 1 and the width of the image minus xorigin. * @param height The height of the cropped image. * between 1 and the height of the image minus yorigin. * @return */ public MediaEffectCrop setParameter( final int x, final int y, final int width, final int height) { setParameter("xorigin", x); setParameter("yorigin", y); setParameter("width", width); setParameter("height", height); return this; } }
saki4510t/libcommon
common/src/main/java/com/serenegiant/mediaeffect/MediaEffectCrop.java
Java
apache-2.0
2,176
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper.internal; import com.google.common.collect.Iterables; import org.apache.lucene.document.BinaryDocValuesField; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.Term; import org.apache.lucene.queries.TermsQuery; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.MultiTermQuery; import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.RegexpQuery; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.lucene.BytesRefs; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.mapper.MergeMappingException; import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.RootMapper; import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.core.AbstractFieldMapper; import org.elasticsearch.index.query.QueryParseContext; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.elasticsearch.index.mapper.MapperBuilders.id; import static org.elasticsearch.index.mapper.core.TypeParsers.parseField; /** * */ public class IdFieldMapper extends AbstractFieldMapper implements RootMapper { public static final String NAME = "_id"; public static final String CONTENT_TYPE = "_id"; public static class Defaults extends AbstractFieldMapper.Defaults { public static final String NAME = IdFieldMapper.NAME; public static final String INDEX_NAME = IdFieldMapper.NAME; public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexOptions(IndexOptions.NONE); FIELD_TYPE.setStored(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.freeze(); } public static final String PATH = null; } public static class Builder extends AbstractFieldMapper.Builder<Builder, IdFieldMapper> { private String path = Defaults.PATH; public Builder() { super(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE)); indexName = Defaults.INDEX_NAME; } public Builder path(String path) { this.path = path; return builder; } // if we are indexed we use DOCS @Override protected IndexOptions getDefaultIndexOption() { return IndexOptions.DOCS; } @Override public IdFieldMapper build(BuilderContext context) { return new IdFieldMapper(name, indexName, boost, fieldType, docValues, path, fieldDataSettings, context.indexSettings()); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0)) { throw new MapperParsingException(NAME + " is not configurable"); } IdFieldMapper.Builder builder = id(); parseField(builder, builder.name, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("path")) { builder.path(fieldNode.toString()); iterator.remove(); } } return builder; } } private final String path; public IdFieldMapper(Settings indexSettings) { this(Defaults.NAME, Defaults.INDEX_NAME, Defaults.BOOST, idFieldType(indexSettings), null, Defaults.PATH, null, indexSettings); } protected IdFieldMapper(String name, String indexName, float boost, FieldType fieldType, Boolean docValues, String path, @Nullable Settings fieldDataSettings, Settings indexSettings) { super(new Names(name, indexName, indexName, name), boost, fieldType, docValues, Lucene.KEYWORD_ANALYZER, Lucene.KEYWORD_ANALYZER, null, null, fieldDataSettings, indexSettings); this.path = path; } private static FieldType idFieldType(Settings indexSettings) { FieldType fieldType = new FieldType(Defaults.FIELD_TYPE); boolean pre2x = Version.indexCreated(indexSettings).before(Version.V_2_0_0); if (pre2x && indexSettings.getAsBoolean("index.mapping._id.indexed", true) == false) { fieldType.setTokenized(false); } return fieldType; } public String path() { return this.path; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("string"); } @Override public String value(Object value) { if (value == null) { return null; } return value.toString(); } @Override public boolean useTermQueryWithQueryString() { return true; } @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { return super.termQuery(value, context); } final BytesRef[] uids = Uid.createUidsForTypesAndId(context.queryTypes(), value); if (uids.length == 1) { return new TermQuery(new Term(UidFieldMapper.NAME, uids[0])); } else { return new TermsQuery(UidFieldMapper.NAME, uids); } } @Override public Query termsQuery(List values, @Nullable QueryParseContext context) { if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { return super.termsQuery(values, context); } return new TermsQuery(UidFieldMapper.NAME, Uid.createUidsForTypesAndIds(context.queryTypes(), values)); } @Override public Query prefixQuery(Object value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { return super.prefixQuery(value, method, context); } Collection<String> queryTypes = context.queryTypes(); BooleanQuery query = new BooleanQuery(); for (String queryType : queryTypes) { PrefixQuery prefixQuery = new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(queryType, BytesRefs.toBytesRef(value)))); if (method != null) { prefixQuery.setRewriteMethod(method); } query.add(prefixQuery, BooleanClause.Occur.SHOULD); } return query; } @Override public Query regexpQuery(Object value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { if (fieldType.indexOptions() != IndexOptions.NONE || context == null) { return super.regexpQuery(value, flags, maxDeterminizedStates, method, context); } Collection<String> queryTypes = context.queryTypes(); if (queryTypes.size() == 1) { RegexpQuery regexpQuery = new RegexpQuery(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(Iterables.getFirst(queryTypes, null), BytesRefs.toBytesRef(value))), flags, maxDeterminizedStates); if (method != null) { regexpQuery.setRewriteMethod(method); } return regexpQuery; } BooleanQuery query = new BooleanQuery(); for (String queryType : queryTypes) { RegexpQuery regexpQuery = new RegexpQuery(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(queryType, BytesRefs.toBytesRef(value))), flags, maxDeterminizedStates); if (method != null) { regexpQuery.setRewriteMethod(method); } query.add(regexpQuery, BooleanClause.Occur.SHOULD); } return query; } @Override public void preParse(ParseContext context) throws IOException { if (context.sourceToParse().id() != null) { context.id(context.sourceToParse().id()); super.parse(context); } } @Override public void postParse(ParseContext context) throws IOException { if (context.id() == null && !context.sourceToParse().flyweight()) { throw new MapperParsingException("No id found while parsing the content source"); } // it either get built in the preParse phase, or get parsed... } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { XContentParser parser = context.parser(); if (parser.currentName() != null && parser.currentName().equals(Defaults.NAME) && parser.currentToken().isValue()) { // we are in the parse Phase String id = parser.text(); if (context.id() != null && !context.id().equals(id)) { throw new MapperParsingException("Provided id [" + context.id() + "] does not match the content one [" + id + "]"); } context.id(id); } // else we are in the pre/post parse phase if (fieldType.indexOptions() != IndexOptions.NONE || fieldType.stored()) { fields.add(new Field(names.indexName(), context.id(), fieldType)); } if (hasDocValues()) { fields.add(new BinaryDocValuesField(names.indexName(), new BytesRef(context.id()))); } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (indexCreatedBefore2x == false) { return builder; } boolean includeDefaults = params.paramAsBoolean("include_defaults", false); // if all are defaults, no sense to write it at all if (!includeDefaults && fieldType.stored() == Defaults.FIELD_TYPE.stored() && fieldType.indexOptions() == Defaults.FIELD_TYPE.indexOptions() && path == Defaults.PATH && customFieldDataSettings == null) { return builder; } builder.startObject(CONTENT_TYPE); if (includeDefaults || fieldType.stored() != Defaults.FIELD_TYPE.stored()) { builder.field("store", fieldType.stored()); } if (includeDefaults || fieldType.indexOptions() != Defaults.FIELD_TYPE.indexOptions()) { builder.field("index", indexTokenizeOptionToString(fieldType.indexOptions() != IndexOptions.NONE, fieldType.tokenized())); } if (includeDefaults || path != Defaults.PATH) { builder.field("path", path); } if (customFieldDataSettings != null) { builder.field("fielddata", (Map) customFieldDataSettings.getAsMap()); } else if (includeDefaults) { builder.field("fielddata", (Map) fieldDataType.getSettings().getAsMap()); } builder.endObject(); return builder; } @Override public void merge(Mapper mergeWith, MergeResult mergeResult) throws MergeMappingException { // do nothing here, no merging, but also no exception } }
Flipkart/elasticsearch
src/main/java/org/elasticsearch/index/mapper/internal/IdFieldMapper.java
Java
apache-2.0
13,278
/* * Copyright 2014-05-19 the original author or authors. */ package pl.com.softproject.altkom.hibernate.dao.hibernate; import pl.com.softproject.altkom.hibernate.model.Team; /** * * @author Adrian Lapierre <adrian@softproject.com.pl> */ public interface TeamDAO { Team load(Long id); void save(Team team); }
alapierre/hibernate-forms
core/src/main/java/pl/com/softproject/altkom/hibernate/dao/hibernate/TeamDAO.java
Java
apache-2.0
332
package net.sourceforge.staticmap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import net.sourceforge.staticmap.annotation.GuardedBy; import net.sourceforge.staticmap.annotation.ThreadSafe; /** * static map implementation class * * read codelist from file, database and make a static map object using loadData method * * should implement a loadData() method. * * @author kris.j * * @param <K, V> */ @ThreadSafe public abstract class StaticMapByTemplet<K, V> implements StaticMap<K, V> { protected final Map<K, V> staticMap = new ConcurrentHashMap<K, V>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(false /* fair */); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock(); @Override @GuardedBy("this") public final int cleanAndLoad() { this.writeLock.lock(); try { this.staticMap.clear(); return this.loadData(); } finally { this.writeLock.unlock(); } } @Override @GuardedBy("this") public final V get(K key) { this.readLock.lock(); try { return this.staticMap.get(key); } finally { this.readLock.unlock(); } } /** * read from datasource and set to Map object */ protected abstract int loadData(); }
krisjey/jStaticMap
src/java/net/sourceforge/staticmap/StaticMapByTemplet.java
Java
apache-2.0
1,468
/** * */ package org.minnal.instrument.entity.metadata.handler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.testng.Assert.assertEquals; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.minnal.instrument.entity.DummyModel; import org.minnal.instrument.entity.EntityKey; import org.minnal.instrument.entity.metadata.EntityMetaData; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author ganeshs * */ public class EntityKeyAnnotationHandlerTest { private EntityKeyAnnotationHandler handler; private EntityMetaData metaData; private EntityKey key; @BeforeMethod public void setup() { handler = new EntityKeyAnnotationHandler(); metaData = mock(EntityMetaData.class); key = mock(EntityKey.class); } @Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), EntityKey.class); } @Test public void shouldSetEntityKeyOnMetaDataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, key, method); verify(metaData).setEntityKey("code"); } @Test public void shouldSetEntityKeyOnMetaDataWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("code"); handler.handle(metaData, key, field); verify(metaData).setEntityKey("code"); } @Test(expectedExceptions=IllegalArgumentException.class, expectedExceptionsMessageRegExp="Method - readCode is not a getter") public void shouldThrowExceptionWhenMethodIsNotGetter() throws Exception { Method method = DummyModel.class.getDeclaredMethod("readCode"); handler.handle(metaData, key, method); } }
minnal/minnal
minnal-jaxrs/minnal-instrumentation-jaxrs/src/test/java/org/minnal/instrument/entity/metadata/handler/EntityKeyAnnotationHandlerTest.java
Java
apache-2.0
1,737
/* * Copyright 2004,2005 The Apache Software Foundation. * * 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.wso2.carbon.user.core.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import java.util.ArrayList; import java.util.List; public abstract class BundleCheckActivator implements BundleActivator { private static final Log log = LogFactory.getLog(BundleCheckActivator.class); private String DEPLOY_BEFORE = "DeployBefore"; public void start(final BundleContext bundleContext) throws Exception { /* * Check for the services that should be deployed before this if there * are any. * if there are such services we wait for such bundles to deploy and * gets the notification * through a service listener. */ // first check whether there are such services and they have already // deployed. String pendingBundleName = null; final List<Bundle> pendingBundles = new ArrayList<Bundle>(); for (Bundle bundle : bundleContext.getBundles()) { pendingBundleName = (String) bundle.getHeaders().get(DEPLOY_BEFORE); if ((pendingBundleName != null) && (pendingBundleName.equals(getName())) && (bundle.getState() != Bundle.ACTIVE)) { // i.e this bundle should be started before the user manager but // yet has not started pendingBundles.add(bundle); } } if (pendingBundles.isEmpty()) { startDeploy(bundleContext); } else { BundleListener bundleListener = new BundleListener() { public void bundleChanged(BundleEvent bundleEvent) { synchronized (pendingBundles) { if (bundleEvent.getType() == BundleEvent.STARTED) { pendingBundles.remove(bundleEvent.getBundle()); if (pendingBundles.isEmpty()) { // now start the user manager deployment bundleContext.removeBundleListener(this); try { startDeploy(bundleContext); } catch (Exception e) { log.error("Can not start the bundle ", e); } } } } } }; bundleContext.addBundleListener(bundleListener); } } public abstract void startDeploy(BundleContext bundleContext) throws Exception; public abstract String getName(); }
maheshika/carbon4-kernel
core/org.wso2.carbon.user.core/src/main/java/org/wso2/carbon/user/core/internal/BundleCheckActivator.java
Java
apache-2.0
2,922
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.util.graph; import com.intellij.openapi.util.Couple; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import consulo.util.collection.primitive.ints.IntStack; import com.intellij.util.containers.Stack; import consulo.util.collection.primitive.ints.IntList; import consulo.util.collection.primitive.ints.IntLists; import gnu.trove.TIntArrayList; import gnu.trove.TObjectIntHashMap; import javax.annotation.Nonnull; import java.util.*; /** * @author dsl, ven */ public class DFSTBuilder<Node> { private final OutboundSemiGraph<Node> myGraph; private final TObjectIntHashMap<Node> myNodeToNNumber; // node -> node number in topological order [0..size). Independent nodes are in reversed loading order (loading order is the graph.getNodes() order) private final Node[] myInvN; // node number in topological order [0..size) -> node private Couple<Node> myBackEdge; private Comparator<Node> myComparator; private final IntList mySCCs = IntLists.newArrayList(); // strongly connected component sizes private final TObjectIntHashMap<Node> myNodeToTNumber = new TObjectIntHashMap<Node>(); // node -> number in scc topological order. Independent scc are in reversed loading order private final Node[] myInvT; // number in (enumerate all nodes scc by scc) order -> node private final Node[] myAllNodes; public DFSTBuilder(@Nonnull Graph<Node> graph) { this((OutboundSemiGraph<Node>)graph); } @SuppressWarnings("unchecked") public DFSTBuilder(@Nonnull OutboundSemiGraph<Node> graph) { myAllNodes = (Node[])graph.getNodes().toArray(); myGraph = graph; int size = graph.getNodes().size(); myNodeToNNumber = new TObjectIntHashMap<Node>(size * 2, 0.5f); myInvN = (Node[])new Object[size]; myInvT = (Node[])new Object[size]; new Tarjan().build(); } /** * Tarjan's strongly connected components search algorithm * (<a href="https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm">Wikipedia article</a>).<br> * This implementation differs from the canonical one above by:<br> * <ul> * <li>being non-recursive</li> * <li>also computing a topological order during the same single pass</li> * </ul> */ private class Tarjan { private final int[] lowLink = new int[myInvN.length]; private final int[] index = new int[myInvN.length]; private final IntStack nodesOnStack = new IntStack(); private final boolean[] isOnStack = new boolean[index.length]; private class Frame { public Frame(int nodeI) { this.nodeI = nodeI; Iterator<Node> outNodes = myGraph.getOut(myAllNodes[nodeI]); TIntArrayList list = new TIntArrayList(); while (outNodes.hasNext()) { Node node = outNodes.next(); list.add(nodeIndex.get(node)); } out = list.toNativeArray(); } private final int nodeI; private final int[] out; private int nextUnexploredIndex; @Override public String toString() { StringBuilder o = new StringBuilder(); o.append(myAllNodes[nodeI]).append(" -> ["); for (int id : out) o.append(myAllNodes[id]).append(", "); return o.append(']').toString(); } } private final Stack<Frame> frames = new Stack<Frame>(); // recursion stack private final TObjectIntHashMap<Node> nodeIndex = new TObjectIntHashMap<Node>(); private int dfsIndex; private int sccsSizeCombined; private final TIntArrayList topo = new TIntArrayList(index.length); // nodes in reverse topological order private void build() { Arrays.fill(index, -1); for (int i = 0; i < myAllNodes.length; i++) { Node node = myAllNodes[i]; nodeIndex.put(node, i); } for (int i = 0; i < index.length; i++) { if (index[i] == -1) { frames.push(new Frame(i)); List<List<Node>> sccs = new ArrayList<List<Node>>(); strongConnect(sccs); for (List<Node> scc : sccs) { int sccSize = scc.size(); mySCCs.add(sccSize); int sccBase = index.length - sccsSizeCombined - sccSize; // root node should be first in scc for some reason Node rootNode = myAllNodes[i]; int rIndex = scc.indexOf(rootNode); if (rIndex != -1) { ContainerUtil.swapElements(scc, rIndex, 0); } for (int j = 0; j < scc.size(); j++) { Node sccNode = scc.get(j); int tIndex = sccBase + j; myInvT[tIndex] = sccNode; myNodeToTNumber.put(sccNode, tIndex); } sccsSizeCombined += sccSize; } } } for (int i = 0; i < topo.size(); i++) { int nodeI = topo.get(i); Node node = myAllNodes[nodeI]; myNodeToNNumber.put(node, index.length - 1 - i); myInvN[index.length - 1 - i] = node; } IntLists.reverse(mySCCs); // have to place SCCs in topological order too } private void strongConnect(@Nonnull List<List<Node>> sccs) { int successor = -1; nextNode: while (!frames.isEmpty()) { Frame pair = frames.peek(); int i = pair.nodeI; // we have returned to the node if (index[i] == -1) { // actually we visit node first time, prepare index[i] = dfsIndex; lowLink[i] = dfsIndex; dfsIndex++; nodesOnStack.push(i); isOnStack[i] = true; } if (ArrayUtil.indexOf(pair.out, successor) != -1) { lowLink[i] = Math.min(lowLink[i], lowLink[successor]); } successor = i; // if unexplored children left, dfs there while (pair.nextUnexploredIndex < pair.out.length) { int nextI = pair.out[pair.nextUnexploredIndex++]; if (index[nextI] == -1) { frames.push(new Frame(nextI)); continue nextNode; } if (isOnStack[nextI]) { lowLink[i] = Math.min(lowLink[i], index[nextI]); if (myBackEdge == null) { myBackEdge = Couple.of(myAllNodes[nextI], myAllNodes[i]); } } } frames.pop(); topo.add(i); // we are really back, pop a scc if (lowLink[i] == index[i]) { // found yer List<Node> scc = new ArrayList<Node>(); int pushedI; do { pushedI = nodesOnStack.pop(); Node pushed = myAllNodes[pushedI]; isOnStack[pushedI] = false; scc.add(pushed); } while (pushedI != i); sccs.add(scc); } } } } @Nonnull public Comparator<Node> comparator() { if (myComparator == null) { final TObjectIntHashMap<Node> map = isAcyclic() ? myNodeToNNumber : myNodeToTNumber; myComparator = new Comparator<Node>() { @Override public int compare(@Nonnull Node t, @Nonnull Node t1) { return map.get(t) - map.get(t1); } }; } return myComparator; } public Couple<Node> getCircularDependency() { return myBackEdge; } public boolean isAcyclic() { return getCircularDependency() == null; } @Nonnull public Node getNodeByNNumber(final int n) { return myInvN[n]; } @Nonnull public Node getNodeByTNumber(final int n) { return myInvT[n]; } /** * @return the list containing the number of nodes in strongly connected components. * Respective nodes could be obtained via {@link #getNodeByTNumber(int)}. */ @Nonnull public IntList getSCCs() { return mySCCs; } @Nonnull public Collection<Collection<Node>> getComponents() { final IntList componentSizes = getSCCs(); if (componentSizes.isEmpty()) return List.of(); return new MyCollection<Collection<Node>>(componentSizes.size()) { @Nonnull @Override public Iterator<Collection<Node>> iterator() { return new MyIterator<Collection<Node>>(componentSizes.size()) { private int offset; @Override protected Collection<Node> get(int i) { final int cSize = componentSizes.get(i); final int cOffset = offset; if (cSize == 0) return List.of(); offset += cSize; return new MyCollection<Node>(cSize) { @Nonnull @Override public Iterator<Node> iterator() { return new MyIterator<Node>(cSize) { @Override public Node get(int i) { return getNodeByTNumber(cOffset + i); } }; } }; } }; } }; } private abstract static class MyCollection<T> extends AbstractCollection<T> { private final int size; protected MyCollection(int size) { this.size = size; } @Override public int size() { return size; } } private abstract static class MyIterator<T> implements Iterator<T> { private final int size; private int i; protected MyIterator(int size) { this.size = size; } @Override public boolean hasNext() { return i < size; } @Override public T next() { if (i == size) throw new NoSuchElementException(); return get(i++); } protected abstract T get(int i); @Override public void remove() { throw new UnsupportedOperationException(); } } @Nonnull public List<Node> getSortedNodes() { List<Node> result = new ArrayList<Node>(myGraph.getNodes()); Collections.sort(result, comparator()); return result; } }
consulo/consulo
modules/base/util-deprecated/src/main/java/com/intellij/util/graph/DFSTBuilder.java
Java
apache-2.0
10,376
package com.foxty.jmon.pojo; import java.util.ArrayList; import java.util.List; public class Graph<T> { private String name; private List<String> categories; private List<Serial<T>> serials = new ArrayList<Serial<T>>(); public Graph(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setCategories(List<String> cate) { this.categories = cate; } public List<String> getCategories() { return categories; } public void addSerial(String name, List<T> list) { Serial<T> serial = new Serial<T>(name, list); serials.add(serial); } public List<Serial<T>> getSerials() { return serials; } public static class Serial<T> { private String name; private List<T> data; public Serial(String name, List<T> data) { this.name = name; this.data = data; } public String getName() { return name; } public List<T> getData() { return data; } } }
foxty/jmon
src/main/java/com/foxty/jmon/pojo/Graph.java
Java
apache-2.0
992
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.vfs2.provider; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.vfs2.util.RandomAccessMode; /** * Implements the part usable for all stream base random access implementations. * * @author <a href="http://commons.apache.org/vfs/team-list.html">Commons VFS team</a> * @version $Revision$ $Date$ */ public abstract class AbstractRandomAccessStreamContent extends AbstractRandomAccessContent { protected AbstractRandomAccessStreamContent(final RandomAccessMode mode) { super(mode); } protected abstract DataInputStream getDataInputStream() throws IOException; public byte readByte() throws IOException { byte data = getDataInputStream().readByte(); return data; } public char readChar() throws IOException { char data = getDataInputStream().readChar(); return data; } public double readDouble() throws IOException { double data = getDataInputStream().readDouble(); return data; } public float readFloat() throws IOException { float data = getDataInputStream().readFloat(); return data; } public int readInt() throws IOException { int data = getDataInputStream().readInt(); return data; } public int readUnsignedByte() throws IOException { int data = getDataInputStream().readUnsignedByte(); return data; } public int readUnsignedShort() throws IOException { int data = getDataInputStream().readUnsignedShort(); return data; } public long readLong() throws IOException { long data = getDataInputStream().readLong(); return data; } public short readShort() throws IOException { short data = getDataInputStream().readShort(); return data; } public boolean readBoolean() throws IOException { boolean data = getDataInputStream().readBoolean(); return data; } public int skipBytes(int n) throws IOException { int data = getDataInputStream().skipBytes(n); return data; } public void readFully(byte[] b) throws IOException { getDataInputStream().readFully(b); } public void readFully(byte[] b, int off, int len) throws IOException { getDataInputStream().readFully(b, off, len); } public String readUTF() throws IOException { String data = getDataInputStream().readUTF(); return data; } public InputStream getInputStream() throws IOException { return getDataInputStream(); } }
easel/commons-vfs
core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessStreamContent.java
Java
apache-2.0
3,503
package com.sequenceiq.cloudbreak.domain.view; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status; import com.sequenceiq.cloudbreak.domain.ProvisionEntity; import com.sequenceiq.cloudbreak.domain.converter.StatusConverter; @Entity @Table(name = "stackstatus") public class StackStatusView implements ProvisionEntity { @Id private Long id; @Convert(converter = StatusConverter.class) private Status status; public Long getId() { return id; } public Status getStatus() { return status; } public void setId(Long id) { this.id = id; } public void setStatus(Status status) { this.status = status; } }
hortonworks/cloudbreak
core-model/src/main/java/com/sequenceiq/cloudbreak/domain/view/StackStatusView.java
Java
apache-2.0
824
package cn.nec.nlc.example.activitytest17; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; public class ImagePickActivity extends Activity { private static final int REQUEST_CODE = 1; private Bitmap bitmap; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.result); } public void pickImage(View view) { Intent intent = new Intent(); // ACTION_GET_CONTENT with MIME type */* and category CATEGORY_OPENABLE // -- Display all pickers for data that can be opened with // ContentResolver.openInputStream(), allowing the user to pick one of // them and then some data inside of it and returning the resulting URI // to the caller. This can be used, for example, in an e-mail application // to allow the user to pick some data to include as an attachment. intent.setType("image/*"); // set an explicit MIME data type. intent.setAction(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { InputStream stream = null; if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) try { // recycle unused bitmaps if (bitmap != null) bitmap.recycle(); stream = getContentResolver().openInputStream(data.getData()); bitmap = BitmapFactory.decodeStream(stream); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
jamescfli/GitRepository
ActivityTest17PickImageWithIntent/src/cn/nec/nlc/example/activitytest17/ImagePickActivity.java
Java
apache-2.0
2,119
package com.example.jingbin.cloudreader.ui.gank; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.jingbin.cloudreader.R; import com.example.jingbin.cloudreader.app.RxCodeConstants; import com.example.jingbin.cloudreader.databinding.FragmentContentBinding; import com.example.jingbin.cloudreader.ui.gank.child.AndroidFragment; import com.example.jingbin.cloudreader.ui.gank.child.CustomFragment; import com.example.jingbin.cloudreader.ui.gank.child.GankHomeFragment; import com.example.jingbin.cloudreader.ui.gank.child.WelfareFragment; import com.example.jingbin.cloudreader.view.MyFragmentPagerAdapter; import java.util.ArrayList; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import me.jingbin.bymvvm.base.BaseFragment; import me.jingbin.bymvvm.base.NoViewModel; import me.jingbin.bymvvm.rxbus.RxBus; /** * Created by jingbin on 16/11/21. * 展示干货的页面 */ public class GankFragment extends BaseFragment<NoViewModel, FragmentContentBinding> { private final ArrayList<String> mTitleList = new ArrayList<>(4); private final ArrayList<Fragment> mFragments = new ArrayList<>(4); private boolean mIsFirst = true; @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); if (mIsFirst) { showLoading(); bindingView.vpGank.postDelayed(() -> { initFragmentList(); MyFragmentPagerAdapter myAdapter = new MyFragmentPagerAdapter(getChildFragmentManager(), mFragments, mTitleList); bindingView.vpGank.setAdapter(myAdapter); myAdapter.notifyDataSetChanged(); // 左右预加载页面的个数 bindingView.vpGank.setOffscreenPageLimit(3); bindingView.tabGank.setupWithViewPager(bindingView.vpGank); // item点击跳转 initRxBus(); showContentView(); }, 120); mIsFirst = false; } } @Override public int setContent() { return R.layout.fragment_content; } private void initFragmentList() { mTitleList.clear(); mTitleList.add("干货首页"); mTitleList.add("福利"); mTitleList.add("订制"); mTitleList.add("大安卓"); mFragments.add(new GankHomeFragment()); mFragments.add(new WelfareFragment()); mFragments.add(new CustomFragment()); mFragments.add(AndroidFragment.newInstance("Android")); } /** * 每日推荐点击"更多"跳转 */ private void initRxBus() { Disposable subscribe = RxBus.getDefault().toObservable(RxCodeConstants.JUMP_TYPE, Integer.class) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { if (integer == 0) { bindingView.vpGank.setCurrentItem(3); } else if (integer == 1) { bindingView.vpGank.setCurrentItem(1); } else if (integer == 2) { bindingView.vpGank.setCurrentItem(2); } } }); addSubscription(subscribe); } }
youlookwhat/CloudReader
app/src/main/java/com/example/jingbin/cloudreader/ui/gank/GankFragment.java
Java
apache-2.0
3,521
package com.sakebook.android.library.multilinedividersample.grid; import android.view.View; import android.widget.ImageView; import com.sakebook.android.library.multilinedevider.divider.GridDivider; import com.sakebook.android.library.multilinedividersample.R; import com.sakebook.android.library.multilinedividersample.multiline.Number; /** * Created by sakemotoshinya on 2017/05/21. */ public class GridImageViewHolder extends ViewHolder<Number> implements GridDivider { private ImageView imageView; public GridImageViewHolder(View itemView) { super(itemView); imageView = (ImageView) itemView.findViewById(R.id.image); } @Override void setData(Number number) { switch (number) { case EVEN: imageView.setImageResource(R.drawable.cat2); break; case ODD: imageView.setImageResource(R.drawable.cat3); break; case PRIME: imageView.setImageResource(R.drawable.cat1); break; } } @Override public int getPadding() { return itemView.getContext().getResources().getDimensionPixelSize(R.dimen.tiny_margin); } @Override public boolean getFullBleed() { return false; } }
sakebook/MultiLineDivider
sample/src/main/java/com/sakebook/android/library/multilinedividersample/grid/GridImageViewHolder.java
Java
apache-2.0
1,299
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.apm.collector.storage.h2.dao.armp; import org.apache.skywalking.apm.collector.client.h2.H2Client; import org.apache.skywalking.apm.collector.core.storage.TimePyramid; import org.apache.skywalking.apm.collector.core.util.Const; import org.apache.skywalking.apm.collector.storage.dao.armp.IApplicationReferenceDayMetricPersistenceDAO; import org.apache.skywalking.apm.collector.storage.h2.base.define.H2SqlEntity; import org.apache.skywalking.apm.collector.storage.table.application.ApplicationReferenceMetric; import org.apache.skywalking.apm.collector.storage.table.application.ApplicationReferenceMetricTable; /** * @author peng-yongsheng */ public class ApplicationReferenceDayMetricH2PersistenceDAO extends AbstractApplicationReferenceMetricH2PersistenceDAO implements IApplicationReferenceDayMetricPersistenceDAO<H2SqlEntity, H2SqlEntity, ApplicationReferenceMetric> { public ApplicationReferenceDayMetricH2PersistenceDAO(H2Client client) { super(client); } @Override protected String tableName() { return ApplicationReferenceMetricTable.TABLE + Const.ID_SPLIT + TimePyramid.Day.getName(); } }
hanahmily/sky-walking
apm-collector/apm-collector-storage/collector-storage-h2-provider/src/main/java/org/apache/skywalking/apm/collector/storage/h2/dao/armp/ApplicationReferenceDayMetricH2PersistenceDAO.java
Java
apache-2.0
1,972
package org.jetbrains.teamcity.wbb; import jetbrains.buildServer.serverSide.*; import jetbrains.buildServer.serverSide.impl.BuildQueueImpl; import jetbrains.buildServer.vcs.SVcsModification; import jetbrains.buildServer.vcs.VcsModificationHistory; import org.jetbrains.annotations.NotNull; import java.util.SortedSet; /** * @author Leonid Bushuev from JetBrains **/ public class WbbBuildStarter { @NotNull private final BuildCustomizerFactory myBuildCustomizerFactory; @NotNull private final VcsModificationHistory myModificationHistory; public WbbBuildStarter(@NotNull final BuildCustomizerFactory buildCustomizerFactory, @NotNull final VcsModificationHistory modificationHistory) { myBuildCustomizerFactory = buildCustomizerFactory; myModificationHistory = modificationHistory; } void startIteration(@NotNull final Situation situation, @NotNull final SBuildType bt) { final SortedSet<Long> suggestions = Logic.suggestCheckPoints(situation); if (suggestions == null || suggestions.isEmpty()) return; enqueue(situation, bt, suggestions); } void enqueue(@NotNull final Situation situation, @NotNull final SBuildType bt, @NotNull final SortedSet<Long> revisionsIds) { for (Long revisionId : revisionsIds) { enqueue(bt, revisionId); situation.setValid(false); } } void enqueue(@NotNull final SBuildType bt, @NotNull final Long revisionId) { final SVcsModification modification = myModificationHistory.findChangeById(revisionId); if (modification == null) return; final BuildCustomizerEx bc = (BuildCustomizerEx) myBuildCustomizerFactory.createBuildCustomizer(bt, null); //bc.setDesiredBranchName(???); bc.setChangesUpTo(modification); //bc.setFreezeSettings(true); //bc.setStickToRevisions(true); final BuildPromotion promotion = bc.createPromotion(); TriggeredByBuilder tbb = new TriggeredByBuilder(); tbb.addParameter(BuildQueueImpl.TRIGGERED_BY_QUEUE_MERGING_ENABLED_PARAM, "false"); promotion.addToQueue(tbb.toString()); } }
leo-from-spb/teamcity-wbb
server/src/org/jetbrains/teamcity/wbb/WbbBuildStarter.java
Java
apache-2.0
2,144
package edu.scu.smurali.parkonthego; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
parkonthego/parkonthegoAndroidApp
app/src/test/java/edu/scu/smurali/parkonthego/ExampleUnitTest.java
Java
apache-2.0
320
package com.lachesis.mnisqm.module.trainExamManage.domain; import java.util.Date; public class TemAttendanceManage { private Long seqId; private String trainCode; private String deptCode; private String userCode; private String userName; private Integer attendanceSituation; private String remark; private Date createTime; private String createPerson; private Date updateTime; private String updatePerson; public Long getSeqId() { return seqId; } public void setSeqId(Long seqId) { this.seqId = seqId; } public String getTrainCode() { return trainCode; } public void setTrainCode(String trainCode) { this.trainCode = trainCode; } public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getAttendanceSituation() { return attendanceSituation; } public void setAttendanceSituation(Integer attendanceSituation) { this.attendanceSituation = attendanceSituation; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreatePerson() { return createPerson; } public void setCreatePerson(String createPerson) { this.createPerson = createPerson; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdatePerson() { return updatePerson; } public void setUpdatePerson(String updatePerson) { this.updatePerson = updatePerson; } }
gavin2lee/incubator
mnisqm/mnisqm-services/src/main/java/com/lachesis/mnisqm/module/trainExamManage/domain/TemAttendanceManage.java
Java
apache-2.0
2,261
package com.bytebeats.codelab.serialization.kryo; import com.bytebeats.codelab.serialization.model.Author; import com.bytebeats.codelab.serialization.util.IoUtils; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.serializers.CollectionSerializer; import com.esotericsoftware.kryo.serializers.FieldSerializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; public class KryoFieldSerializerDemo { public static void main(String[] args) { Author author = new Author(); author.setName("Ricky"); author.setGender("male"); author.setAge(26); author.setDesc("No zuo no die!"); ArrayList<String> tag = new ArrayList<>(); tag.add("IT"); tag.add("屌丝"); author.setTag(tag); System.out.println(author); Kryo kryo = new Kryo(); FieldSerializer<Author> someClassSerializer = new FieldSerializer<Author>(kryo, Author.class); CollectionSerializer listSerializer = new CollectionSerializer(); listSerializer.setElementClass(String.class, kryo.getSerializer(String.class)); listSerializer.setElementsCanBeNull(false); someClassSerializer.getField("tag").setClass(ArrayList.class, listSerializer); kryo.register(Author.class, someClassSerializer); KryoFieldSerializerDemo demo = new KryoFieldSerializerDemo(); byte[] data = demo.serialize(kryo, author); System.out.println(data.length); System.out.println(demo.deserialize(kryo, data)); } public byte[] serialize(Kryo kryo, Author author) { // Write Obj to File Output output = null; ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); output = new Output(baos); kryo.writeObject(output, author); output.flush(); return baos.toByteArray(); } catch (KryoException e) { e.printStackTrace(); } finally { IoUtils.closeQuietly(output); IoUtils.closeQuietly(baos); } return null; } public Author deserialize(Kryo kryo, byte[] data) { // Read Obj from File Input input = null; try { input = new Input(new ByteArrayInputStream(data)); return kryo.readObject(input, Author.class); } catch (KryoException e) { e.printStackTrace(); } finally { IoUtils.closeQuietly(input); } return null; } }
FBing/cglib-demo
serialization-sample/src/main/java/com/bytebeats/codelab/serialization/kryo/KryoFieldSerializerDemo.java
Java
apache-2.0
2,451
package com.znet.reconnaissance.server.service.websockets; import java.util.List; import java.util.Map; import com.znet.reconnaissance.model.Client; import com.znet.reconnaissance.model.Registration; import com.znet.reconnaissance.server.service.Service; public class WSService extends Service { private Client<?> client; private Registration registration; public WSService(Client<?> client, Registration registration) { super(client.getId()); this.client = client; this.registration = registration; } @Override public void disconnect() { this.client.disconnect(); } @Override public boolean heartbeat() { if (!isConnected()) { return false; } return this.client.heartbeat(); } @Override public String getTree() { return this.registration.getTree(); } @Override public String getName() { return this.registration.getName(); } @Override public String getType() { return this.registration.getType(); } @Override public List<String> getProfiles() { return this.registration.getProfiles(); } @Override public String getHostname() { return this.registration.getHostname(); } @Override public String getEnvironment() { return this.registration.getEnvironment(); } @Override public Map<String, String> getMetadata() { return this.registration.getMetadata(); } @Override public boolean isConnected() { return this.client != null && this.client.isConnected(); } }
nicholashagen/Reconnaissance
server/src/main/java/com/znet/reconnaissance/server/service/websockets/WSService.java
Java
apache-2.0
1,442
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spreadcoinj.net; import java.io.IOException; /** * A target to which messages can be written/connection can be closed */ public interface MessageWriteTarget { /** * Writes the given bytes to the remote server. */ void writeBytes(byte[] message) throws IOException; /** * Closes the connection to the server, triggering the {@link StreamParser#connectionClosed()} * event on the network-handling thread where all callbacks occur. */ void closeConnection(); }
bitbandi/spreadcoinj
core/src/main/java/org/spreadcoinj/net/MessageWriteTarget.java
Java
apache-2.0
1,110
/******************************************************************************* * Copyright (c) 2006-2010 eBay Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 *******************************************************************************/ package org.ebayopensource.turmeric.runtime.tests.common.sif.error; import org.ebayopensource.turmeric.runtime.common.exceptions.ServiceInvocationException; import org.ebayopensource.turmeric.runtime.errorlibrary.ErrorDataCollection; import org.ebayopensource.turmeric.runtime.tests.common.AbstractTurmericTestCase; import org.ebayopensource.turmeric.runtime.tests.common.junit.NeedsConfig; import org.ebayopensource.turmeric.runtime.tests.common.sif.tester.AssertErrorData; import org.ebayopensource.turmeric.runtime.tests.common.sif.tester.ServicePayloadExecutor; import org.ebayopensource.turmeric.runtime.tests.service1.sample.Test1Constants; import org.ebayopensource.turmeric.runtime.tests.service1.sample.errors.TestServerErrorTypes; import org.ebayopensource.turmeric.runtime.tests.service1.sample.types1.CustomErrorMessage; import org.ebayopensource.turmeric.common.v1.types.ErrorMessage; import org.junit.Rule; import org.junit.Test; public class LocalCustomError1Test extends AbstractTurmericTestCase { @Rule public NeedsConfig needsconfig = new NeedsConfig("config"); private ServicePayloadExecutor createExecutor() throws Exception { // Setup Request ServicePayloadExecutor test = new ServicePayloadExecutor(); test.setServiceNameDefault(); test.setClientName("local"); test.setUseLocalService(); // Use known working formats test.addAllPayloadFormats(); // Test all modes test.addAllTestModes(); test.setOperationName("customError1"); test.setUseInParams(false); test.addTransportHeader("TEST_CALL_HEADER", "MyValue"); return test; } @Test public void test1Exception() throws Exception { ServicePayloadExecutor test = createExecutor(); test.addTransportHeader(Test1Constants.TR_HDR_TEST1_EXCEPTION, "true"); test.addTransportHeader(Test1Constants.TR_HDR_TEST1_HARMLESS_EXCEPTION, "true"); AssertErrorData error = new AssertErrorData(); error.needsCause(ServiceInvocationException.class); error.needsErrorDataSource(CustomErrorMessage.class); error.needsExceptionText("Test1Exception: Our test1 exception"); error.optionalErrorDataId(ErrorDataCollection.svc_rt_application_internal_error); test.setAssertException(error); test.doCalls(); } @SuppressWarnings("deprecation") @Test public void test1ServiceException() throws Exception { ServicePayloadExecutor test = createExecutor(); test.addTransportHeader(Test1Constants.TR_HDR_TEST1_SERVICE_EXCEPTION, "true"); AssertErrorData error = new AssertErrorData(); error.needsCause(ServiceInvocationException.class); error.needsErrorDataSource(CustomErrorMessage.class); error.needsExceptionText("with data my_program_data"); error.optionalErrorDataId(TestServerErrorTypes.TEST1_SERVICE_EXCEPTION.getId()); test.setAssertException(error); test.doCalls(); } @Test public void errorMapperException() throws Exception { ServicePayloadExecutor test = createExecutor(); test.addTransportHeader(Test1Constants.TR_HDR_TEST1_EXCEPTION, "true"); test.addTransportHeader(Test1Constants.TR_HDR_ERROR_MAPPER_EXCEPTION, "true"); AssertErrorData error = new AssertErrorData(); error.needsCause(ServiceInvocationException.class); error.needsExceptionText("java.lang.RuntimeException: Test error mapper exception"); error.needsErrorDataSource(ErrorMessage.class); error.needsErrorDataId(ErrorDataCollection.svc_transport_unserializable_message); test.setAssertException(error); test.doCalls(); } @Test public void testHandlerException() throws Exception { ServicePayloadExecutor test = createExecutor(); test.doCalls(); } }
vthangathurai/SOA-Runtime
integration-tests/Test1ServiceConsumer/src/test/java/org/ebayopensource/turmeric/runtime/tests/common/sif/error/LocalCustomError1Test.java
Java
apache-2.0
4,361
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * Copyright (C) 2011-2012 Eugene Fradkin (eugene.fradkin@gmail.com) * * 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.jkiss.dbeaver.ui.dialogs.connection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.model.DBIcon; import org.jkiss.dbeaver.model.app.DBPProject; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.internal.UIConnectionMessages; import java.util.List; /** * ProjectSelectorPanel */ public class ProjectSelectorPanel { private DBPProject selectedProject; public ProjectSelectorPanel(@NotNull Composite parent, @Nullable DBPProject activeProject, int style) { this.selectedProject = activeProject; final List<DBPProject> projects = DBWorkbench.getPlatform().getWorkspace().getProjects(); if (projects.size() == 1) { if (selectedProject == null) { selectedProject = projects.get(0); } } else if (projects.size() > 1) { boolean showIcon = (style & SWT.ICON) != 0; Composite projectGroup = UIUtils.createComposite(parent, showIcon ? 3 : 2); projectGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); if (showIcon) { new Label(projectGroup, SWT.NONE).setImage(DBeaverIcons.getImage(DBIcon.PROJECT)); } UIUtils.createControlLabel(projectGroup, UIConnectionMessages.dialog_connection_driver_project); final Combo projectCombo = new Combo(projectGroup, SWT.DROP_DOWN | SWT.READ_ONLY); projectCombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); for (DBPProject project : projects) { projectCombo.add(project.getName()); } if (selectedProject == null) { selectedProject = DBWorkbench.getPlatform().getWorkspace().getActiveProject(); if (!projects.contains(selectedProject)) { selectedProject = projects.get(0); } } projectCombo.setText(selectedProject.getName()); projectCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { selectedProject = projects.get(projectCombo.getSelectionIndex()); onProjectChange(); } }); if (projects.size() < 2) { //projectCombo.setEnabled(false); } } } protected void onProjectChange() { } public DBPProject getSelectedProject() { return selectedProject; } }
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ui.editors.connection/src/org/jkiss/dbeaver/ui/dialogs/connection/ProjectSelectorPanel.java
Java
apache-2.0
3,665
package droolsbook.sampleApplication.repository; import java.util.List; import droolsbook.bank.model.Customer; public interface CustomerRepository { Customer findCustomerByUuid(String customerUuid); List<Customer> findAllCustomers(); List<Customer> findCustomerByName(String firstName, String lastName); void addCustomer(final Customer customer); Customer updateCustomer(final Customer customer); }
zhwbqd/drools
sampleApplication/src/main/java/droolsbook/sampleApplication/repository/CustomerRepository.java
Java
apache-2.0
434
package com.github.vvv1559.algorithms.leetcode.strings; import com.github.vvv1559.algorithms.annotations.Difficulty; import com.github.vvv1559.algorithms.annotations.Level; /* * Original text: https://leetcode.com/problems/add-binary/description/ * * Given two binary strings, return their sum (also a binary string). * * For example, * a = "11" * b = "1" * Return "100". * */ @Difficulty(Level.EASY) class AddBinary { String addBinary(String a, String b) { int aIndex = a.length(); if (aIndex == 0) return b; int bIndex = b.length(); if (bIndex == 0) return a; char[] result = new char[Math.max(aIndex, bIndex) + 1]; for (int i = result.length - 2; i >= 0; i--) { int aInt = (--aIndex >= 0 ? a.charAt(aIndex) - '0' : 0); int bInt = (--bIndex >= 0 ? b.charAt(bIndex) - '0' : 0); int sum = aInt + bInt + result[i + 1]; result[i + 1] = (char) (sum % 2 + '0'); result[i] = (char) (sum / 2); } if (result[0] == 1) { result[0] += '0'; return new String(result); } else { return new String(result, 1, result.length - 1); } } }
vvv1559/algorytms-and-data-structures
leetcode/src/main/java/com/github/vvv1559/algorithms/leetcode/strings/AddBinary.java
Java
apache-2.0
1,221
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.ChainExtension; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; @RunWith(MockitoJUnitRunner.class) public class DefaultDynamoDbEnhancedClientTest { @Mock private DynamoDbClient mockDynamoDbClient; @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension2; @Mock private TableSchema<Object> mockTableSchema; private DefaultDynamoDbEnhancedClient dynamoDbEnhancedClient; @Before public void initializeClient() { this.dynamoDbEnhancedClient = DefaultDynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .extensions(mockDynamoDbEnhancedClientExtension) .build(); } @Test public void table() { DefaultDynamoDbTable<Object> mappedTable = dynamoDbEnhancedClient.table("table-name", mockTableSchema); assertThat(mappedTable.dynamoDbClient(), is(mockDynamoDbClient)); assertThat(mappedTable.mapperExtension(), is(mockDynamoDbEnhancedClientExtension)); assertThat(mappedTable.tableSchema(), is(mockTableSchema)); assertThat(mappedTable.tableName(), is("table-name")); } @Test public void builder_minimal() { DefaultDynamoDbEnhancedClient builtObject = DefaultDynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .build(); assertThat(builtObject.dynamoDbClient(), is(mockDynamoDbClient)); assertThat(builtObject.mapperExtension(), instanceOf(VersionedRecordExtension.class)); } @Test public void builder_maximal() { DefaultDynamoDbEnhancedClient builtObject = DefaultDynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .extensions(mockDynamoDbEnhancedClientExtension) .build(); assertThat(builtObject.dynamoDbClient(), is(mockDynamoDbClient)); assertThat(builtObject.mapperExtension(), is(mockDynamoDbEnhancedClientExtension)); } @Test public void builder_multipleExtensions_varargs() { DefaultDynamoDbEnhancedClient builtObject = DefaultDynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .extensions(mockDynamoDbEnhancedClientExtension, mockDynamoDbEnhancedClientExtension2) .build(); assertThat(builtObject.dynamoDbClient(), is(mockDynamoDbClient)); assertThat(builtObject.mapperExtension(), instanceOf(ChainExtension.class)); } @Test public void builder_multipleExtensions_list() { DefaultDynamoDbEnhancedClient builtObject = DefaultDynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .extensions(Arrays.asList(mockDynamoDbEnhancedClientExtension, mockDynamoDbEnhancedClientExtension2)) .build(); assertThat(builtObject.dynamoDbClient(), is(mockDynamoDbClient)); assertThat(builtObject.mapperExtension(), instanceOf(ChainExtension.class)); } @Test public void toBuilder() { DefaultDynamoDbEnhancedClient copiedObject = dynamoDbEnhancedClient.toBuilder().build(); assertThat(copiedObject, is(dynamoDbEnhancedClient)); } }
aws/aws-sdk-java-v2
services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbEnhancedClientTest.java
Java
apache-2.0
5,251
package jp.hcrisis.assistant.disaster; import org.postgis.PGgeometry; import java.io.*; import java.sql.*; import java.util.LinkedList; /** * Created by manabu on 2016/10/14. */ public class EarthquakeDamageDbSet { private static String url; private static String usr; private static String pwd; public EarthquakeDamageDbSet(File dir, String code) { // JDBCドライバのロード this.url = "jdbc:postgresql://gis.h-crisis.jp/hcrisis"; this.usr = "hcrisis"; this.pwd = "niph614"; File municipalitiesFile = new File(dir.getPath() + "/" + code + "_municipalities_base_02_damage.csv"); File shelterFile = new File(dir.getPath() + "/" + code + "_shelter_01_evacuee.csv"); createEventTables(code); //addShelters2Table(municipalitiesFile, code); addShelters2TableCustom(shelterFile, code); //updateEstimateInfoShelter2Table(shelterFile, code); } public static void createEventTables(String eventCode) { try { Class.forName("org.postgresql.Driver"); // データベース接続 System.out.println("Connecting to " + url); Connection db = DriverManager.getConnection(url, usr, pwd); Statement st = db.createStatement(); st.execute("CREATE TABLE event_shelter_" + eventCode + " AS SELECT * FROM event_shelter_template"); //避難所テンプレートデータベースの複製 // データベース切断 st.close(); db.close(); // エラー処理 } catch (Exception ex) { ex.printStackTrace(); } } public static void addShelters2Table(File file, String eventCode) { try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Shift_JIS"))) { // JDBCドライバのロード Class.forName("org.postgresql.Driver"); // データベース接続 System.out.println("Connecting to " + url); Connection db = DriverManager.getConnection(url, usr, pwd); Statement st = db.createStatement(); ResultSet rs; // 被災自治体の読み込み String line = br.readLine(); // 1行目は見出し int i = 0; while((line = br.readLine())!=null) { String pair[] = line.split(","); // pair[0]が自治体コード、先頭に0を追加する必要あり String jcode = pair[0]; if(jcode.length()==4) { jcode = "0" + jcode; } String sql = "SELECT * FROM template_shelter where jcode='" + jcode + "'"; rs = st.executeQuery(sql); LinkedList<String> list = new LinkedList<>(); while(rs.next()) { String code = rs.getString("code"); String name = rs.getString("name"); String pref = rs.getString("prefecture"); String gun = rs.getString("gun"); if(gun==null) gun = ""; String sikuchoson = rs.getString("sikuchoson"); String address = rs.getString("address"); PGgeometry geom = (PGgeometry) rs.getObject("geom"); String s[] = geom.toString().split(";"); String sgeom = "ST_GeomFromText('" + s[1] + "'," + s[0].substring(5) + ")"; String str = "INSERT INTO event_shelter_" + eventCode + " (code, name, pref, gun, sikuchoson, address, geom) " + "VALUES ('" + code + "','" + name + "','" + pref + "','" + gun + "','" + sikuchoson + "','" + address + "'," + sgeom + ")"; list.add(str); } System.out.println(list.size()); for(String s : list) { i++; System.out.println(i + ":" + s); st.execute(s); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static void addShelters2TableCustom(File file, String eventCode) { try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Shift_JIS"))) { // JDBCドライバのロード Class.forName("org.postgresql.Driver"); // データベース接続 System.out.println("Connecting to " + url); Connection db = DriverManager.getConnection(url, usr, pwd); Statement st = db.createStatement(); ResultSet rs; // 避難所情報の読み込み LinkedList<String> list = new LinkedList<>(); String line = br.readLine(); // 1行目は見出し int i = 0; while((line = br.readLine())!=null) { String pair[] = line.split(","); String code = pair[0]; String name = pair[1]; String pref = pair[2]; String gun = ""; if (gun == null) gun = ""; String sikuchoson = pair[3]; String address = pair[4]; String sgeom = "ST_GeomFromText('POINT(" + pair[8] + " " + pair[7] + ")',4612)"; String str = "INSERT INTO event_shelter_" + eventCode + " (code, name, pref, gun, sikuchoson, address, geom) " + "VALUES ('" + code + "','" + name + "','" + pref + "','" + gun + "','" + sikuchoson + "','" + address + "'," + sgeom + ")"; list.add(str); } System.out.println(list.size()); for(String s : list) { i++; System.out.println(i + ":" + s); st.execute(s); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static void updateEstimateInfoShelter2Table(File file, String eventCode) { try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Shift_JIS"))) { // JDBCドライバのロード Class.forName("org.postgresql.Driver"); // データベース接続 System.out.println("Connecting to " + url); Connection db = DriverManager.getConnection(url, usr, pwd); Statement st = db.createStatement(); int i=0; // 避難所情報の読み込み String line = br.readLine(); // 1行目は見出し while((line = br.readLine()) != null) { String pair[] = line.split(","); String code = pair[0]; double si = 0.0; if(!pair[5].isEmpty()) si = Double.parseDouble(pair[5]); double evacuee = Double.parseDouble(pair[6])*0.8; int ievacuee = (int) evacuee; String sql = "update event_shelter_" + eventCode + " set info_type='estimate',a01=" + ievacuee + " where code='" + code + "'"; i++; System.out.println(i + " : " + sql); st.execute(sql); } } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void updateEstimateInfoShelter2TableEmergency(File file, String eventCode) { try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Shift_JIS"))) { // JDBCドライバのロード Class.forName("org.postgresql.Driver"); // データベース接続 System.out.println("Connecting to " + url); Connection db = DriverManager.getConnection(url, usr, pwd); Statement st = db.createStatement(); int i=0; // 避難所情報の読み込み String line = br.readLine(); // 1行目は見出し while((line = br.readLine()) != null) { String pair[] = line.split(","); String code = pair[0]; double si = 0.0; if(!pair[5].isEmpty()) si = Double.parseDouble(pair[5]); double evacuee = Double.parseDouble(pair[6])*0.8; int ievacuee = (int) evacuee; String sql = "update event_shelter_" + eventCode + " set info_type='estimate',a01=" + ievacuee + " where code='" + code + "'"; i++; System.out.println(i + " : " + sql); st.execute(sql); } } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
h-crisis/assistant
DisasterDamageEstimate/src/jp/hcrisis/assistant/disaster/EarthquakeDamageDbSet.java
Java
apache-2.0
9,688
package com.chenxk.www.imitateqq.util; import android.graphics.PointF; /** * 几何图形工具 */ public class GeometryUtil { /** * As meaning of method name. * 获得两点之间的距离 * @param p0 * @param p1 * @return */ public static float getDistanceBetween2Points(PointF p0, PointF p1) { float distance = (float) Math.sqrt(Math.pow(p0.y - p1.y, 2) + Math.pow(p0.x - p1.x, 2)); return distance; } /** * Get middle point between p1 and p2. * 获得两点连线的中点 * @param p1 * @param p2 * @return */ public static PointF getMiddlePoint(PointF p1, PointF p2) { return new PointF((p1.x + p2.x) / 2.0f, (p1.y + p2.y) / 2.0f); } /** * Get point between p1 and p2 by percent. * 根据百分比获取两点之间的某个点坐标 * @param p1 * @param p2 * @param percent * @return */ public static PointF getPointByPercent(PointF p1, PointF p2, float percent) { return new PointF(evaluateValue(percent, p1.x , p2.x), evaluateValue(percent, p1.y , p2.y)); } /** * 根据分度值,计算从start到end中,fraction位置的值。fraction范围为0 -> 1 * @param fraction * @param start * @param end * @return */ public static float evaluateValue(float fraction, Number start, Number end){ return start.floatValue() + (end.floatValue() - start.floatValue()) * fraction; } /** * Get the point of intersection between circle and line. * 获取 通过指定圆心,斜率为lineK的直线与圆的交点。 * * @param pMiddle The circle center point. * @param radius The circle radius. * @param lineK The slope of line which cross the pMiddle. * @return */ public static PointF[] getIntersectionPoints(PointF pMiddle, float radius, Double lineK) { PointF[] points = new PointF[2]; float radian, xOffset = 0, yOffset = 0; if(lineK != null){ radian= (float) Math.atan(lineK); xOffset = (float) (Math.sin(radian) * radius); yOffset = (float) (Math.cos(radian) * radius); }else { xOffset = radius; yOffset = 0; } points[0] = new PointF(pMiddle.x + xOffset, pMiddle.y - yOffset); points[1] = new PointF(pMiddle.x - xOffset, pMiddle.y + yOffset); return points; } }
chenxiangkong/imitateQQ
ImitateQQ/app/src/main/java/com/chenxk/www/imitateqq/util/GeometryUtil.java
Java
apache-2.0
2,212
package com.coolweather.app.service; import com.coolweather.app.receiver.AutoUpdateReceiver; import com.coolweather.app.util.HttpCallbackListener; import com.coolweather.app.util.HttpUtil; import com.coolweather.app.util.Utility; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; public class AutoUpdateService extends Service { @Override public IBinder onBind(Intent intent) { return null; } public int onStartCommand(Intent intent, int flags, int startId) { new Thread(new Runnable() { @Override public void run() { updateWeather(); } }).start(); AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); int anHour = 8 * 60 * 60 * 1000; // ÕâÊÇ8СʱµÄºÁÃëÊý long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this, AutoUpdateReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId); } /** * ¸üÐÂÌìÆøÐÅÏ¢ */ private void updateWeather() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html"; HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { Utility.handleWeatherResponse(AutoUpdateService.this, response); } @Override public void onError(Exception e) { e.printStackTrace(); } }); } }
kobe-lee/CoolWeather
src/com/coolweather/app/service/AutoUpdateService.java
Java
apache-2.0
1,832
/**************************************************************************** Copyright 2006, Colorado School of Mines and others. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ package edu.mines.jtk.sgl; import java.awt.*; import java.awt.event.ActionEvent; import javax.swing.*; import edu.mines.jtk.awt.*; /** * A frame for testing the package {@link edu.mines.jtk.sgl}. * @author Dave Hale * @version 2006.06.28 */ class TestFrame extends JFrame { private static final long serialVersionUID = 1L; public TestFrame(World world) { OrbitView view = (world!=null)?new OrbitView(world):new OrbitView(); view.setAxesOrientation(AxesOrientation.XRIGHT_YOUT_ZDOWN); _canvas = new ViewCanvas(view); _canvas.setView(view); ModeManager mm = new ModeManager(); mm.add(_canvas); OrbitViewMode ovm = new OrbitViewMode(mm); SelectDragMode sdm = new SelectDragMode(mm); JPopupMenu.setDefaultLightWeightPopupEnabled(false); ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); Action exitAction = new AbstractAction("Exit") { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { System.exit(0); } }; JMenuItem exitItem = fileMenu.add(exitAction); exitItem.setMnemonic('x'); JMenu modeMenu = new JMenu("Mode"); modeMenu.setMnemonic('M'); JMenuItem ovmItem = new ModeMenuItem(ovm); modeMenu.add(ovmItem); JMenuItem sdmItem = new ModeMenuItem(sdm); modeMenu.add(sdmItem); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(modeMenu); JToolBar toolBar = new JToolBar(SwingConstants.VERTICAL); toolBar.setRollover(true); JToggleButton ovmButton = new ModeToggleButton(ovm); toolBar.add(ovmButton); JToggleButton sdmButton = new ModeToggleButton(sdm); toolBar.add(sdmButton); ovm.setActive(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(new Dimension(SIZE,SIZE)); this.add(_canvas,BorderLayout.CENTER); this.add(toolBar,BorderLayout.WEST); this.setJMenuBar(menuBar); _view = view; } public OrbitView getOrbitView() { return _view; } public ViewCanvas getViewCanvas() { return _canvas; } public static void main(String[] args) { TestFrame frame = new TestFrame(null); frame.setVisible(true); } private static final int SIZE = 600; private OrbitView _view; private ViewCanvas _canvas; }
askogvold/jtk
src/test/java/edu/mines/jtk/sgl/TestFrame.java
Java
apache-2.0
3,127
/** * Copyright OPS4J * * 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.ops4j.pax.wicket.spi.blueprint.injection.blueprint; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.ParserContext; import org.osgi.service.blueprint.container.ComponentDefinitionException; import org.osgi.service.blueprint.reflect.ComponentMetadata; import org.osgi.service.blueprint.reflect.Metadata; import org.w3c.dom.Element; import org.w3c.dom.Node; public class BlueprintNamespaceHandler implements NamespaceHandler { Map<String, AbstractBlueprintBeanDefinitionParser> namespaceRegistrations; public BlueprintNamespaceHandler() { namespaceRegistrations = new HashMap<String, AbstractBlueprintBeanDefinitionParser>(); namespaceRegistrations.put("application", new BlueprintApplicationBeanDefinitionParser()); namespaceRegistrations.put("page", new BlueprintPageFactoryBeanDefinitionParser()); namespaceRegistrations.put("classResolver", new BlueprintClassResolverDefinitionParser()); namespaceRegistrations.put("injectionProvider", new BlueprintInjectionResolverDefinitionParser()); namespaceRegistrations.put("filter", new BlueprintFilterFactoryBeanDefinitionParser()); namespaceRegistrations.put("autoPageMounter", new BlueprintAutoPageMounterDefinitionParser()); } public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) { throw new ComponentDefinitionException("Bad xml syntax: node decoration is not supported"); } @SuppressWarnings("rawtypes") public Set<Class> getManagedClasses() { Set<Class> managedClasses = new HashSet<Class>(); Collection<AbstractBlueprintBeanDefinitionParser> abstractBlueprintBeanDefinitionParsers = namespaceRegistrations.values(); for (AbstractBlueprintBeanDefinitionParser abstractBlueprintBeanDefinitionParser : abstractBlueprintBeanDefinitionParsers) { managedClasses.add(abstractBlueprintBeanDefinitionParser.getRuntimeClass()); } return managedClasses; } public URL getSchemaLocation(String schemaLocation) { return getClass().getResource("wicket.xsd"); } public Metadata parse(Element element, ParserContext context) { AbstractBlueprintBeanDefinitionParser definitionParser = retrieveDefinitionParser(element); try { return definitionParser.parse(element, context); } catch (Exception e) { throw new ComponentDefinitionException("Could not parse " + element.getNodeName() + " because of " + e.getMessage(), e); } } private AbstractBlueprintBeanDefinitionParser retrieveDefinitionParser(Node node) { if (namespaceRegistrations.containsKey(node.getNodeName())) { return namespaceRegistrations.get(node.getNodeName()); } if (namespaceRegistrations.containsKey(node.getLocalName())) { return namespaceRegistrations.get(node.getLocalName()); } throw new IllegalStateException("Unexpected element " + node.getNodeName()); } }
thrau/org.ops4j.pax.wicket
spi/blueprint/src/main/java/org/ops4j/pax/wicket/spi/blueprint/injection/blueprint/BlueprintNamespaceHandler.java
Java
apache-2.0
3,829
package com.elong.pb.newdda.client.router.parser.visitor.basic.mysql; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlEvalVisitorImpl; import java.util.Map; /** * MySQL变量中提取参数值与编号. */ public class MySqlEvalVisitor extends MySqlEvalVisitorImpl { public static final String EVAL_VAR_INDEX = "EVAL_VAR_INDEX"; @Override public boolean visit(final SQLVariantRefExpr x) { if (!"?".equals(x.getName())) { return false; } Map<String, Object> attributes = x.getAttributes(); int varIndex = x.getIndex(); if (varIndex == -1 || getParameters().size() <= varIndex) { return false; } if (attributes.containsKey(EVAL_VALUE)) { return false; } Object value = getParameters().get(varIndex); if (value == null) { value = EVAL_VALUE_NULL; } attributes.put(EVAL_VALUE, value); attributes.put(EVAL_VAR_INDEX, varIndex); return false; } }
makemyownlife/newdda-client
src/main/java/com/elong/pb/newdda/client/router/parser/visitor/basic/mysql/MySqlEvalVisitor.java
Java
apache-2.0
1,093
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2021 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.eclipse.launching.shortcuts; import org.eclipse.xtext.xbase.ui.launching.JavaElementDelegateMainLaunch; /** Delegate dedicated to SARL for breaking down the multiple adapter (from SARL and Xtend) issue. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ public class SarlJavaElementDelegateMainLaunch extends JavaElementDelegateMainLaunch { // }
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/launching/shortcuts/SarlJavaElementDelegateMainLaunch.java
Java
apache-2.0
1,174
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.hdds.scm.container.placement.algorithms; import com.google.common.annotations.VisibleForTesting; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric; import org.apache.hadoop.hdds.scm.exceptions.SCMException; import org.apache.hadoop.hdds.scm.node.NodeManager; import org.apache.hadoop.hdds.protocol.DatanodeDetails; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.stream.Collectors; /** * SCM CommonPolicy implements a set of invariants which are common * for all container placement policies, acts as the repository of helper * functions which are common to placement policies. */ public abstract class SCMCommonPolicy implements ContainerPlacementPolicy { @VisibleForTesting static final Logger LOG = LoggerFactory.getLogger(SCMCommonPolicy.class); private final NodeManager nodeManager; private final Random rand; private final Configuration conf; /** * Constructs SCM Common Policy Class. * * @param nodeManager NodeManager * @param conf Configuration class. */ public SCMCommonPolicy(NodeManager nodeManager, Configuration conf) { this.nodeManager = nodeManager; this.rand = new Random(); this.conf = conf; } /** * Return node manager. * * @return node manager */ public NodeManager getNodeManager() { return nodeManager; } /** * Returns the Random Object. * * @return rand */ public Random getRand() { return rand; } /** * Get Config. * * @return Configuration */ public Configuration getConf() { return conf; } /** * Given the replication factor and size required, return set of datanodes * that satisfy the nodes and size requirement. * <p> * Here are some invariants of container placement. * <p> * 1. We place containers only on healthy nodes. * 2. We place containers on nodes with enough space for that container. * 3. if a set of containers are requested, we either meet the required * number of nodes or we fail that request. * * * @param excludedNodes - datanodes with existing replicas * @param nodesRequired - number of datanodes required. * @param sizeRequired - size required for the container or block. * @return list of datanodes chosen. * @throws SCMException SCM exception. */ @Override public List<DatanodeDetails> chooseDatanodes( List<DatanodeDetails> excludedNodes, int nodesRequired, final long sizeRequired) throws SCMException { List<DatanodeDetails> healthyNodes = nodeManager.getNodes(HddsProtos.NodeState.HEALTHY); healthyNodes.removeAll(excludedNodes); String msg; if (healthyNodes.size() == 0) { msg = "No healthy node found to allocate container."; LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes .FAILED_TO_FIND_HEALTHY_NODES); } if (healthyNodes.size() < nodesRequired) { msg = String.format("Not enough healthy nodes to allocate container. %d " + " datanodes required. Found %d", nodesRequired, healthyNodes.size()); LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes.FAILED_TO_FIND_SUITABLE_NODE); } List<DatanodeDetails> healthyList = healthyNodes.stream().filter(d -> hasEnoughSpace(d, sizeRequired)).collect(Collectors.toList()); if (healthyList.size() < nodesRequired) { msg = String.format("Unable to find enough nodes that meet the space " + "requirement of %d bytes in healthy node set." + " Nodes required: %d Found: %d", sizeRequired, nodesRequired, healthyList.size()); LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes.FAILED_TO_FIND_NODES_WITH_SPACE); } return healthyList; } /** * Returns true if this node has enough space to meet our requirement. * * @param datanodeDetails DatanodeDetails * @return true if we have enough space. */ private boolean hasEnoughSpace(DatanodeDetails datanodeDetails, long sizeRequired) { SCMNodeMetric nodeMetric = nodeManager.getNodeStat(datanodeDetails); return (nodeMetric != null) && (nodeMetric.get() != null) && nodeMetric.get().getRemaining().hasResources(sizeRequired); } /** * This function invokes the derived classes chooseNode Function to build a * list of nodes. Then it verifies that invoked policy was able to return * expected number of nodes. * * @param nodesRequired - Nodes Required * @param healthyNodes - List of Nodes in the result set. * @return List of Datanodes that can be used for placement. * @throws SCMException */ public List<DatanodeDetails> getResultSet( int nodesRequired, List<DatanodeDetails> healthyNodes) throws SCMException { List<DatanodeDetails> results = new ArrayList<>(); for (int x = 0; x < nodesRequired; x++) { // invoke the choose function defined in the derived classes. DatanodeDetails nodeId = chooseNode(healthyNodes); if (nodeId != null) { results.add(nodeId); } } if (results.size() < nodesRequired) { LOG.error("Unable to find the required number of healthy nodes that " + "meet the criteria. Required nodes: {}, Found nodes: {}", nodesRequired, results.size()); throw new SCMException("Unable to find required number of nodes.", SCMException.ResultCodes.FAILED_TO_FIND_SUITABLE_NODE); } return results; } /** * Choose a datanode according to the policy, this function is implemented * by the actual policy class. For example, PlacementCapacity or * PlacementRandom. * * @param healthyNodes - Set of healthy nodes we can choose from. * @return DatanodeDetails */ public abstract DatanodeDetails chooseNode( List<DatanodeDetails> healthyNodes); }
littlezhou/hadoop
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/placement/algorithms/SCMCommonPolicy.java
Java
apache-2.0
6,968
package ca.weblite.codename1.cn1ml.demos; import com.codename1.ui.Command; import com.codename1.ui.Component; import com.codename1.ui.Display; import com.codename1.ui.Form; import com.codename1.ui.Label; import com.codename1.ui.events.ActionEvent; import com.codename1.ui.events.ActionListener; import com.codename1.ui.layouts.BorderLayout; import com.codename1.ui.plaf.UIManager; import com.codename1.ui.util.Resources; import java.io.IOException; import java.util.HashMap; public class CN1MLDemo { private Form current; private Resources theme; public void init(Object context) { try { theme = Resources.openLayered("/theme"); UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0])); } catch(IOException e){ e.printStackTrace(); } // Pro users - uncomment this code to get crash reports sent to you automatically /*Display.getInstance().addEdtErrorHandler(new ActionListener() { public void actionPerformed(ActionEvent evt) { evt.consume(); Log.p("Exception in AppName version " + Display.getInstance().getProperty("AppVersion", "Unknown")); Log.p("OS " + Display.getInstance().getPlatformName()); Log.p("Error " + evt.getSource()); Log.p("Current Form " + Display.getInstance().getCurrent().getName()); Log.e((Throwable)evt.getSource()); Log.sendLog(); } });*/ } public void start() { if(current != null){ current.show(); return; } showMainMenu(); } private Form createForm(String title, Component content){ Form f = new Form(title); f.setLayout(new BorderLayout()); f.addComponent(BorderLayout.CENTER, content); if (!"Main Menu".equals(title)){ f.setBackCommand(new Command("Main Menu"){ @Override public void actionPerformed(ActionEvent evt) { createForm("Main Menu", getMainMenu()).showBack(); } }); } return f; } private Component getMainMenu(){ HashMap context = new HashMap(); context.put("res", theme); context.put("menuItems", new String[]{ "Simple List", "Contact Form", "Contact Form i18n", "Map", "Web Browser", "Default Sample Template", "Images Example", "My Old Form", "Tabs Demo", "Login Form" }); final MainMenu m = new MainMenu(context); m.getMenuList().addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { String sel = (String)m.getMenuList().getSelectedItem(); if ("Simple List".equals(sel)){ showSimpleList(); } else if ( "Contact Form".equals(sel)){ showContactForm(); } else if ( "Contact Form i18n".equals(sel)){ showContactFormI18n(); } else if ("Map".equals(sel)){ showMap(); } else if ("Web Browser".equals(sel)){ showWebBrowser(); } else if ("Default Sample Template".equals(sel)){ showMyNewForm(); } else if ("Images Example".equals(sel)){ showImagesExample(); } else if ( "My Old Form".equals(sel)){ showMyOldForm(); } else if ("Tabs Demo".equals(sel)){ showTabsDemo(); } else if ("Login Form".equals(sel)){ showLoginDemo(); } } }); return m.getRoot(); } private void showMainMenu(){ createForm("CN1ML Demos", getMainMenu()).show(); } private void showSimpleList(){ SimpleList l = new SimpleList(newContext()); createForm("Simple List", l.getRoot()).show(); } private HashMap newContext(){ HashMap context = new HashMap(); context.put("res", theme); return context; } private void showContactForm(){ ContactForm f = new ContactForm(newContext()); createForm("Contact Form", f.getRoot()).show(); } private void showContactFormI18n(){ ContactFormI18n f = new ContactFormI18n(newContext()); UIManager.getInstance().setBundle(theme.getL10N("ContactFormI18n", "fr")); createForm("Contact Form i18n", f.getRoot()).show(); } private void showMap(){ Map m = new Map(newContext()); createForm("Map", m.getRoot()).show(); } private void showWebBrowser(){ WebBrowser m = new WebBrowser(newContext()); createForm("Web Browser", m.getRoot()).show(); } private void showImagesExample(){ ImagesExample e = new ImagesExample(newContext()); createForm("Images Grid", e.getRoot()).show(); } private void showMyOldForm(){ MyOldForm f = new MyOldForm(newContext()); createForm("Old Form", f.getRoot()).show(); } private void showTabsDemo(){ TabsDemo f = new TabsDemo(newContext()); createForm("Tabs Demo", f.getRoot()).show(); } private void showLoginDemo(){ LoginPanel f = new LoginPanel(newContext()); createForm("Login Demo", f.getRoot()).show(); } private void showMyNewForm(){ // Instantiate the MyNewForm class. // Takes a Map in the constructor as a means of passing data to the // template. MyNewForm f = new MyNewForm(new HashMap()); // Create a new form to show our template Form form = new Form("My New Form"); form.setLayout(new BorderLayout()); // Add the MyNewForm to the form. // Use the getRoot() method to get the root container // corresponding to the <body> tag. form.addComponent(BorderLayout.CENTER, f.getRoot()); // Show the form form.show(); } public void stop() { current = Display.getInstance().getCurrent(); } public void destroy() { } }
shannah/CN1ML-NetbeansModule
CN1MLDemos/src/ca/weblite/codename1/cn1ml/demos/CN1MLDemo.java
Java
apache-2.0
6,690
/* * Copyright 2013-2022 Erudika. https://erudika.com * * 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. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.email; import com.erudika.para.core.email.Emailer; import java.util.ArrayList; import java.util.Collections; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; /** * * @author Alex Bogdanovski [alex@erudika.com] */ @Ignore public abstract class EmailerTest { protected Emailer e; @Test public void testSendEmail() { assertFalse(e.sendEmail(null, null, null)); assertFalse(e.sendEmail(new ArrayList<>(), null, "asd")); assertFalse(e.sendEmail(Collections.singletonList("test@test.com"), null, "")); assertTrue(e.sendEmail(Collections.singletonList("test@test.com"), null, "asd")); } }
Erudika/para
para-server/src/test/java/com/erudika/para/email/EmailerTest.java
Java
apache-2.0
1,339
/** * Copyright 2011-2017 Asakusa Framework Team. * * 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.asakusafw.utils.java.internal.model.util; import java.math.BigInteger; /** * Analyzes Java literals. */ public final class LiteralAnalyzer { private static final BigInteger MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.ONE); private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); private LiteralAnalyzer() { return; } /** * Analyzes the literal token. * @param literal the target literal * @return the analyzed token * @throws IllegalArgumentException if the parameter is {@code null} */ public static LiteralToken parse(String literal) { if (literal == null) { throw new IllegalArgumentException("literal must not be null"); //$NON-NLS-1$ } LiteralTokenKind kind = LiteralParser.scan(literal); Object value = valueOf(kind, literal); return new LiteralToken(literal, kind, value); } private static Object valueOf(LiteralTokenKind kind, String literal) { switch (kind) { case BOOLEAN: return booleanValueOf(literal); case CHAR: return charValueOf(literal); case DOUBLE: return doubleValueOf(literal); case FLOAT: return floatValueOf(literal); case INT: return intValueOf(literal); case LONG: return longValueOf(literal); case NULL: return null; case STRING: return stringValueOf(literal); case UNKNOWN: return LiteralTokenKind.UNKNOWN; default: throw new AssertionError(literal); } } /** * Analyzes a literal which represents {@code boolean} value and returns it value. * @param literal the target literal token * @return the corresponded value * @throws IllegalArgumentException if the target literal is malformed */ public static boolean booleanValueOf(String literal) { if (LiteralToken.TOKEN_TRUE.equals(literal)) { return true; } else if (LiteralToken.TOKEN_FALSE.equals(literal)) { return false; } else { throw new IllegalArgumentException(literal); } } /** * Analyzes a literal which represents {@code char} value and returns it value. * @param literal the target literal token * @return the corresponded value * @throws IllegalArgumentException if the target literal is malformed */ public static char charValueOf(String literal) { int length = literal.length(); if (length < 3 || literal.charAt(0) != '\'' || literal.charAt(length - 1) != '\'') { throw new IllegalArgumentException(literal); } String unescaped = JavaEscape.unescape(literal.substring(1, length - 1)); if (unescaped.length() != 1) { throw new IllegalArgumentException(literal); } return unescaped.charAt(0); } /** * Analyzes a literal which represents {@code double} value and returns it value. * @param literal the target literal token * @return the corresponded value * @throws NumberFormatException if the target literal is malformed */ public static double doubleValueOf(String literal) { return Double.parseDouble(literal); } /** * Analyzes a literal which represents {@code float} value and returns it value. * @param literal the target literal token * @return the corresponded value * @throws NumberFormatException if the target literal is malformed */ public static float floatValueOf(String literal) { return Float.parseFloat(literal); } /** * Analyzes a literal which represents {@code int} value and returns it value. * @param literal the target literal token * @return the corresponded value * @throws NumberFormatException if the target literal is malformed */ public static int intValueOf(String literal) { IntegerHolder h = parseInteger(literal); BigInteger number = h.toBigInteger(); if (h.radix != 10) { if (number.bitLength() > 32) { throw new NumberFormatException(literal); } } else { if (number.bitLength() > 31 && !number.equals(MAX_INT)) { throw new NumberFormatException(literal); } } return number.intValue(); } /** * Analyzes a literal which represents {@code long} value and returns it value. * @param literal the target literal token * @return the corresponded value * @throws NumberFormatException if the target literal is malformed */ public static long longValueOf(String literal) { String target; if (literal.endsWith("l") || literal.endsWith("L")) { //$NON-NLS-1$ //$NON-NLS-2$ target = literal.substring(0, literal.length() - 1); } else { target = literal; } IntegerHolder h = parseInteger(target); BigInteger number = h.toBigInteger(); if (h.radix != 10) { if (number.bitLength() > 64) { throw new NumberFormatException(literal); } } else { if (number.bitLength() > 63 && !number.equals(MAX_LONG)) { throw new NumberFormatException(literal); } } return number.longValue(); } /** * Analyzes a literal which represents a value of {@link String} and returns its value. * @param literal the target literal token * @return the corresponded value * @throws IllegalArgumentException if the target literal is malformed */ public static String stringValueOf(String literal) { int length = literal.length(); if (length < 2 || literal.charAt(0) != '\"' || literal.charAt(length - 1) != '\"') { throw new IllegalArgumentException(literal); } return JavaEscape.unescape(literal.substring(1, length - 1)); } /** * Returns the literal token of the target value. * @param value the target value * @return the corresponded literal string * @throws IllegalArgumentException if there is no suitable literal for the target value */ public static String literalOf(Object value) { if (value == null) { return nullLiteral(); } Class<? extends Object> klass = value.getClass(); if (klass == Boolean.class) { return booleanLiteralOf((Boolean) value); } else if (klass == Character.class) { return charLiteralOf((Character) value); } else if (klass == Double.class) { return doubleLiteralOf((Double) value); } else if (klass == Float.class) { return floatLiteralOf((Float) value); } else if (klass == Integer.class) { return intLiteralOf((Integer) value); } else if (klass == Long.class) { return longLiteralOf((Long) value); } else if (klass == String.class) { return stringLiteralOf((String) value); } else { throw new IllegalArgumentException(value.toString()); } } /** * Returns the literal token of target {@code boolean} value. * @param value the target value * @return the corresponded literal token */ public static String booleanLiteralOf(boolean value) { return String.valueOf(value); } /** * Returns the literal token of target {@code char} value. * @param value the target value * @return the corresponded literal token */ public static String charLiteralOf(char value) { return '\'' + JavaEscape.escape(String.valueOf(value), true, false) + '\''; } /** * Returns the literal token of target {@code double} value. * @param value the target value * @return the corresponded literal token */ public static String doubleLiteralOf(double value) { return String.valueOf(value); } /** * Returns the literal token of target {@code float} value. * @param value the target value * @return the corresponded literal token */ public static String floatLiteralOf(float value) { if (Float.isInfinite(value) || Float.isNaN(value)) { return String.valueOf(value); } else { return String.valueOf(value) + "f"; //$NON-NLS-1$ } } /** * Returns the literal token of target {@code int} value. * @param value the target value * @return the corresponded literal token */ public static String intLiteralOf(int value) { return String.valueOf(value); } /** * Returns the literal token of target {@code long} value. * @param value the target value * @return the corresponded literal token */ public static String longLiteralOf(long value) { return String.valueOf(value) + 'L'; } /** * Returns a literal token for the {@code String} value. * @param value the target value * @return the corresponded literal token */ public static String stringLiteralOf(String value) { return '\"' + JavaEscape.escape(value, false, false) + '\"'; } /** * Returns the literal token of {@code null}. * @return the {@code null} literal token */ public static String nullLiteral() { return LiteralToken.TOKEN_NULL; } private static IntegerHolder parseInteger(String literal) { assert literal != null; String target; boolean positive; if (literal.startsWith("-")) { //$NON-NLS-1$ target = literal.substring(1).trim(); positive = false; } else { target = literal; positive = true; } if (target.length() > 2 && (target.startsWith("0x") || target.startsWith("0X"))) { //$NON-NLS-1$ //$NON-NLS-2$ return new IntegerHolder(positive, target.substring(2), 16); } else if (target.length() > 1 && target.startsWith("0")) { //$NON-NLS-1$ return new IntegerHolder(positive, target.substring(1), 8); } else { return new IntegerHolder(positive, target, 10); } } private static class IntegerHolder { private final boolean positive; private final String literal; final int radix; IntegerHolder(boolean positive, String literal, int radix) { this.positive = positive; this.literal = literal; this.radix = radix; } BigInteger toBigInteger() { BigInteger bint = new BigInteger(this.literal, this.radix); if (this.positive) { return bint; } else { return bint.negate(); } } } }
cocoatomo/asakusafw
utils-project/java-dom/src/main/java/com/asakusafw/utils/java/internal/model/util/LiteralAnalyzer.java
Java
apache-2.0
11,585
package com.fishercoder; import com.fishercoder.solutions._1371; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; public class _1371Test { private static _1371.Solution1 solution1; @BeforeClass public static void setup() { solution1 = new _1371.Solution1(); } @Test public void test1() { assertEquals(13, solution1.findTheLongestSubstring("eleetminicoworoep")); } @Test public void test2() { assertEquals(5, solution1.findTheLongestSubstring("leetcodeisgreat")); } @Test public void test3() { assertEquals(6, solution1.findTheLongestSubstring("bcbcbc")); } @Test public void test4() { assertEquals(1, solution1.findTheLongestSubstring("id")); } }
fishercoder1534/Leetcode
src/test/java/com/fishercoder/_1371Test.java
Java
apache-2.0
808
package djgcv.ssjp.util.flow; import java.util.concurrent.Executor; public class ExecutorPipe<T> extends AbstractPipe<T> { private final Executor executor; public ExecutorPipe(Executor executor) { this.executor = executor; } public Executor getExecutor() { return executor; } @Override public Receiver<? super T> getInput() { return input; } private final Receiver<T> input = new Receiver<T>() { @Override public boolean receive(final T value) { Executor executor = getExecutor(); boolean handled = false; for (final Receiver<? super T> receiver : getOutput().getReceivers()) { executor.execute(new Runnable() { @Override public void run() { receiver.receive(value); } }); handled = true; } return handled; } }; }
talflon/ssjp-java
src/main/java/djgcv/ssjp/util/flow/ExecutorPipe.java
Java
apache-2.0
860
/** * Copyright 2005 Cordys R&D B.V. * * This file is part of the Cordys File Connector. * * 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.cordys.coe.ac.fileconnector; import java.io.File; import java.nio.charset.spi.CharsetProvider; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; import com.cordys.coe.ac.fileconnector.charset.ascii.AsciiCharset; import com.cordys.coe.ac.fileconnector.exception.ConfigException; import com.cordys.coe.ac.fileconnector.utils.XPathWrapperFactory; import com.cordys.coe.ac.fileconnector.utils.XmlUtils; import com.cordys.coe.exception.GeneralException; import com.cordys.coe.util.XMLProperties; import com.cordys.coe.util.win32.NetworkDrive; import com.cordys.coe.util.xml.nom.XPathHelper; import com.eibus.util.Base64; import com.eibus.util.logger.CordysLogger; import com.eibus.util.logger.Severity; import com.eibus.xml.nom.Node; /** * This class holds the configuration details for the FileConnector. The configuration specifies the * actual configuration file location in the XMLStore. * * @author mpoyhone */ public class ApplicationConfiguration { /** * The tag name which holds the XMLStore record reader configuration file name in the processor * configuration xml. */ private static final String READER_CONFIG_FILENAME = "/configuration/Configuration/readerconfigfile"; /** * The tag name which holds character set name for ReadFileRecords method. */ private static final String READER_CHARACTER_SET = "/configuration/Configuration/readercharset"; /** * The tag name which holds character set name for WriteFileRecords method. */ private static final String WRITER_CHARACTER_SET = "/configuration/Configuration/writercharset"; /** * The tag name which holds the XMLStore record writer configuration file name in the processor * configuration xml. */ private static final String WRITER_CONFIG_FILENAME = "/configuration/Configuration/writerconfigfile"; /** * The tag name which holds the configuration reload flag name. */ private static final String RELOAD_CONFIG = "/configuration/Configuration/reload-configuration"; /** * The tag name which holds the simple XPath flag name. */ private static final String USE_SIMPLE_XPATH = "/configuration/Configuration/use-simple-xpath"; /** * The name of the tag holding all the drive mappings. */ private static final String PROP_DRIVE_MAPPINGS = "/configuration/Configuration/drivemappings/drivemapping"; /** * Identifies the Logger. */ private static CordysLogger LOGGER = CordysLogger.getCordysLogger(FileConnector.class); /** * Custom character set provider for Latin-1 to Ascii conversion feature. */ private CharsetProvider cpCustomProvider; /** * Contains all directory and file names that are allowed to be accessed through this connector. */ private Pattern[] paAllowedDirectoryNames = null; /** * If <code>true</code> simple XPath expressions are used. */ private boolean useSimpleXPath; /** * Contains the XPath wrapper factory which contains namespace bindings from the configuration. */ private XPathWrapperFactory xpathFactory; /** * Holds the XMLProperties object to extract the value for different configuration keys. */ private XMLProperties xpBase; /** * Creates the constructor.This loads the configuration object and pass it to XMLProperties for * processing. * * @param iConfigNode The xml-node that contains the configuration. * * @throws ConfigException Thrown if the configuration XML was invalid. */ public ApplicationConfiguration(int iConfigNode) throws ConfigException { if (iConfigNode == 0) { throw new ConfigException(LogMessages.CONFIGURATION_NOT_FOUND); } if (!Node.getName(iConfigNode).equals("configuration")) { throw new ConfigException(LogMessages.ROOT_ELEMENT_MISS_MATCH); } try { xpBase = new XMLProperties(iConfigNode); } catch (GeneralException e) { throw new ConfigException( e,LogMessages.EXCEPTION_CREATING_CONFIG_OBJECT); } useSimpleXPath = xpBase.getBooleanValue(USE_SIMPLE_XPATH, true); xpathFactory = XmlUtils.parseNamespaceBindings(iConfigNode, false); setUseSimpleXPath(useSimpleXPath); String sAllowedStr = xpBase.getStringValue("included-directories", ""); if (!sAllowedStr.equals("")) { String[] saAllowedLines = sAllowedStr.split("[\r\n]+"); if ((saAllowedLines != null) && (saAllowedLines.length > 0)) { List<Pattern> lList = new LinkedList<Pattern>(); for (int i = 0; i < saAllowedLines.length; i++) { String sLine = saAllowedLines[i]; if (sLine.length() == 0) { continue; } if (File.pathSeparatorChar == '\\') { // Convert / to \ on windows platform sLine = sLine.replaceAll("/", "\\\\"); } Pattern pPat; try { pPat = convertWildCardToPattern(sLine, File.separator); } catch (IllegalArgumentException e) { throw new ConfigException(e,LogMessages.UNABLE_TO_PARESE_DIRECTORY_SPECIFICATION); } lList.add(pPat); } if (lList.size() > 0) { paAllowedDirectoryNames = lList.toArray(new Pattern[lList.size()]); } } } } /** * Sets the useSimpleXPath. * * @param useSimpleXPath The useSimpleXPath to be set. */ public void setUseSimpleXPath(boolean useSimpleXPath) { this.useSimpleXPath = useSimpleXPath; if (xpathFactory != null) { xpathFactory.setUseSimpleXPath(useSimpleXPath); } } /** * Returns the refresh interval for the configuration file. * * @return The interval in milliseconds. */ public long getConfigFileRefreshInterval() { return 20000L; } /** * Returns the root configuration node. * * @return Root node */ public int getConfigurationNode() { return (xpBase != null) ? xpBase.getConfigNode() : 0; } /** * Returns the custom character set provider or null if none was loaded. * * @return The custom character set provider or null if none was loaded. */ public CharsetProvider getCustomCharsetProvider() { return cpCustomProvider; } /** * This method returns the network drives that should be created for this directory connector. * * @return An array containing all the network drives. */ public NetworkDrive[] getNetworkDrives() { int[] aiMapping = XPathHelper.selectNodes(xpBase.getConfigNode(), PROP_DRIVE_MAPPINGS); ArrayList<NetworkDrive> alTemp = new ArrayList<NetworkDrive>(); for (int iCount = 0; iCount < aiMapping.length; iCount++) { try { XMLProperties xpTemp = new XMLProperties(aiMapping[iCount]); String password = Base64.decode(xpTemp.getStringValue("password")); NetworkDrive ndTemp = new NetworkDrive(xpTemp.getStringValue("location"), getDriveLetter(xpTemp), xpTemp.getStringValue("username"), password); alTemp.add(ndTemp); } catch (Exception e) { if (LOGGER.isEnabled(Severity.ERROR)) { LOGGER.error(e, LogMessages.DRIVE_MAPPING_UNREADABLE); } throw new IllegalStateException(e); } } return alTemp.toArray(new NetworkDrive[alTemp.size()]); } /** * This method returns the character set to be used for reading file records. * * @return The reader character set. */ public String getReaderCharacterSet() { return xpBase.getStringValue(READER_CHARACTER_SET, ""); } /** * This method returns the record reader configuration file path in XMLStore. * * @return The location for the configuration file */ public String getReaderConfigFileLocation() { String sReturn = ""; sReturn = xpBase.getStringValue(READER_CONFIG_FILENAME, ""); return sReturn; } /** * Returns a configuration section. * * @param path Section path * * @return Section. * * @throws GeneralException */ public XMLProperties getSection(String path) throws GeneralException { return xpBase.getXMLProperties(path); } /** * This method returns the character set to be used for reading file records. This does not * return the X-CORDYS-LATIN1-ASCII character set. * * @return The read character set. */ public String getStandardReaderCharacterSet() { String res = getReaderCharacterSet(); if (AsciiCharset.CHARSETNAME.equals(res)) { return "ISO-8859-1"; } else { return res; } } /** * This method returns the character set to be used for writing file records. This does not * return the X-CORDYS-LATIN1-ASCII character set. * * @return The read character set. */ public String getStandardWriterCharacterSet() { String res = getWriterCharacterSet(); if (AsciiCharset.CHARSETNAME.equals(res)) { return "ISO-8859-1"; } else { return res; } } /** * Returns the read buffer size int bytes for record validator. * * @return */ public int getValidatorWindowSize() { return 4096; } /** * This method returns the character set to be used for writing file records. * * @return The writer character set. */ public String getWriterCharacterSet() { return xpBase.getStringValue(WRITER_CHARACTER_SET, "ISO-8859-1"); } /** * This method returns the record writer configuration file path in XMLStore. * * @return The location for the configuration file */ public String getWriterConfigFileLocation() { String sReturn = ""; sReturn = xpBase.getStringValue(WRITER_CONFIG_FILENAME, ""); return sReturn; } /** * Returns the associated XPathFactory. * * @return XPath factory. */ public XPathWrapperFactory getXPathFactory() { return xpathFactory; } /** * Returns the configuration reload flag value. * * @return <code>true</code> if configuration should be loaded with each request. */ public boolean isConfigurationReloadEnabled() { return xpBase.getBooleanValue(RELOAD_CONFIG, false); } /** * Checks if the file is allowed to be accesses by the configuration settings. * * @param fFile File to be checked. * * @return True, if file is allowed, false otherwise. */ public boolean isFileAllowed(File fFile) { String sFilePath = fFile.getAbsolutePath(); if ((paAllowedDirectoryNames == null) || (paAllowedDirectoryNames.length == 0)) { return true; } for (int i = 0; i < paAllowedDirectoryNames.length; i++) { Pattern pFilePattern = paAllowedDirectoryNames[i]; if (pFilePattern.matcher(sFilePath).matches()) { return true; } } if (fFile.isDirectory()) { // We need to add directory separator to the path in order // to catch the directory itself for patterns like /path/** sFilePath += File.separator; for (int i = 0; i < paAllowedDirectoryNames.length; i++) { Pattern pFilePattern = paAllowedDirectoryNames[i]; if (pFilePattern.matcher(sFilePath).matches()) { return true; } } } return false; } /** * Returns the useSimpleXPath. * * @return Returns the useSimpleXPath. */ public boolean isUseSimpleXPath() { return useSimpleXPath; } /** * Sets the custom character set provider. * * @param prov The custom character set provider to be set. */ public void setCustomCharsetProvider(CharsetProvider prov) { cpCustomProvider = prov; } /** * Converts wild card string of forms \a\\b, \a\\b \a\.txt to a regular expression. * * @param sWildCardString Wild card string to be converted. * @param sPathSep File path separator (e.g. \ or /) * * @return Regular expression <code>Pattern</code> object * * @throws IllegalArgumentException Thrown if the parsing failed. */ protected static Pattern convertWildCardToPattern(String sWildCardString, String sPathSep) throws IllegalArgumentException { String sPatternString = sWildCardString; if (sPathSep.equals("\\")) { sPathSep = "\\\\"; } // Convert simple wild-card to a regexp. This uses unicode character \u0001 as a marker // for * character so it will not be replaced twice. // Also path separator string is marked by \u0002 // Escape all path separators to \u0002 sPatternString = sPatternString.replaceAll(sPathSep, "\u0002"); // Escape special characters \[](){}.$^ sPatternString = sPatternString.replaceAll("([\\\\\\[\\]\\(\\)\\{\\}\\.$\\^])", "\\\\$1"); // Change /path/** notation to /path/.* sPatternString = sPatternString.replaceAll("\u0002\\*\\*$", "\u0002.\u0001"); // Change /path/**/path notation to /path/.*/ sPatternString = sPatternString.replaceAll("\u0002\\*\\*\u0002", "\u0002.\u0001\u0002"); // Change /path/*/path notation /path/[^/]*/path sPatternString = sPatternString.replaceAll("\\*", "[^\u0002]\u0001"); // Replace the marker with * sPatternString = sPatternString.replace('\u0001', '*'); if (sPathSep.equals("\\\\")) { // A weird behavior in replaceAll seems to require this. sPathSep = "\\\\\\\\"; } // Escape all \u0002's to path separators. sPatternString = sPatternString.replaceAll("\u0002", sPathSep); try { return Pattern.compile(sPatternString, Pattern.CASE_INSENSITIVE); } catch (Exception e) { throw new IllegalArgumentException("Invalid wildcard pattern '" + sWildCardString + "' : " + e); } } /** * This method returns the drive letter for the given drive. * * @param xpTemp The property definition. * * @return The drive letter (if any specified). * * @throws ConfigException */ private String getDriveLetter(XMLProperties xpTemp) throws ConfigException { String driveLetter = xpTemp.getStringValue("driveletter"); if (driveLetter != null) { driveLetter = driveLetter.toUpperCase(); if ((driveLetter != null) && (driveLetter.length() > 0)) { if (!driveLetter.matches("[a-zA-Z]:{0,1}")) { throw new ConfigException(LogMessages.DRIVELETTER_NOT_VALID,driveLetter); } if (driveLetter.length() == 1) { driveLetter = driveLetter + ":"; } } } return driveLetter; } }
MatthiasEberl/cordysfilecon
src/cws/FileConnector/com-cordys-coe/fileconnector/java/source/com/cordys/coe/ac/fileconnector/ApplicationConfiguration.java
Java
apache-2.0
17,807
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * 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.seleniumtests.it.stubclasses; import java.lang.reflect.Method; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.xml.XmlTest; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.customexception.ConfigurationException; import com.seleniumtests.reporter.logger.TestLogging; /** * Test class to product a BeforeXXX configuration error and look for logs in report * @author s047432 * */ public class StubTestClassForConfigurationError1 extends StubParentClass { @BeforeMethod public void beforeMethod(Method method) { SeleniumTestsContextManager.getThreadContext().setManualTestSteps(true); throw new ConfigurationException("Some error before method"); } @Test public void testWithABeforeMethodError(XmlTest xmlTest) { addStep("step 1"); logger.info("some info"); } }
bhecquet/seleniumRobot
core/src/test/java/com/seleniumtests/it/stubclasses/StubTestClassForConfigurationError1.java
Java
apache-2.0
1,643
/** * Copyright (c) 2009-2012, Christer Sandberg * Thymesheet modifications Copyright (c) 2013 Adam Perry, Connect Group */ package com.connect_group.thymesheet.css.selectors.specifier; import com.connect_group.thymesheet.css.selectors.Specifier; import com.connect_group.thymesheet.css.util.Assert; /** * An implementation of {@link Specifier} for pseudo-classes. * <p> * Note: * <br> * The negation pseudo-class specifier is implemented by {@link NegationSpecifier}, and * the {@code nth-*} pseudo-classes are implemented by {@link PseudoNthSpecifier}. * * @see <a href="http://www.w3.org/TR/css3-selectors/#pseudo-classes">Pseudo-classes</a> * * @author Christer Sandberg */ public class PseudoClassSpecifier implements Specifier { /** The pseudo-class value. */ private final String value; /** * Create a new pseudo-class specifier with the specified value. * * @param value The pseudo-class value. */ public PseudoClassSpecifier(String value) { Assert.notNull(value, "value is null!"); this.value = value; } /** * Get the pseudo-class value. * * @return The pseudo-class value. */ public String getValue() { return value; } /** * {@inheritDoc} */ public Type getType() { return Type.PSEUDO; } }
connect-group/thymesheet
src/main/java/com/connect_group/thymesheet/css/selectors/specifier/PseudoClassSpecifier.java
Java
apache-2.0
1,416
package com.laaidback.ascribe.event; public class NoteMovedEvent { private int fromPosition; private int toPosition; public NoteMovedEvent(int fromPosition, int toPosition) { this.fromPosition = fromPosition; this.toPosition = toPosition; } public int getFromPosition() { return fromPosition; } public int getToPosition() { return toPosition; } }
Laaidback/A.scribe
app/src/main/java/com/laaidback/ascribe/event/NoteMovedEvent.java
Java
apache-2.0
417
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_9455 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_9455.java
Java
apache-2.0
151
/* * Copyright 2019 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.clouddriver.tasks.providers.gce; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.netflix.spinnaker.orca.TaskResult; import com.netflix.spinnaker.orca.clouddriver.KatoService; import com.netflix.spinnaker.orca.clouddriver.model.TaskId; import com.netflix.spinnaker.orca.clouddriver.pipeline.servergroup.support.TargetServerGroup; import com.netflix.spinnaker.orca.clouddriver.pipeline.servergroup.support.TargetServerGroupResolver; import com.netflix.spinnaker.orca.pipeline.model.Stage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import rx.Observable; @ExtendWith(MockitoExtension.class) class SetStatefulDiskTaskTest { private SetStatefulDiskTask task; @Mock private KatoService katoService; @Mock private TargetServerGroupResolver resolver; @BeforeEach void setUp() { task = new SetStatefulDiskTask(katoService, resolver); } @Test void success() { when(resolver.resolve(any())) .thenReturn( ImmutableList.of(new TargetServerGroup(ImmutableMap.of("name", "testapp-v000")))); when(katoService.requestOperations(any(), any())) .thenReturn(Observable.just(new TaskId("10111"))); Stage stage = new Stage(); stage.getContext().put("cloudProvider", "gce"); stage.getContext().put("credentials", "spinnaker-test"); stage.getContext().put("serverGroupName", "testapp-v000"); stage.getContext().put("region", "us-desertoasis1"); stage.getContext().put("deviceName", "testapp-v000-1"); TaskResult result = task.execute(stage); ImmutableMap<String, String> operationParams = ImmutableMap.of( "credentials", "spinnaker-test", "serverGroupName", "testapp-v000", "region", "us-desertoasis1", "deviceName", "testapp-v000-1"); verify(katoService) .requestOperations( "gce", ImmutableList.of(ImmutableMap.of("setStatefulDisk", operationParams))); assertThat(result.getContext().get("notification.type")).isEqualTo("setstatefuldisk"); assertThat(result.getContext().get("serverGroupName")).isEqualTo("testapp-v000"); assertThat(result.getContext().get("deploy.server.groups")) .isEqualTo(ImmutableMap.of("us-desertoasis1", ImmutableList.of("testapp-v000"))); } }
duftler/orca
orca-clouddriver/src/test/java/com/netflix/spinnaker/orca/clouddriver/tasks/providers/gce/SetStatefulDiskTaskTest.java
Java
apache-2.0
3,282
package com.wmc.webclient.test2; import psdi.mbo.MboRemote; import psdi.mbo.MboSetRemote; import psdi.util.MXException; import psdi.webclient.system.beans.AppBean; import psdi.webclient.system.beans.DataBean; import java.rmi.RemoteException; /** * com.wmc.webclient.test2.TestAdjustmentAppBean<br> * * @author 蒋カイセキ Japan-Tokyo 2017-12-18 17:45:472017-12-18グ17:46:03shoukaiseki.blog.163.com/<br> * E-メール jiang28555@Gmail.com<br> **/ public class TestAdjustmentAppBean extends AppBean{ public TestAdjustmentAppBean(){ super(); } @Override public int INSERT() throws MXException, RemoteException { super.INSERT(); if(sessionContext.getPreviousApp()!=null){ DataBean poBean = sessionContext.getPreviousApp().getAppBean(); MboRemote po = poBean.getMbo(); System.out.println("po.toBeAdded="+po.toBeAdded()); System.out.println("poBean."+po.getUniqueIDName()+"="+po.getUniqueIDValue()); MboSetRemote polineSet = po.getMboSet("TEST2A"); MboSetRemote prlineSet = this.app.getDataBean("testprline").getMboSet(); String[] targetAttributes = {"A", "B", "DESCRIPTION"}; String[] sourceAttributes = {"A", "B", "DESCRIPTION"}; MboRemote poline ; for (int i=0;(poline = polineSet.getMbo(i))!=null;i++){ System.out.println("polineSet.for.i="+i); MboRemote prline = prlineSet.add(); prline.setValue("TEST2ID",this.getMbo().getLong("TEST2ID"),2L); prline.copyValue(poline,sourceAttributes,targetAttributes,2L); } } return 1; } @Override public int SAVE() throws MXException, RemoteException { boolean toBeAdded = getMbo().toBeAdded(); super.SAVE(); if(sessionContext.getPreviousApp()!=null) { DataBean poBean = sessionContext.getPreviousApp().getAppBean(); String appId = sessionContext.getPreviousApp().getApp(); System.out.println("poBean.appid="+ appId); if(toBeAdded&&"TESTPO".equalsIgnoreCase(appId)){ MboSetRemote polineSet = sessionContext.getPreviousApp().getDataBean("poline").getMboSet(); MboRemote poline; MboSetRemote prlineSet=this.getMbo().getMboSet("TEST2A"); MboRemote prline; for (int i=0;(prline=prlineSet.getMbo(i))!=null;i++){ poline=polineSet.getMbo(i); if(poline!=null){ poline.setValue("DESCRIPTION",String.valueOf(prline.getLong("TEST2AID")),2L); } } } } return 1; } }
shoukaiseki/blogdoc
maximo/maximo获取上一个应用新建未保存的缓存mbo/移植sql/TestAdjustmentAppBean.java
Java
apache-2.0
2,829
package vn.com.hiringviet.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import vn.com.hiringviet.dto.MessageDTO; import vn.com.hiringviet.service.ApplyService; import vn.com.hiringviet.service.MailboxService; import vn.com.hiringviet.service.MemberService; // TODO: Auto-generated Javadoc /** * The Class MessageController. */ @Controller @RequestMapping("/api/message") public class MessageController { /** The mail box service. */ @Autowired private MailboxService mailBoxService; /** The member service. */ @Autowired private MemberService memberService; /** The apply service. */ @Autowired private ApplyService applyService; /** * Send message. * * @param message the message * @return the string */ @ResponseBody @RequestMapping(value = "/send", method = RequestMethod.POST) public String sendMessage(@ModelAttribute MessageDTO message) { mailBoxService.sendMessageViaDto(message); return "Send successfully"; } }
aholake/hiringviet
src/main/java/vn/com/hiringviet/controller/MessageController.java
Java
apache-2.0
1,334
/* * * Copyright 2015 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 springfox.documentation.schema; import com.fasterxml.classmate.ResolvedType; import com.fasterxml.classmate.types.ResolvedArrayType; import com.fasterxml.classmate.types.ResolvedPrimitiveType; import com.google.common.base.Function; import com.google.common.base.Optional; import springfox.documentation.service.AllowableValues; import springfox.documentation.spi.schema.contexts.ModelContext; import java.lang.reflect.Type; import java.util.List; import static springfox.documentation.schema.Collections.isContainerType; import static springfox.documentation.schema.Types.typeNameFor; public class ResolvedTypes { private ResolvedTypes() { throw new UnsupportedOperationException(); } public static String simpleQualifiedTypeName(ResolvedType type) { if (type instanceof ResolvedPrimitiveType) { Type primitiveType = type.getErasedType(); return typeNameFor(primitiveType); } if (type instanceof ResolvedArrayType) { return typeNameFor(type.getArrayElementType().getErasedType()); } return type.getErasedType().getName(); } public static AllowableValues allowableValues(ResolvedType resolvedType) { if (isContainerType(resolvedType)) { List<ResolvedType> typeParameters = resolvedType.getTypeParameters(); if (typeParameters != null && typeParameters.size() == 1) { return Enums.allowableValues(typeParameters.get(0).getErasedType()); } } return Enums.allowableValues(resolvedType.getErasedType()); } public static Optional<String> resolvedTypeSignature(ResolvedType resolvedType) { return Optional.fromNullable(resolvedType).transform(new Function<ResolvedType, String>() { @Override public String apply(ResolvedType input) { return input.getSignature(); } }); } public static Function<ResolvedType, ? extends ModelReference> modelRefFactory( final ModelContext parentContext, final TypeNameExtractor typeNameExtractor) { return new ModelReferenceProvider(typeNameExtractor, parentContext); } }
wjc133/springfox
springfox-schema/src/main/java/springfox/documentation/schema/ResolvedTypes.java
Java
apache-2.0
2,855
package org.jgroups.util; import org.jgroups.annotations.GuardedBy; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * A store for elements (typically messages) to be retransmitted or delivered. Used on sender and receiver side, * as a replacement for HashMap. Table should use less memory than HashMap, as HashMap.Entry has 4 fields, * plus arrays for storage. * <p/> * Table maintains a matrix (an array of arrays) of elements, which are stored in the matrix by mapping * their seqno to an index. E.g. when we have 10 rows of 1000 elements each, and first_seqno is 3000, then an element * with seqno=5600, will be stored in the 3rd row, at index 600. * <p/> * Rows are removed when all elements in that row have been received. * <p/> * Table started out as a copy of RetransmitTable, but is synchronized and maintains its own low, hd and hr * pointers, so it can be used as a replacement for NakReceiverWindow. The idea is to put messages into Table, * deliver them in order of seqnos, and periodically scan over all tables in NAKACK2 to do retransmission. * <p/> * @author Bela Ban * @version 3.1 */ public class Table<T> implements Iterable<T> { protected final int num_rows; /** Must be a power of 2 for efficient modular arithmetic **/ protected final int elements_per_row; protected final double resize_factor; protected T[][] matrix; /** The first seqno, at matrix[0][0] */ protected long offset; protected int size; /** The highest seqno purged */ protected long low; /** The highest received seqno */ protected long hr; /** The highest delivered (= removed) seqno */ protected long hd; /** Time (in nanoseconds) after which a compaction should take place. 0 disables compaction */ protected long max_compaction_time=TimeUnit.NANOSECONDS.convert(DEFAULT_MAX_COMPACTION_TIME, TimeUnit.MILLISECONDS); /** The time when the last compaction took place. If a {@link #compact()} takes place and sees that the * last compaction is more than max_compaction_time nanoseconds ago, a compaction will take place */ protected long last_compaction_timestamp=0; protected final Lock lock=new ReentrantLock(); protected final AtomicInteger adders=new AtomicInteger(0); protected int num_compactions=0, num_resizes=0, num_moves=0, num_purges=0; protected static final long DEFAULT_MAX_COMPACTION_TIME=10000; // in milliseconds protected static final double DEFAULT_RESIZE_FACTOR=1.2; public interface Visitor<T> { /** * Iteration over the table, used by {@link Table#forEach(long,long,org.jgroups.util.Table.Visitor)}. * @param seqno The current seqno * @param element The element at matrix[row][column] * @param row The current row * @param column The current column * @return True if we should continue the iteration, false if we should break out of the iteration */ boolean visit(long seqno, T element, int row, int column); } public Table() { this(5, 8192, 0, DEFAULT_RESIZE_FACTOR); } public Table(long offset) { this(); this.offset=this.low=this.hr=this.hd=offset; } public Table(int num_rows, int elements_per_row, long offset) { this(num_rows,elements_per_row, offset, DEFAULT_RESIZE_FACTOR); } public Table(int num_rows, int elements_per_row, long offset, double resize_factor) { this(num_rows,elements_per_row, offset, resize_factor, DEFAULT_MAX_COMPACTION_TIME); } /** * Creates a new table * @param num_rows the number of rows in the matrix * @param elements_per_row the number of elements per row * @param offset the seqno before the first seqno to be inserted. E.g. if 0 then the first seqno will be 1 * @param resize_factor teh factor with which to increase the number of rows * @param max_compaction_time the max time in milliseconds after we attempt a compaction */ @SuppressWarnings("unchecked") public Table(int num_rows, int elements_per_row, long offset, double resize_factor, long max_compaction_time) { this.num_rows=num_rows; this.elements_per_row=Util.getNextHigherPowerOfTwo(elements_per_row); this.resize_factor=resize_factor; this.max_compaction_time=TimeUnit.NANOSECONDS.convert(max_compaction_time, TimeUnit.MILLISECONDS); this.offset=this.low=this.hr=this.hd=offset; matrix=(T[][])new Object[num_rows][]; if(resize_factor <= 1) throw new IllegalArgumentException("resize_factor needs to be > 1"); } public AtomicInteger getAdders() {return adders;} public long getOffset() {return offset;} public int getElementsPerRow() {return elements_per_row;} /** Returns the total capacity in the matrix */ public int capacity() {return matrix.length * elements_per_row;} public int getNumCompactions() {return num_compactions;} public int getNumMoves() {return num_moves;} public int getNumResizes() {return num_resizes;} public int getNumPurges() {return num_purges;} /** Returns an appromximation of the number of elements in the table */ public int size() {return size;} public boolean isEmpty() {return size <= 0;} public long getLow() {return low;} public long getHighestDelivered() {return hd;} public long getHighestReceived() {return hr;} public long getMaxCompactionTime() {return max_compaction_time;} public void setMaxCompactionTime(long max_compaction_time) { this.max_compaction_time=TimeUnit.NANOSECONDS.convert(max_compaction_time, TimeUnit.MILLISECONDS); } public int getNumRows() {return matrix.length;} public void resetStats() {num_compactions=num_moves=num_resizes=num_purges=0;} /** Returns the highest deliverable (= removable) seqno. This may be higher than {@link #getHighestDelivered()}, * e.g. if elements have been added but not yet removed */ public long getHighestDeliverable() { HighestDeliverable visitor=new HighestDeliverable(); lock.lock(); try { forEach(hd+1, hr, visitor); long retval=visitor.getResult(); return retval == -1? hd : retval; } finally { lock.unlock(); } } /** * Only used internally by JGroups on a state transfer. Please don't use this in application code, or you're on * your own ! * @param seqno */ public void setHighestDelivered(long seqno) { lock.lock(); try { hd=seqno; } finally { lock.unlock(); } } /** * Adds an element if the element at the given index is null. Returns true if no element existed at the given index, * else returns false and doesn't set the element. * @param seqno * @param element * @return True if the element at the computed index was null, else false */ public boolean add(long seqno, T element) { lock.lock(); try { return _add(seqno, element, true, null); } finally { lock.unlock(); } } /** * Adds an element if the element at the given index is null. Returns true if no element existed at the given index, * else returns false and doesn't set the element. * @param seqno * @param element * @param remove_filter If not null, a filter used to remove all consecutive messages passing the filter * @return True if the element at the computed index was null, else false */ public boolean add(long seqno, T element, Predicate<T> remove_filter) { lock.lock(); try { return _add(seqno, element, true, remove_filter); } finally { lock.unlock(); } } /** * Adds elements from list to the table * @param list * @return True if at least 1 element was added successfully */ public boolean add(final List<LongTuple<T>> list) { return add(list, false); } /** * Adds elements from list to the table, removes elements from list that were not added to the table * @param list * @return True if at least 1 element was added successfully. This guarantees that the list has at least 1 element */ public boolean add(final List<LongTuple<T>> list, boolean remove_added_elements) { return add(list, remove_added_elements, null); } /** * Adds elements from the list to the table * @param list The list of tuples of seqnos and elements. If remove_added_elements is true, if elements could * not be added to the table (e.g. because they were already present or the seqno was < HD), those * elements will be removed from list * @param remove_added_elements If true, elements that could not be added to the table are removed from list * @param const_value If non-null, this value should be used rather than the values of the list tuples * @return True if at least 1 element was added successfully, false otherwise. */ public boolean add(final List<LongTuple<T>> list, boolean remove_added_elements, T const_value) { if(list == null || list.isEmpty()) return false; boolean added=false; // find the highest seqno (unfortunately, the list is not ordered by seqno) long highest_seqno=findHighestSeqno(list); lock.lock(); try { if(highest_seqno != -1 && computeRow(highest_seqno) >= matrix.length) resize(highest_seqno); for(Iterator<LongTuple<T>> it=list.iterator(); it.hasNext();) { LongTuple<T> tuple=it.next(); long seqno=tuple.getVal1(); T element=const_value != null? const_value : tuple.getVal2(); if(_add(seqno, element, false, null)) added=true; else if(remove_added_elements) it.remove(); } return added; } finally { lock.unlock(); } } /** * Returns an element at seqno * @param seqno * @return */ public T get(long seqno) { lock.lock(); try { if(seqno - low <= 0 || seqno - hr > 0) return null; int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; T[] row=matrix[row_index]; if(row == null) return null; int index=computeIndex(seqno); return index >= 0? row[index] : null; } finally { lock.unlock(); } } /** * To be used only for testing; doesn't do any index or sanity checks * @param seqno * @return */ public T _get(long seqno) { lock.lock(); try { int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; T[] row=matrix[row_index]; if(row == null) return null; int index=computeIndex(seqno); return index >= 0? row[index] : null; } finally { lock.unlock(); } } public T remove() { return remove(true); } /** Removes the next non-null element and nulls the index if nullify=true */ public T remove(boolean nullify) { lock.lock(); try { int row_index=computeRow(hd+1); if(row_index < 0 || row_index >= matrix.length) return null; T[] row=matrix[row_index]; if(row == null) return null; int index=computeIndex(hd+1); if(index < 0) return null; T existing_element=row[index]; if(existing_element != null) { hd++; size=Math.max(size-1, 0); // cannot be < 0 (well that would be a bug, but let's have this 2nd line of defense !) if(nullify) { row[index]=null; if(hd - low > 0) low=hd; } } return existing_element; } finally { lock.unlock(); } } public List<T> removeMany(boolean nullify, int max_results) { return removeMany(nullify, max_results, null); } public List<T> removeMany(boolean nullify, int max_results, Predicate<T> filter) { return removeMany(nullify, max_results, filter, LinkedList::new, LinkedList::add); } /** * Removes elements from the table and adds them to the result created by result_creator. Between 0 and max_results * elements are removed. If no elements were removed, processing will be set to true while the table lock is held. * @param nullify if true, the x,y location of the removed element in the matrix will be nulled * @param max_results the max number of results to be returned, even if more elements would be removable * @param filter a filter which accepts (or rejects) elements into the result. If null, all elements will be accepted * @param result_creator a supplier required to create the result, e.g. ArrayList::new * @param accumulator an accumulator accepting the result and an element, e.g. ArrayList::add * @param <R> the type of the result * @return the result */ public <R> R removeMany(boolean nullify, int max_results, Predicate<T> filter, Supplier<R> result_creator, BiConsumer<R,T> accumulator) { lock.lock(); try { Remover<R> remover=new Remover<>(nullify, max_results, filter, result_creator, accumulator); forEach(hd+1, hr, remover); return remover.getResult(); } finally { lock.unlock(); } } /** * Removes all elements less than or equal to seqno from the table. Does this by nulling entire rows in the matrix * and nulling all elements < index(seqno) of the first row that cannot be removed * @param seqno */ public void purge(long seqno) { purge(seqno, false); } /** * Removes all elements less than or equal to seqno from the table. Does this by nulling entire rows in the matrix * and nulling all elements < index(seqno) of the first row that cannot be removed. * @param seqno All elements <= seqno will be nulled * @param force If true, we only ensure that seqno <= hr, but don't care about hd, and set hd=low=seqno. */ public void purge(long seqno, boolean force) { lock.lock(); try { if(seqno - low <= 0) return; if(force) { if(seqno - hr > 0) seqno=hr; } else { if(seqno - hd > 0) // we cannot be higher than the highest removed seqno seqno=hd; } int start_row=computeRow(low), end_row=computeRow(seqno); if(start_row < 0) start_row=0; if(end_row < 0) return; for(int i=start_row; i < end_row; i++) // Null all rows which can be fully removed matrix[i]=null; if(matrix[end_row] != null) { int index=computeIndex(seqno); for(int i=0; i <= index; i++) // null all elements up to and including seqno in the given row matrix[end_row][i]=null; } if(seqno - low > 0) low=seqno; if(force) { if(seqno - hd > 0) low=hd=seqno; size=computeSize(); } num_purges++; if(max_compaction_time <= 0) // see if compaction should be triggered return; long current_time=System.nanoTime(); if(last_compaction_timestamp > 0) { if(current_time - last_compaction_timestamp >= max_compaction_time) { _compact(); last_compaction_timestamp=current_time; } } else // the first time we don't do a compaction last_compaction_timestamp=current_time; } finally { lock.unlock(); } } public void compact() { lock.lock(); try { _compact(); } finally { lock.unlock(); } } /** * Iterates over the matrix with range [from .. to] (including from and to), and calls * {@link Visitor#visit(long,Object,int,int)}. If the visit() method returns false, the iteration is terminated. * <p/> * This method must be called with the lock held * @param from The starting seqno * @param to The ending seqno, the range is [from .. to] including from and to * @param visitor An instance of Visitor */ @GuardedBy("lock") public void forEach(long from, long to, Visitor<T> visitor) { if(from - to > 0) // same as if(from > to), but prevents long overflow return; int row=computeRow(from), column=computeIndex(from); int distance=(int)(to - from +1); T[] current_row=row+1 > matrix.length? null : matrix[row]; for(int i=0; i < distance; i++) { T element=current_row == null? null : current_row[column]; if(!visitor.visit(from, element, row, column)) break; from++; if(++column >= elements_per_row) { column=0; row++; current_row=row+1 > matrix.length? null : matrix[row]; } } } public Iterator<T> iterator() { return new TableIterator(); } public Iterator<T> iterator(long from, long to) { return new TableIterator(from, to); } public Stream<T> stream() { Spliterator<T> sp=Spliterators.spliterator(iterator(), size(), 0); return StreamSupport.stream(sp, false); } public Stream<T> stream(long from, long to) { Spliterator<T> sp=Spliterators.spliterator(iterator(from, to), size(), 0); return StreamSupport.stream(sp, false); } protected boolean _add(long seqno, T element, boolean check_if_resize_needed, Predicate<T> remove_filter) { if(seqno - hd <= 0) return false; int row_index=computeRow(seqno); if(check_if_resize_needed && row_index >= matrix.length) { resize(seqno); row_index=computeRow(seqno); } T[] row=getRow(row_index); int index=computeIndex(seqno); T existing_element=row[index]; if(existing_element == null) { row[index]=element; size++; if(seqno - hr > 0) hr=seqno; if(remove_filter != null && hd +1 == seqno) { forEach(hd + 1, hr, (seq, msg, r, c) -> { if(msg == null || !remove_filter.test(msg)) return false; if(seq - hd > 0) hd=seq; size=Math.max(size-1, 0); // cannot be < 0 (well that would be a bug, but let's have this 2nd line of defense !) return true; }); } return true; } return false; } // list must not be null or empty protected long findHighestSeqno(List<LongTuple<T>> list) { long seqno=-1; for(LongTuple<T> tuple: list) { long val=tuple.getVal1(); if(val - seqno > 0) seqno=val; } return seqno; } /** Moves rows down the matrix, by removing purged rows. If resizing to accommodate seqno is still needed, computes * a new size. Then either moves existing rows down, or copies them into a new array (if resizing took place). * The lock must be held by the caller of resize(). */ @SuppressWarnings("unchecked") @GuardedBy("lock") protected void resize(long seqno) { int num_rows_to_purge=computeRow(low); int row_index=computeRow(seqno) - num_rows_to_purge; if(row_index < 0) return; int new_size=Math.max(row_index +1, matrix.length); if(new_size > matrix.length) { T[][] new_matrix=(T[][])new Object[new_size][]; System.arraycopy(matrix, num_rows_to_purge, new_matrix, 0, matrix.length - num_rows_to_purge); matrix=new_matrix; num_resizes++; } else if(num_rows_to_purge > 0) { move(num_rows_to_purge); } offset+=(num_rows_to_purge * elements_per_row); } /** Moves contents of matrix num_rows down. Avoids a System.arraycopy(). Caller must hold the lock. */ @GuardedBy("lock") protected void move(int num_rows) { if(num_rows <= 0 || num_rows > matrix.length) return; int target_index=0; for(int i=num_rows; i < matrix.length; i++) matrix[target_index++]=matrix[i]; for(int i=matrix.length - num_rows; i < matrix.length; i++) matrix[i]=null; num_moves++; } /** * Moves the contents of matrix down by the number of purged rows and resizes the matrix accordingly. The * capacity of the matrix should be size * resize_factor. Caller must hold the lock. */ @SuppressWarnings("unchecked") @GuardedBy("lock") protected void _compact() { // This is the range we need to copy into the new matrix (including from and to) int from=computeRow(low), to=computeRow(hr); int range=to - from +1; // e.g. from=3, to=5, new_size has to be [3 .. 5] (=3) int new_size=(int)Math.max( (double)range * resize_factor, (double) range +1 ); new_size=Math.max(new_size, num_rows); // don't fall below the initial size defined if(new_size < matrix.length) { T[][] new_matrix=(T[][])new Object[new_size][]; System.arraycopy(matrix, from, new_matrix, 0, range); matrix=new_matrix; offset+=from * elements_per_row; num_compactions++; } } /** Iterate from low to hr and add up non-null values. Caller must hold the lock. */ @GuardedBy("lock") public int computeSize() { return (int)stream().filter(Objects::nonNull).count(); } /** Returns the number of null elements in the range [hd+1 .. hr-1] excluding hd and hr */ public int getNumMissing() { lock.lock(); try { return (int)(hr - hd - size); } finally { lock.unlock(); } } /** * Returns a list of missing (= null) elements * @return A SeqnoList of missing messages, or null if no messages are missing */ public SeqnoList getMissing() { return getMissing(0); } /** * Returns a list of missing messages * @param max_msgs If > 0, the max number of missing messages to be returned (oldest first), else no limit * @return A SeqnoList of missing messages, or null if no messages are missing */ public SeqnoList getMissing(int max_msgs) { lock.lock(); try { if(size == 0) return null; long start_seqno=getHighestDeliverable() +1; int capacity=(int)(hr - start_seqno); int max_size=max_msgs > 0? Math.min(max_msgs, capacity) : capacity; if(max_size <= 0) return null; Missing missing=new Missing(start_seqno, capacity, max_size); forEach(start_seqno, hr-1, missing); return missing.getMissingElements(); } finally { lock.unlock(); } } public long[] getDigest() { lock.lock(); try { return new long[]{hd,hr}; } finally { lock.unlock(); } } public String toString() { StringBuilder sb=new StringBuilder(); sb.append("[" + low + " | " + hd + " | " + hr + "] (" + size() + " elements, " + getNumMissing() + " missing)"); return sb.toString(); } /** Dumps the seqnos in the table as a list */ public String dump() { lock.lock(); try { return stream(low, hr).filter(Objects::nonNull).map(Object::toString) .collect(Collectors.joining(", ")); } finally { lock.unlock(); } } /** * Returns a row. Creates a new row and inserts it at index if the row at index doesn't exist * @param index * @return A row */ @SuppressWarnings("unchecked") @GuardedBy("lock") protected T[] getRow(int index) { T[] row=matrix[index]; if(row == null) { row=(T[])new Object[elements_per_row]; matrix[index]=row; } return row; } /** Computes and returns the row index for seqno. The caller must hold the lock. */ // Note that seqno-offset is never > Integer.MAX_VALUE and thus doesn't overflow into a negative long, // as offset is always adjusted in resize() or compact(). Even if it was negative, callers of computeRow() will // ignore the result or throw an ArrayIndexOutOfBound exception @GuardedBy("lock") protected int computeRow(long seqno) { int diff=(int)(seqno-offset); if(diff < 0) return diff; return diff / elements_per_row; } /** Computes and returns the index within a row for seqno */ // Note that seqno-offset is never > Integer.MAX_VALUE and thus doesn't overflow into a negative long, // as offset is always adjusted in resize() or compact(). Even if it was negative, callers of computeIndex() will // ignore the result or throw an ArrayIndexOutOfBound exception @GuardedBy("lock") protected int computeIndex(long seqno) { int diff=(int)(seqno - offset); if(diff < 0) return diff; return diff & (elements_per_row - 1); // same as mod, but (apparently, I'm told) more efficient } /** * Iterates through all elements of the matrix. The range (from-to) can be defined, default is [hd+1 .. hr] (incl hr). * Matrix compactions and resizings will lead to undefined results, as this iterator doesn't maintain a separate ref * of the matrix, so it is best to run this with the lock held. This iterator is also used by {@link #stream()} */ protected class TableIterator implements Iterator<T> { protected int row, column; protected T[] current_row; protected long from; protected final long to; protected TableIterator() { this(hd+1, hr); } protected TableIterator(final long from, final long to) { //if(from - to > 0) // same as if(from > to), but prevents long overflow // throw new IllegalArgumentException(String.format("range [%d .. %d] invalid", from, to)); this.from=from; this.to=to; row=computeRow(from); column=computeIndex(from); current_row=row+1 > matrix.length? null : matrix[row]; } public boolean hasNext() { return to - from >= 0; } public T next() { if(row > matrix.length) throw new NoSuchElementException(String.format("row (%d) is > matrix.length (%d)", row, matrix.length)); T element=current_row == null? null : current_row[column]; from++; if(++column >= elements_per_row) { column=0; row++; current_row=row+1 > matrix.length? null : matrix[row]; } return element; } } protected class Remover<R> implements Visitor<T> { protected final boolean nullify; protected final int max_results; protected int num_results; protected final Predicate<T> filter; protected R result; protected Supplier<R> result_creator; protected BiConsumer<R,T> result_accumulator; public Remover(boolean nullify, int max_results, Predicate<T> filter, Supplier<R> creator, BiConsumer<R,T> accumulator) { this.nullify=nullify; this.max_results=max_results; this.filter=filter; this.result_creator=creator; this.result_accumulator=accumulator; } public R getResult() {return result;} @GuardedBy("lock") public boolean visit(long seqno, T element, int row, int column) { if(element != null) { if(filter == null || filter.test(element)) { if(result == null) result=result_creator.get(); result_accumulator.accept(result, element); num_results++; } if(seqno - hd > 0) hd=seqno; size=Math.max(size-1, 0); // cannot be < 0 (well that would be a bug, but let's have this 2nd line of defense !) if(nullify) { matrix[row][column]=null; // if we're nulling the last element of a row, null the row as well if(column == elements_per_row-1) matrix[row]=null; if(seqno - low > 0) low=seqno; } return max_results == 0 || num_results < max_results; } return false; } } protected class Missing implements Visitor<T> { protected final SeqnoList missing_elements; protected final int max_num_msgs; protected int num_msgs; protected Missing(long start, int capacity, int max_number_of_msgs) { missing_elements=new SeqnoList(capacity, start); this.max_num_msgs=max_number_of_msgs; } protected SeqnoList getMissingElements() {return missing_elements;} public boolean visit(long seqno, T element, int row, int column) { if(element == null) { if(++num_msgs > max_num_msgs) return false; missing_elements.add(seqno); } return true; } } protected class HighestDeliverable implements Visitor<T> { protected long highest_deliverable=-1; public long getResult() {return highest_deliverable;} public boolean visit(long seqno, T element, int row, int column) { if(element == null) return false; highest_deliverable=seqno; return true; } } }
danberindei/JGroups
src/org/jgroups/util/Table.java
Java
apache-2.0
32,001
/******************************************************************************* * Copyright 2015 MobileMan GmbH * www.mobileman.com * * 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. ******************************************************************************/ /** * PatientQuestionAnswerHolder.java * * Project: projecth * * @author mobileman * @date 8.2.2011 * @version 1.0 * * (c) 2010 MobileMan GmbH */ package com.mobileman.projecth.domain.util.patient.questionary; /** * @author mobileman * */ public class PatientQuestionAnswerHolder { private Long haqId; private Long questionId; private Long answerId; private String customAnswer; /** * @param haqId * @param questionId * @param answerId * @param customAnswer */ public PatientQuestionAnswerHolder(Long haqId, Long questionId, Long answerId, String customAnswer) { super(); this.haqId = haqId; this.questionId = questionId; this.answerId = answerId; this.customAnswer = customAnswer; } /** * */ public PatientQuestionAnswerHolder() { super(); } /** * @return questionId */ public Long getQuestionId() { return this.questionId; } /** * @param questionId new value of questionId */ public void setQuestionId(Long questionId) { this.questionId = questionId; } /** * @return answerId */ public Long getAnswerId() { return this.answerId; } /** * @param answerId new value of answerId */ public void setAnswerId(Long answerId) { this.answerId = answerId; } /** * @return customAnswer */ public String getCustomAnswer() { return this.customAnswer; } /** * @param customAnswer new value of customAnswer */ public void setCustomAnswer(String customAnswer) { this.customAnswer = customAnswer; } /** * @return haqId */ public Long getHaqId() { return this.haqId; } /** * @param haqId new value of haqId */ public void setHaqId(Long haqId) { this.haqId = haqId; } }
MobileManAG/Project-H-Backend
src/main/java/com/mobileman/projecth/domain/util/patient/questionary/PatientQuestionAnswerHolder.java
Java
apache-2.0
2,477
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.exceptions; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.classification.InterfaceStability; import org.apache.hadoop.hbase.RegionException; /** * Thrown when something is wrong in trying to merge two regions. */ @InterfaceAudience.Public @InterfaceStability.Stable public class MergeRegionException extends RegionException { private static final long serialVersionUID = 4970899110066124122L; /** default constructor */ public MergeRegionException() { super(); } /** * Constructor * @param s message */ public MergeRegionException(String s) { super(s); } }
Jackygq1982/hbase_src
hbase-client/src/main/java/org/apache/hadoop/hbase/exceptions/MergeRegionException.java
Java
apache-2.0
1,484
package executor; import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; import org.antlr.v4.runtime.tree.TerminalNode; import python.object.*; import python.scope.SymbolTable; import python.statement.*; import java.util.*; import java.util.stream.Collectors; public class PythonVisitor implements Python3Visitor<Statement> { public Map<String, PythonFunction> functions = new HashMap<>(); { List<Statement> statements = new ArrayList<>(); PrintStatement printStatement = new PrintStatement(); printStatement.setName("x"); statements.add(printStatement); Map<String, ExpressionTree> trees = new LinkedHashMap<>(); ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node n = new ExpressionTree.Node(); n.object = new PythonInteger(10); tree.setRoot(n); trees.put("x", tree); ParametersStatement statement = new ParametersStatement(trees); PythonFunction function = new PythonFunction("print", new StatementBlock(statements), statement); functions.put("print", function); } @Override public Statement visitTestlist(@NotNull Python3Parser.TestlistContext ctx) { List<ExpressionTree> trees = new ArrayList<>(); for (int i = 0; i < ctx.test().size(); i++) { trees.add((ExpressionTree) visitTest(ctx.test(i))); } return new TestListStatement(trees); } @Override public Statement visitAssert_stmt(@NotNull Python3Parser.Assert_stmtContext ctx) { return null; } @Override public Statement visitArgument(@NotNull Python3Parser.ArgumentContext ctx) { if ( ctx.test().size() == 1 ) { return new ArgumentStatement(ArgumentStatement.notExist, (ExpressionTree) visitTest(ctx.test(0))); } return new ArgumentStatement(ctx.test(0).getText(), (ExpressionTree) visitTest(ctx.test(1))); } @Override public Statement visitNot_test(@NotNull Python3Parser.Not_testContext ctx) { if ( ctx.not_test() == null ) { BooleanTree tree = new BooleanTree(null); BooleanTree.Node node = new BooleanTree.Node(); node.statement = (ComparisonStatement) visitComparison(ctx.comparison()); tree.setRoot(node); return new TestStatement(tree); } TestStatement testStatement = (TestStatement) visitNot_test(ctx.not_test()); testStatement.getTree().getRoot().statement.flipNot(); return testStatement; } @Override public Statement visitFile_input(@NotNull Python3Parser.File_inputContext ctx) { return null; } @Override public Statement visitXor_expr(@NotNull Python3Parser.Xor_exprContext ctx) { if ( ctx.and_expr().size() == 1 ) { return visitAnd_expr(ctx.and_expr(0)); } ExpressionTree tree = new ExpressionTree("^"); for (int i = 0; i < ctx.and_expr().size(); i++) { tree.addChild((ExpressionTree) visitAnd_expr(ctx.and_expr(i))); } return tree; } @Override public Statement visitInteger(@NotNull Python3Parser.IntegerContext ctx) { return new PythonInteger(ctx.getText()); } @Override public Statement visitImport_from(@NotNull Python3Parser.Import_fromContext ctx) { return null; } @Override public Statement visitSingle_input(@NotNull Python3Parser.Single_inputContext ctx) { return null; } @Override public Statement visitDecorated(@NotNull Python3Parser.DecoratedContext ctx) { return null; } @Override public Statement visitWith_item(@NotNull Python3Parser.With_itemContext ctx) { return null; } @Override public Statement visitRaise_stmt(@NotNull Python3Parser.Raise_stmtContext ctx) { return new ReturnStatement(new TestListStatement(new ArrayList<>())); } @Override public Statement visitImport_as_name(@NotNull Python3Parser.Import_as_nameContext ctx) { return null; } @Override public Statement visitExcept_clause(@NotNull Python3Parser.Except_clauseContext ctx) { return null; } @Override public Statement visitCompound_stmt(@NotNull Python3Parser.Compound_stmtContext ctx) { if ( ctx.if_stmt() != null ) { return visitIf_stmt(ctx.if_stmt()); } if ( ctx.while_stmt() != null ) { return visitWhile_stmt(ctx.while_stmt()); } if ( ctx.for_stmt() != null ) { return visitFor_stmt(ctx.for_stmt()); } if ( ctx.try_stmt() != null ) { return visitTry_stmt(ctx.try_stmt()); } if ( ctx.classdef() != null ) { return visitClassdef(ctx.classdef()); } if ( ctx.funcdef() != null ) { return visitFuncdef(ctx.funcdef()); } if ( ctx.with_stmt() != null ) { return visitWith_stmt(ctx.with_stmt()); } if ( ctx.decorated() != null ) { return visitDecorated(ctx.decorated()); } return null; } @Override public Statement visitNumber(@NotNull Python3Parser.NumberContext ctx) { ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node node = new ExpressionTree.Node(); if ( ctx.integer() != null ) { node.object = (PythonObject) visitInteger(ctx.integer()); } if ( ctx.FLOAT_NUMBER() != null ) { node.object = new PythonFloat(ctx.FLOAT_NUMBER().getText()); } else if ( ctx.IMAG_NUMBER() != null ) { node.object = new PythonComplex(ctx.IMAG_NUMBER().getText()); } tree.setRoot(node); return tree; } @Override public Statement visitAnd_expr(@NotNull Python3Parser.And_exprContext ctx) { if ( ctx.shift_expr().size() == 1 ) { return visitShift_expr(ctx.shift_expr(0)); } ExpressionTree tree = new ExpressionTree("&"); for (int i = 0; i < ctx.shift_expr().size(); i++) { tree.addChild((ExpressionTree) visitShift_expr(ctx.shift_expr(i))); } return tree; } @Override public Statement visitLambdef_nocond(@NotNull Python3Parser.Lambdef_nocondContext ctx) { return null; } @Override public Statement visitDictorsetmaker(@NotNull Python3Parser.DictorsetmakerContext ctx) { return null; } @Override public Statement visitReturn_stmt(@NotNull Python3Parser.Return_stmtContext ctx) { return new ReturnStatement((TestListStatement) visitTestlist(ctx.testlist())); } @Override public Statement visitDotted_name(@NotNull Python3Parser.Dotted_nameContext ctx) { return null; } @Override public Statement visitFlow_stmt(@NotNull Python3Parser.Flow_stmtContext ctx) { if ( ctx.break_stmt() != null ) { return visitBreak_stmt(ctx.break_stmt()); } if ( ctx.continue_stmt() != null ) { return visitContinue_stmt(ctx.continue_stmt()); } if ( ctx.return_stmt() != null ) { return visitReturn_stmt(ctx.return_stmt()); } if ( ctx.raise_stmt() != null ) { return visitRaise_stmt(ctx.raise_stmt()); } if ( ctx.yield_stmt() != null ) { return visitYield_stmt(ctx.yield_stmt()); } return null; } @Override public Statement visitWhile_stmt(@NotNull Python3Parser.While_stmtContext ctx) { TestStatement conditionStatement = (TestStatement) visitTest(ctx.test()); StatementBlock statementBlock = (StatementBlock) visitSuite(ctx.suite(0)); return new WhileStatement(conditionStatement, statementBlock); } @Override public Statement visitOr_test(@NotNull Python3Parser.Or_testContext ctx) { if ( ctx.OR().size() == 0 ) { return visitAnd_test(ctx.and_test(0)); } BooleanTree tree = new BooleanTree("or"); for (int i = 0; i < ctx.and_test().size(); i++) { Statement statement = visitAnd_test(ctx.and_test(i)); if ( statement instanceof TestStatement ) tree.addChild(((TestStatement)statement).getTree()); else tree.addChild((ExpressionTree) statement); } return new TestStatement(tree); } @Override public Statement visitComparison(@NotNull Python3Parser.ComparisonContext ctx) { if ( ctx.star_expr().size() == 1 ) { List<ExpressionTree> trees = new ArrayList<>(); trees.add((ExpressionTree) visitStar_expr(ctx.star_expr(0))); return new ComparisonStatement(new ArrayList<>(), trees); } List<String> ops = new ArrayList<>(); List<ExpressionTree> trees = new ArrayList<>(); trees.add((ExpressionTree) visitStar_expr(ctx.star_expr(0))); trees.add((ExpressionTree) visitStar_expr(ctx.star_expr(1))); String str = ((ContianerStatement) visitComp_op(ctx.comp_op(0))).getValue().toString(); ops.add(str); for (int i = 1; i < ctx.comp_op().size(); i++) { str = ((ContianerStatement) visitComp_op(ctx.comp_op(i))).getValue().toString(); ops.add(str); trees.add((ExpressionTree) visitStar_expr(ctx.star_expr(i + 1))); } return new ComparisonStatement(ops, trees); } @Override public Statement visitTest(@NotNull Python3Parser.TestContext ctx) { return visitOr_test(ctx.or_test(0)); } @Override public Statement visitSubscript(@NotNull Python3Parser.SubscriptContext ctx) { return visitTest(ctx.test(0)); } @Override public Statement visitComp_for(@NotNull Python3Parser.Comp_forContext ctx) { return null; } @Override public Statement visitYield_arg(@NotNull Python3Parser.Yield_argContext ctx) { return null; } @Override public Statement visitYield_expr(@NotNull Python3Parser.Yield_exprContext ctx) { return null; } @Override public Statement visitImport_stmt(@NotNull Python3Parser.Import_stmtContext ctx) { return null; } @Override public Statement visitShift_expr(@NotNull Python3Parser.Shift_exprContext ctx) { if ( ctx.arith_expr().size() == 1 ) { return visitArith_expr(ctx.arith_expr(0)); } ExpressionTree tree = new ExpressionTree(ctx.opss.get(0).getText()); tree.addChild((ExpressionTree) visitArith_expr(ctx.arith_expr(0))); tree.addChild((ExpressionTree) visitArith_expr(ctx.arith_expr(1))); for (int i = 1; i < ctx.opss.size(); i++) { ExpressionTree tree1 = new ExpressionTree(ctx.opss.get(i).getText()); tree1.addChild((ExpressionTree) visitArith_expr(ctx.arith_expr(i + 1))); tree.addChild(tree1); } return tree; } @Override public Statement visitLambdef(@NotNull Python3Parser.LambdefContext ctx) { return null; } @Override public Statement visitAnd_test(@NotNull Python3Parser.And_testContext ctx) { if ( ctx.AND().size() == 0 ) { return visitNot_test(ctx.not_test(0)); } BooleanTree tree = new BooleanTree("and"); for (int i = 0; i < ctx.not_test().size(); i++) { Statement statement = visitNot_test(ctx.not_test(i)); if ( statement instanceof TestStatement ) tree.addChild(((TestStatement)statement).getTree()); else { tree.addChild((ExpressionTree) statement); } } return new TestStatement(tree); } @Override public Statement visitGlobal_stmt(@NotNull Python3Parser.Global_stmtContext ctx) { List<String> vars = new ArrayList<>(); for (int i = 0; i < ctx.NAME().size(); i++) { vars.add(ctx.NAME(i).getText()); } return new GlobalStatement(vars); } @Override public Statement visitImport_as_names(@NotNull Python3Parser.Import_as_namesContext ctx) { return null; } @Override public Statement visitDecorators(@NotNull Python3Parser.DecoratorsContext ctx) { return null; } @Override public Statement visitTry_stmt(@NotNull Python3Parser.Try_stmtContext ctx) { return new TryStatement((StatementBlock) visitSuite(ctx.suite(0)), (StatementBlock) visitSuite(ctx.suite(1))); } @Override public Statement visitComp_op(@NotNull Python3Parser.Comp_opContext ctx) { return new ContianerStatement(ctx.getText()); } @Override public Statement visitStar_expr(@NotNull Python3Parser.Star_exprContext ctx) { return visitExpr(ctx.expr()); } @Override public Statement visitBreak_stmt(@NotNull Python3Parser.Break_stmtContext ctx) { return new BreakStatement(); } @Override public Statement visitParameters(@NotNull Python3Parser.ParametersContext ctx) { if ( ctx.getText().equals("()") ) { return new ParametersStatement(new LinkedHashMap<>()); } return visitTypedargslist(ctx.typedargslist()); } @Override public Statement visitDecorator(@NotNull Python3Parser.DecoratorContext ctx) { return null; } @Override public Statement visitTfpdef(@NotNull Python3Parser.TfpdefContext ctx) { return null; } @Override public Statement visitString(@NotNull Python3Parser.StringContext ctx) { ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node node = new ExpressionTree.Node(); node.object = new PythonString(ctx.STRING_LITERAL().getText()); tree.setRoot(node); return tree; } @Override public Statement visitTestlist_comp(@NotNull Python3Parser.Testlist_compContext ctx) { return null; } @Override public Statement visitIf_stmt(@NotNull Python3Parser.If_stmtContext ctx) { List<TestStatement> testStatements = new ArrayList<>(); List<StatementBlock> blocks = new ArrayList<>(); for (int i = 0; i < ctx.elifTest.size(); i++) { testStatements.add((TestStatement) visitTest(ctx.elifTest.get(i))); blocks.add((StatementBlock) visitSuite(ctx.suite(i + 1))); } StatementBlock b = null; if ( ctx.ELSE() != null ) { b = (StatementBlock) visitSuite(ctx.elseSuite); } TestStatement ifTest = (TestStatement) visitTest(ctx.test().get(0)); return new IfStatement(ifTest, (StatementBlock) visitSuite(ctx.suite().get(0)), b, testStatements, blocks); } @Override public Statement visitWith_stmt(@NotNull Python3Parser.With_stmtContext ctx) { return null; } @Override public Statement visitClassdef(@NotNull Python3Parser.ClassdefContext ctx) { return null; } @Override public Statement visitExprlist(@NotNull Python3Parser.ExprlistContext ctx) { return null; } @Override public Statement visitSmall_stmt(@NotNull Python3Parser.Small_stmtContext ctx) { if ( ctx.global_stmt() != null ) { return visitGlobal_stmt(ctx.global_stmt()); } if ( ctx.expr_stmt() != null ) { return visitExpr_stmt(ctx.expr_stmt()); } if ( ctx.flow_stmt() != null ) { return visitFlow_stmt(ctx.flow_stmt()); } if ( ctx.global_stmt() != null ) { return visitGlobal_stmt(ctx.global_stmt()); } if ( ctx.pass_stmt() != null ) { return visitPass_stmt(ctx.pass_stmt()); } if ( ctx.del_stmt() != null ) { return visitDel_stmt(ctx.del_stmt()); } return null; } @Override public Statement visitTrailer(@NotNull Python3Parser.TrailerContext ctx) { if(ctx.getText().equals("()")) return new ArgumentListStatement(new ArrayList<>()); return visitArglist(ctx.arglist()); } @Override public Statement visitDotted_as_names(@NotNull Python3Parser.Dotted_as_namesContext ctx) { return null; } @Override public Statement visitArith_expr(@NotNull Python3Parser.Arith_exprContext ctx) { if ( ctx.term().size() == 1 ) { return visitTerm(ctx.term(0)); } ExpressionTree tree = new ExpressionTree(ctx.opss.get(0).getText()); ExpressionTree tt = (ExpressionTree) visitTerm(ctx.term(0)); tree.addChild(tt); tt = (ExpressionTree) visitTerm(ctx.term(1)); tree.addChild(tt); for (int i = 1; i < ctx.opss.size(); i++) { ExpressionTree tree1 = new ExpressionTree(ctx.opss.get(i).getText()); tree1.addChild((ExpressionTree) visitTerm(ctx.term(i + 1))); tree.addChild(tree1); } return tree; } @Override public Statement visitArglist(@NotNull Python3Parser.ArglistContext ctx) { List<ArgumentStatement> statements = new ArrayList<>(); for (int i = 0; i < ctx.argument().size(); i++) { statements.add((ArgumentStatement) visitArgument(ctx.argument(i))); } return new ArgumentListStatement(statements); } @Override public Statement visitSimple_stmt(@NotNull Python3Parser.Simple_stmtContext ctx) { List<Statement> statements = new ArrayList<>(); for (int i = 0; i < ctx.small_stmt().size(); i++) { Statement statement = visitSmall_stmt(ctx.small_stmt(i)); statements.add(statement); } return new StatementBlock(statements); } @Override public Statement visitTypedargslist(@NotNull Python3Parser.TypedargslistContext ctx) { Map<String, ExpressionTree> map = new LinkedHashMap<>(); if ( ctx.test(0) != null ) { map.put(ctx.tfpdef(0).NAME().getText(), (ExpressionTree) visitTest(ctx.test(0))); } for (int i = 1; i < ctx.tfpdef().size(); i++) { if ( i >= ctx.test().size() ) { map.put(ctx.tfpdef().get(i).NAME().getText(), new ExpressionTree(null)); break; } map.put(ctx.tfpdef().get(i).NAME().getText(), (ExpressionTree) visitTest(ctx.test(i))); } return new ParametersStatement(map); } @Override public Statement visitExpr(@NotNull Python3Parser.ExprContext ctx) { if ( ctx.xor_expr().size() == 1 ) { return visitXor_expr(ctx.xor_expr(0)); } ExpressionTree tree = new ExpressionTree("|"); for (int i = 0; i < ctx.xor_expr().size(); i++) { tree.addChild((ExpressionTree) visitXor_expr(ctx.xor_expr(i))); } return tree; } @Override public Statement visitTerm(@NotNull Python3Parser.TermContext ctx) { if ( ctx.factor().size() == 1 ) { return visitFactor(ctx.factor(0)); } ExpressionTree tree = new ExpressionTree(ctx.opss.get(0).getText()); tree.addChild((ExpressionTree) visitFactor(ctx.factor(0))); tree.addChild((ExpressionTree) visitFactor(ctx.factor(1))); for (int i = 1; i < ctx.opss.size(); i++) { ExpressionTree tree1 = new ExpressionTree(ctx.opss.get(i).getText()); tree1.addChild((ExpressionTree) visitFactor(ctx.factor(i + 1))); tree.addChild(tree1); } return tree; } @Override public Statement visitPower(@NotNull Python3Parser.PowerContext ctx) { if ( ctx.trailer() != null && ctx.trailer().size() > 0) { ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node node = new ExpressionTree.Node(); PythonFunction function = functions.get(ctx.atom().getText()); node.object = function; ArgumentListStatement argumentListStatement = (ArgumentListStatement) visitTrailer(ctx.trailer().get(0)); tree.setRoot(node); function.setParameters(argumentListStatement); SymbolTable.beginScope(ctx.atom().getText(), SymbolTable.ScopeType.FUNCTION); return tree; } return visitAtom(ctx.atom()); } @Override public Statement visitDotted_as_name(@NotNull Python3Parser.Dotted_as_nameContext ctx) { return null; } @Override public Statement visitFactor(@NotNull Python3Parser.FactorContext ctx) { if ( ctx.power() != null ) { return visitPower(ctx.power()); } ExpressionTree tree = (ExpressionTree) visitFactor(ctx.factor()); tree.setSpeical(ctx.op.getText()); return tree; } @Override public Statement visitSliceop(@NotNull Python3Parser.SliceopContext ctx) { return null; } @Override public Statement visitFuncdef(@NotNull Python3Parser.FuncdefContext ctx) { String name = ctx.NAME().getSymbol().getText(); StatementBlock block = (StatementBlock) visitSuite(ctx.suite()); ParametersStatement parameters = (ParametersStatement) visit(ctx.parameters()); PythonFunction function = new PythonFunction(name, block, parameters); functions.put(function.getName(), function); return block; } @Override public Statement visitSubscriptlist(@NotNull Python3Parser.SubscriptlistContext ctx) { return null; } @Override public Statement visitTest_nocond(@NotNull Python3Parser.Test_nocondContext ctx) { return visitOr_test(ctx.or_test()); } @Override public Statement visitComp_iter(@NotNull Python3Parser.Comp_iterContext ctx) { return null; } @Override public Statement visitNonlocal_stmt(@NotNull Python3Parser.Nonlocal_stmtContext ctx) { return null; } @Override public Statement visitEval_input(@NotNull Python3Parser.Eval_inputContext ctx) { return null; } @Override public Statement visitVfpdef(@NotNull Python3Parser.VfpdefContext ctx) { return null; } @Override public Statement visitImport_name(@NotNull Python3Parser.Import_nameContext ctx) { return null; } @Override public Statement visitComp_if(@NotNull Python3Parser.Comp_ifContext ctx) { return null; } @Override public Statement visitAugassign(@NotNull Python3Parser.AugassignContext ctx) { return null; } @Override public Statement visitPass_stmt(@NotNull Python3Parser.Pass_stmtContext ctx) { return null; } @Override public Statement visitExpr_stmt(@NotNull Python3Parser.Expr_stmtContext ctx) { if(ctx.augassign() == null && ctx.testlist_star_expr(1) == null && ctx.yield_expr(1) == null){ return visitTestlist_star_expr(ctx.testlist_star_expr(0)); } List<String> names = new ArrayList<>(Arrays.asList(ctx.testlist_star_expr(0).getText().split(","))); TestListStatement statement = (TestListStatement) visitTestlist_star_expr(ctx.testlist_star_expr(1)); if ( ctx.augassign() == null ) { return new AssignStatement(names, statement.getTrees()); } return new AugAssignStatement(ctx.augassign().getText(), names, statement.getTrees()); } @Override public Statement visitProg(@NotNull Python3Parser.ProgContext ctx) { return new StatementBlock(ctx.stmt().stream().map(this::visitStmt).collect(Collectors.toList())); } @Override public Statement visitYield_stmt(@NotNull Python3Parser.Yield_stmtContext ctx) { return null; } @Override public Statement visitSuite(@NotNull Python3Parser.SuiteContext ctx) { if ( ctx.simple_stmt() != null ) { return new StatementBlock(new ArrayList<>(Collections.singletonList(visitSimple_stmt(ctx.simple_stmt())))); } List<Statement> statements = new ArrayList<>(); for (Python3Parser.StmtContext context : ctx.stmt()) { statements.add(visitStmt(context)); } return new StatementBlock(statements); } @Override public Statement visitContinue_stmt(@NotNull Python3Parser.Continue_stmtContext ctx) { return new ContinueStatement(); } @Override public Statement visitTestlist_star_expr(@NotNull Python3Parser.Testlist_star_exprContext ctx) { List<ExpressionTree> trees = new ArrayList<>(); for(Python3Parser.TestContext testContext : ctx.test()){ trees.add((ExpressionTree) visitTest(testContext)); } return new TestListStatement(trees); } @Override public Statement visitVarargslist(@NotNull Python3Parser.VarargslistContext ctx) { return null; } @Override public Statement visitFor_stmt(@NotNull Python3Parser.For_stmtContext ctx) { TestListStatement testListStatement = (TestListStatement) visitTestlist(ctx.testlist()); StatementBlock body = (StatementBlock) visitSuite(ctx.suite(0)); return new ForStatement(new ArrayList<>(Arrays.asList(ctx.exprlist().getText().split(","))), testListStatement.getTrees(), body); } @Override public Statement visitDel_stmt(@NotNull Python3Parser.Del_stmtContext ctx) { ExpressionTree tree = (ExpressionTree) visitExprlist(ctx.exprlist()); return new DeleteStatement(tree); } @Override public Statement visitAtom(@NotNull Python3Parser.AtomContext ctx) { if ( ctx.FALSE() != null ) { ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node node = new ExpressionTree.Node(); node.object = new PythonBoolean(false); tree.setRoot(node); return tree; } if ( ctx.TRUE() != null ) { ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node node = new ExpressionTree.Node(); node.object = new PythonBoolean(true); tree.setRoot(node); return tree; } if ( ctx.NONE() != null ) { ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node node = new ExpressionTree.Node(); node.object = Python.none(); tree.setRoot(node); return tree; } if ( ctx.NAME() != null ) { ExpressionTree tree = new ExpressionTree(null); ExpressionTree.Node node = new ExpressionTree.Node(); node.object = new PythonRef(ctx.NAME().getText()); tree.setRoot(node); return tree; } if ( ctx.number() != null ) { return visitNumber(ctx.number()); } return visitString(ctx.string(0)); } @Override public Statement visitStmt(@NotNull Python3Parser.StmtContext ctx) { if ( ctx.compound_stmt() != null ) { return visitCompound_stmt(ctx.compound_stmt()); } else { return visitSimple_stmt(ctx.simple_stmt()); } } @Override public Statement visit(@NotNull ParseTree tree) { return tree.accept(this); } @Override public Statement visitChildren(@NotNull RuleNode node) { return null; } @Override public Statement visitTerminal(@NotNull TerminalNode node) { return null; } @Override public Statement visitErrorNode(@NotNull ErrorNode node) { return null; } }
ObadaJabassini/Python-Interpreter
src/main/java/executor/PythonVisitor.java
Java
apache-2.0
24,136
package com.bjorktech.cayman.javaweb.core; import lombok.Data; import lombok.Getter; import java.io.Serializable; @Data public class WebAPIResponse<T> { private static final long serialVersionUID = -7075279526593760189L; @Getter private boolean success; @Getter private int code; @Getter private String msg; @Getter private T data; private WebAPIResponse() { } public static <T> WebAPIResponse<T> buildSuccessResponse(T data) { WebAPIResponse<T> result = new WebAPIResponse<T>(); result.setSuccess(true); result.setCode(0); result.setMsg(""); result.setData(data); return result; } public static <T> WebAPIResponse<T> buildFailResponse(int code, String msg) { WebAPIResponse<T> result = new WebAPIResponse<T>(); result.setSuccess(false); result.setCode(code); result.setMsg(msg); //data.setData(data); //错误时无需返回数据,如果是部分成功,返回也是成功,具体item的成功失败就在data中 return result; } }
wanliwang/cayman
cm-javaweb/src/main/java/com/bjorktech/cayman/javaweb/core/WebAPIResponse.java
Java
apache-2.0
1,099
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * Agfa-Gevaert AG. * Portions created by the Initial Developer are Copyright (C) 2002-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * See listed authors below. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chee.usr.dao; import java.util.List; import javax.ejb.Local; import org.dcm4chee.usr.entity.Role; import org.dcm4chee.usr.entity.User; /** * @author Robert David <robert.david@agfa.com> * @version $Revision$ $Date$ * @since 19.08.2009 */ @Local public interface UserAccess { String JNDI_NAME = "dcm4chee-usr-dao/UserAccess/local"; public List<User> findAll(); public User getUser(String userId); public void createUser(User user); public void updateUser(String userId, String password); public void deleteUser(String userId); public Boolean userExists(String username); public Boolean hasPassword(String username, String password); public List<String> getAllRolenames(); public void addRole(Role role); public void removeRole(Role role); public Boolean roleExists(String rolename); }
medicayun/medicayundicom
dcm4chee-usr/tags/DCM4CHEE_WEB_3_0_0_TEST1/dcm4chee-usr-dao/src/main/java/org/dcm4chee/usr/dao/UserAccess.java
Java
apache-2.0
2,684
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.xray.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.xray.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * TelemetryRecord JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class TelemetryRecordJsonUnmarshaller implements Unmarshaller<TelemetryRecord, JsonUnmarshallerContext> { public TelemetryRecord unmarshall(JsonUnmarshallerContext context) throws Exception { TelemetryRecord telemetryRecord = new TelemetryRecord(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Timestamp", targetDepth)) { context.nextToken(); telemetryRecord.setTimestamp(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("SegmentsReceivedCount", targetDepth)) { context.nextToken(); telemetryRecord.setSegmentsReceivedCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("SegmentsSentCount", targetDepth)) { context.nextToken(); telemetryRecord.setSegmentsSentCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("SegmentsSpilloverCount", targetDepth)) { context.nextToken(); telemetryRecord.setSegmentsSpilloverCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("SegmentsRejectedCount", targetDepth)) { context.nextToken(); telemetryRecord.setSegmentsRejectedCount(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("BackendConnectionErrors", targetDepth)) { context.nextToken(); telemetryRecord.setBackendConnectionErrors(BackendConnectionErrorsJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return telemetryRecord; } private static TelemetryRecordJsonUnmarshaller instance; public static TelemetryRecordJsonUnmarshaller getInstance() { if (instance == null) instance = new TelemetryRecordJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/transform/TelemetryRecordJsonUnmarshaller.java
Java
apache-2.0
4,089
package com.sync.jdbc.spring; import com.sync.jdbc.JdbcUtils; import com.sync.jdbc.domain.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; /** * Created by Administrator on 2016/11/9 0009. */ public class JdbcTemplateTest { static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource()); public static void main(String[] args) { //User u = findUser("zhangsan"); //System.out.println(u); //List<User> users = findUsers(10); //System.out.println(users); //int count = getUserCount(); //System.out.println(count); //String name = getUserName(); //System.out.println(name); //System.out.println(getData(1)); //System.out.println(getDataList(12)); User user =new User(); user.setName("luo"); user.setBirthday(new Date()); user.setMoney(20.0f); System.out.println(addUser(user)); } static int addUser(final User user) { int id = jdbc.execute(new ConnectionCallback<Integer>() { public Integer doInConnection(Connection connection) throws SQLException, DataAccessException { String sql = "insert into user(name,birthday,money) values(?,?,?)"; PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, user.getName()); ps.setDate(2, new java.sql.Date(user.getBirthday().getTime())); ps.setFloat(3, user.getMoney()); ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) user.setId(rs.getInt(1)); return user.getId(); } }); return id; } static List<Map<String, Object>> getDataList(int id) { String sql = "select id,name,birthday,money FROM user WHERE id<?"; List<Map<String, Object>> dataList = jdbc.queryForList(sql, id); return dataList; } static Map<String, Object> getData(int id) { String sql = "SELECT id,name,birthday,money FROM user where id = ?"; Map<String, Object> datas = jdbc.queryForMap(sql, id); return datas; } static String getUserName() { String sql = "SELECT name FROM user WHERE id=?"; String name = jdbc.queryForObject(sql, String.class, 1); return name; } static int getUserCount() { String sql = "select count(*) from user"; int count = jdbc.queryForObject(sql, Integer.class); return count; } static List<User> findUsers(int id) { String sql = "select id,name,money,birthday from user where id<?"; Object[] args = new Object[] {id}; List<User> users = jdbc.query(sql, args, new BeanPropertyRowMapper<User>(User.class)); return users; } static User findUser(String name) { String sql = "select id,name,money,birthday from user where name=?"; Object[] args = new Object[] {name}; User user = jdbc.queryForObject(sql, args, new BeanPropertyRowMapper<User>(User.class)); return user; } static User findUser1(String name) { String sql = "select id,name,money,birthday from user where name=?"; //Object[] args = new Object[]{name}; User user = jdbc.queryForObject(sql, new RowMapper<User>() { public User mapRow(ResultSet resultSet, int i) throws SQLException { User u = new User(); u.setId(resultSet.getInt("id")); u.setName(resultSet.getString("name")); u.setMoney(resultSet.getFloat("money")); u.setBirthday(resultSet.getDate("birthday")); return u; } }, name); return user; } }
MariShunxiang/JdbcSample
src/main/java/com/sync/jdbc/spring/JdbcTemplateTest.java
Java
apache-2.0
3,897
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codepipeline.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.codepipeline.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * PipelineSummary JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PipelineSummaryJsonUnmarshaller implements Unmarshaller<PipelineSummary, JsonUnmarshallerContext> { public PipelineSummary unmarshall(JsonUnmarshallerContext context) throws Exception { PipelineSummary pipelineSummary = new PipelineSummary(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("name", targetDepth)) { context.nextToken(); pipelineSummary.setName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("version", targetDepth)) { context.nextToken(); pipelineSummary.setVersion(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("created", targetDepth)) { context.nextToken(); pipelineSummary.setCreated(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("updated", targetDepth)) { context.nextToken(); pipelineSummary.setUpdated(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return pipelineSummary; } private static PipelineSummaryJsonUnmarshaller instance; public static PipelineSummaryJsonUnmarshaller getInstance() { if (instance == null) instance = new PipelineSummaryJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/transform/PipelineSummaryJsonUnmarshaller.java
Java
apache-2.0
3,485
package br.com.objectos.pojo.plugin; import br.com.objectos.way.orm.Orm; import br.com.objectos.way.schema.meta.EnumType; import javax.annotation.Generated; @Generated({ "br.com.objectos.way.orm.compiler.InjectPlugin", "br.com.objectos.way.pojo.WritingPojoCompiler", "br.com.objectos.way.pojo.StandardBuilderPropertyAction" }) final class EnumeratedBuilderPojo implements EnumeratedBuilder, EnumeratedBuilder.EnumeratedBuilderOrdinalEnum, EnumeratedBuilder.EnumeratedBuilderStringEnum { private final Orm orm; private EnumType ordinalEnum; private EnumType stringEnum; public EnumeratedBuilderPojo(Orm orm) { this.orm = orm; } @Override public Enumerated build() { return new EnumeratedPojo(orm, this); } @Override public EnumeratedBuilder.EnumeratedBuilderOrdinalEnum ordinalEnum(EnumType ordinalEnum) { if (ordinalEnum == null) { throw new NullPointerException(); } this.ordinalEnum = ordinalEnum; return this; } EnumType ___get___ordinalEnum() { return ordinalEnum; } @Override public EnumeratedBuilder.EnumeratedBuilderStringEnum stringEnum(EnumType stringEnum) { if (stringEnum == null) { throw new NullPointerException(); } this.stringEnum = stringEnum; return this; } EnumType ___get___stringEnum() { return stringEnum; } }
objectos/way
orm/orm-testing/src/test/resources/code/pojo-plugin/EnumeratedBuilderPojo.java
Java
apache-2.0
1,349
package org.ogf.schemas.nsi._2013._12.services.types; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * A simple ordered list type of Service Termination Point (STP). List * order is determined by the integer order attribute in the orderedSTP * element. * * Elements: * * orderedSTP - A list of STP ordered 0..n by their integer order attribute. * * * <p>Java class for StpListType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="StpListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="orderedSTP" type="{http://schemas.ogf.org/nsi/2013/12/services/types}OrderedStpType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "StpListType", propOrder = { "orderedSTP" }) public class StpListType { protected List<OrderedStpType> orderedSTP; /** * Gets the value of the orderedSTP property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the orderedSTP property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOrderedSTP().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OrderedStpType } * * */ public List<OrderedStpType> getOrderedSTP() { if (orderedSTP == null) { orderedSTP = new ArrayList<OrderedStpType>(); } return this.orderedSTP; } }
nsicontest/nsi-ri
src/org/ogf/schemas/nsi/_2013/_12/services/types/StpListType.java
Java
apache-2.0
2,247
/** * ContentStatus.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201208; public class ContentStatus implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected ContentStatus(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _ACTIVE = "ACTIVE"; public static final java.lang.String _INACTIVE = "INACTIVE"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final ContentStatus ACTIVE = new ContentStatus(_ACTIVE); public static final ContentStatus INACTIVE = new ContentStatus(_INACTIVE); public static final ContentStatus UNKNOWN = new ContentStatus(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static ContentStatus fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { ContentStatus enumeration = (ContentStatus) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static ContentStatus fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ContentStatus.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201208", "ContentStatus")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
google-code-export/google-api-dfp-java
src/com/google/api/ads/dfp/v201208/ContentStatus.java
Java
apache-2.0
2,850
//! futname = Subject //NAME OF FUNCTION UNDER TEST //! mutation = false //SPECIFY MUTATION COVERAGE //! textout = true //WRITE INSTRUMENTED SUBJECT TO FILE //! maxchildren = 500000 //MAX LENGTH OF SEARCH //! totalpopsize = 100 //TOTAL SIZE OF POPULATIONS //! mutationpercent = 50 //REL FREQUENCY OF GENETIC MUTATION TO CROSSOVER //! samefitcountmax = 100 //NUMBER OF CONSECUTIVE TESTS IN A POP //THAT MUST HAVE THE SAME COST FOR POP TO BE STAGNANT //! verbose = false //PRINT MESSAGES SHOWING PROGRESS OF SEARCH //! showevery = 3000 //NUMBER OF CANDIDATE INPUTS GENERATED BETWEEN EACH SHOW //! numbins = 0 //GRANULARITY OF CANDIDATE INPUT HISTOGRAM, SET TO 0 TO NOT COLLECT STATS //! trialfirst = 1 //EACH TRIAL USES A DIFFERENT RANDOM SEED //! triallast = 1 //NUMBER OF TRIALS = triallast - trialfirst + 1 package org.restscs.imp; public class FileSuffix { public static String subject(String directory , String file ) { int result = 0; //EG pathname = "...WORD/FILE.DOC"; // files : Object[]; String[] fileparts = null; //var lastfile : int = 0; int lastpart = 0; String suffix = null; fileparts = file.split("."); lastpart = fileparts.length - 1; if (lastpart > 0) { suffix = fileparts[lastpart]; //Console.WriteLine("{0}, {1}", directory, suffix); if ("text".equals(directory)) { if ("txt".equals(suffix)) { result = 1; } } if ("acrobat".equals(directory)) { if ("pdf".equals(suffix)) { //print("acrobat"); result = 2; } } if ("word".equals(directory)) { if ("doc".equals(suffix)) { //print("word"); result = 3; } } if ("bin".equals(directory)) { if ("exe".equals(suffix)) { //print("bin"); result = 4; } } if ("lib".equals(directory)) { if ("dll".equals(suffix)) { //print("lib"); result = 5; } } } return "" + result; } }
EMResearch/EMB
jdk_8_maven/cs/rest/artificial/scs/src/main/java/org/restscs/imp/FileSuffix.java
Java
apache-2.0
1,952
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shindig.gadgets.spec; import org.apache.shindig.common.xml.XmlUtil; import org.apache.shindig.gadgets.variables.Substitutions; import junit.framework.TestCase; public class UserPrefTest extends TestCase { public void testBasic() throws Exception { String xml = "<UserPref" + " name=\"name\"" + " display_name=\"display_name\"" + " default_value=\"default_value\"" + " required=\"true\"" + " datatype=\"hidden\"/>"; UserPref userPref = new UserPref(XmlUtil.parse(xml)); assertEquals("name", userPref.getName()); assertEquals("display_name", userPref.getDisplayName()); assertEquals("default_value", userPref.getDefaultValue()); assertEquals(true, userPref.getRequired()); assertEquals(UserPref.DataType.HIDDEN, userPref.getDataType()); } public void testEnum() throws Exception { String xml = "<UserPref name=\"foo\" datatype=\"enum\">" + " <EnumValue value=\"0\" display_value=\"Zero\"/>" + " <EnumValue value=\"1\"/>" + "</UserPref>"; UserPref userPref = new UserPref(XmlUtil.parse(xml)); assertEquals(2, userPref.getEnumValues().size()); assertEquals("Zero", userPref.getEnumValues().get("0")); assertEquals("1", userPref.getEnumValues().get("1")); } public void testSubstitutions() throws Exception { String xml = "<UserPref name=\"name\" datatype=\"enum\"" + " display_name=\"__MSG_display_name__\"" + " default_value=\"__MSG_default_value__\">" + " <EnumValue value=\"0\" display_value=\"__MSG_dv__\"/>" + "</UserPref>"; String displayName = "This is the display name"; String defaultValue = "This is the default value"; String displayValue = "This is the display value"; Substitutions substituter = new Substitutions(); substituter.addSubstitution(Substitutions.Type.MESSAGE, "display_name", displayName); substituter.addSubstitution(Substitutions.Type.MESSAGE, "default_value", defaultValue); substituter.addSubstitution(Substitutions.Type.MESSAGE, "dv", displayValue); UserPref userPref = new UserPref(XmlUtil.parse(xml)).substitute(substituter); assertEquals(displayName, userPref.getDisplayName()); assertEquals(defaultValue, userPref.getDefaultValue()); assertEquals(displayValue, userPref.getEnumValues().get("0")); } public void testMissingName() throws Exception { String xml = "<UserPref datatype=\"string\"/>"; try { new UserPref(XmlUtil.parse(xml)); fail("No exception thrown when name is missing"); } catch (SpecParserException e) { // OK } } public void testMissingDataType() throws Exception { String xml = "<UserPref name=\"name\"/>"; UserPref pref = new UserPref(XmlUtil.parse(xml)); assertEquals(UserPref.DataType.STRING, pref.getDataType()); } public void testMissingEnumValue() throws Exception { String xml = "<UserPref name=\"foo\" datatype=\"enum\">" + " <EnumValue/>" + "</UserPref>"; try { new UserPref(XmlUtil.parse(xml)); fail("No exception thrown when EnumValue@value is missing"); } catch (SpecParserException e) { // OK } } public void testToString() throws Exception { String xml = "<UserPref name=\"name\" display_name=\"__MSG_display_name__\" " + "default_value=\"__MSG_default_value__\" required=\"false\" " + "datatype=\"enum\">" + "<EnumValue value=\"0\" display_value=\"__MSG_dv__\"/>" + "</UserPref>"; UserPref userPref = new UserPref(XmlUtil.parse(xml)); assertEquals(xml, userPref.toString().replaceAll("\n", "")); } }
apache/shindig
java/gadgets/src/test/java/org/apache/shindig/gadgets/spec/UserPrefTest.java
Java
apache-2.0
4,611
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.lucene.query.select; import com.google.inject.Inject; import com.metamx.common.ISE; import com.metamx.common.guava.Sequence; import io.druid.lucene.LuceneDirectory; import io.druid.query.*; import io.druid.segment.Segment; import java.util.Map; import java.util.concurrent.ExecutorService; /** */ public class SelectQueryRunnerFactory implements QueryRunnerFactory<Result<SelectResultValue>, SelectQuery> { private final SelectQueryQueryToolChest toolChest; private final SelectQueryEngine engine; private final QueryWatcher queryWatcher; @Inject public SelectQueryRunnerFactory( SelectQueryQueryToolChest toolChest, SelectQueryEngine engine, QueryWatcher queryWatcher ) { this.toolChest = toolChest; this.engine = engine; this.queryWatcher = queryWatcher; } @Override public QueryRunner<Result<SelectResultValue>> createRunner(final Segment segment) { return new SelectQueryRunner(engine, segment); } @Override public QueryRunner<Result<SelectResultValue>> mergeRunners( ExecutorService queryExecutor, Iterable<QueryRunner<Result<SelectResultValue>>> queryRunners ) { return new ChainedExecutionQueryRunner<Result<SelectResultValue>>( queryExecutor, queryWatcher, queryRunners ); } @Override public QueryToolChest<Result<SelectResultValue>, SelectQuery> getToolchest() { return toolChest; } private static class SelectQueryRunner implements QueryRunner<Result<SelectResultValue>> { private final SelectQueryEngine engine; private final Segment segment; private SelectQueryRunner(SelectQueryEngine engine, Segment segment) { this.engine = engine; this.segment = segment; } @Override public Sequence<Result<SelectResultValue>> run( Query<Result<SelectResultValue>> input, Map<String, Object> responseContext ) { if (!(input instanceof SelectQuery)) { throw new ISE("Got a [%s] which isn't a %s", input.getClass(), SelectQuery.class); } return engine.process((SelectQuery) input, segment); } } }
yaochitc/druid-dev
extensions-core/lucene-extensions/src/main/java/io/druid/lucene/query/select/SelectQueryRunnerFactory.java
Java
apache-2.0
2,936
/* * Copyright (c) 2015 Sillelien * * * 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 sillelien.tutum; import java.util.List; /** * (c) 2015 Cazcade Limited * * @author neil@cazcade.com */ public interface TutumService extends TutumServiceDefinition { List<String> containers(); boolean isRunning(); boolean isStarting(); String state(); String uri(); String uuid(); List<TutumPort> containerPorts(); }
sillelien/tutum-api
src/main/java/sillelien/tutum/TutumService.java
Java
apache-2.0
970
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package brooklyn.entity.network.bind; import brooklyn.entity.basic.SoftwareProcessDriver; public interface BindDnsServerDriver extends SoftwareProcessDriver { // Marker Interface }
neykov/incubator-brooklyn
software/network/src/main/java/brooklyn/entity/network/bind/BindDnsServerDriver.java
Java
apache-2.0
997
package org.dcm4chee.web.war.folder; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ResourceReference; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.image.Image; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.dcm4chee.icons.ImageManager; import org.dcm4chee.icons.behaviours.ImageSizeBehaviour; import org.dcm4chee.web.common.behaviours.TooltipBehaviour; import org.dcm4chee.web.war.AuthenticatedWebSession; import org.dcm4chee.web.war.common.SelectAllLink; import org.dcm4chee.web.war.folder.model.PatientModel; public class StudyListHeader extends Panel { private static final long serialVersionUID = 1L; private int headerExpandLevel = 1; private int expandAllLevel = 5; private IModel<Boolean> autoExpand = new Model<Boolean>(false); private final class Row extends WebMarkupContainer { private static final long serialVersionUID = 1L; private final int entityLevel; public Row(String id, int entityLevel) { super(id); this.entityLevel = entityLevel; } @Override public boolean isVisible() { return StudyListHeader.this.headerExpandLevel >= Row.this.entityLevel; } } private final class Cell extends WebMarkupContainer { private static final long serialVersionUID = 1L; private final int entityLevel; public Cell(String id, int entityLevel) { super(id); this.entityLevel = entityLevel; add(new AjaxFallbackLink<Object>("expand"){ private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { headerExpandLevel = headerExpandLevel > Cell.this.entityLevel ? Cell.this.entityLevel : Cell.this.entityLevel + 1; if (target != null) { target.addComponent(StudyListHeader.this); } } }.add( new Image("expandImg", new AbstractReadOnlyModel<ResourceReference>() { private static final long serialVersionUID = 1L; @Override public ResourceReference getObject() { return StudyListHeader.this.headerExpandLevel <= Cell.this.entityLevel ? ImageManager.IMAGE_COMMON_EXPAND : ImageManager.IMAGE_COMMON_COLLAPSE; } }) .add(new ImageSizeBehaviour()))); } @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("rowspan", 1 + headerExpandLevel - entityLevel); } } public StudyListHeader(String id, Component toUpd) { super(id); setOutputMarkupId(true); add(new AjaxCheckBox("autoExpand", autoExpand) { private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget target) { if (autoExpand.getObject()) { headerExpandLevel = expandAllLevel; target.addComponent(StudyListHeader.this); } } } .add(new TooltipBehaviour("folder.search.","autoExpand"))); Cell patCell = new Cell("cell", 0); List<PatientModel> patients = ((AuthenticatedWebSession) getSession()).getFolderViewPort().getPatients(); toUpd.setOutputMarkupId(true); add(new Row("patient", PatientModel.PATIENT_LEVEL).add(patCell) .add(new SelectAllLink("selectAll", patients,PatientModel.PATIENT_LEVEL, true, toUpd, true) .add(new TooltipBehaviour("folder.studyview.", "selectAllPatients"))) .add(new SelectAllLink("deselectAll", patients,PatientModel.PATIENT_LEVEL, false, toUpd, true) .add(new TooltipBehaviour("folder.studyview.", "deselectAllPatients"))) ); add(new Row("study", PatientModel.STUDY_LEVEL).add(new Cell("cell", 1)) .add(new SelectAllLink("selectAll", patients,PatientModel.STUDY_LEVEL, true, toUpd, true) .add(new TooltipBehaviour("folder.studyview.", "selectAllStudies"))) .add(new SelectAllLink("deselectAll", patients,PatientModel.STUDY_LEVEL, false, toUpd, true) .add(new TooltipBehaviour("folder.studyview.", "deselectAllStudies"))) ); add(new Row("pps", PatientModel.PPS_LEVEL).add(new Cell("cell", 2))); add(new Row("series", PatientModel.SERIES_LEVEL).add(new Cell("cell", 3)) .add(new SelectAllLink("selectAll", patients,PatientModel.SERIES_LEVEL, true, toUpd, true) .add(new TooltipBehaviour("folder.studyview.", "selectAllSeries"))) .add(new SelectAllLink("deselectAll", patients,PatientModel.SERIES_LEVEL, false, toUpd, true) .add(new TooltipBehaviour("folder.studyview.", "deselectAllSeries"))) ); add(new Row("instance", PatientModel.INSTANCE_LEVEL).add(new Cell("cell", 4))); add(new Row("file", 5)); } public void setExpandAllLevel(int expandAllLevel) { this.expandAllLevel = expandAllLevel; if (autoExpand.getObject()) this.headerExpandLevel = expandAllLevel; } public int getExpandAllLevel() { return expandAllLevel; } public void expandToLevel(int level) { headerExpandLevel = level; } }
medicayun/medicayundicom
dcm4chee-web/tags/DCM4CHEE-WEB-3_0_0/dcm4chee-web-war/src/main/java/org/dcm4chee/web/war/folder/StudyListHeader.java
Java
apache-2.0
6,009
package com.linkedin.parseq.batching; import java.util.Map; import java.util.Set; import com.linkedin.parseq.Context; import com.linkedin.parseq.Task; import com.linkedin.parseq.function.Try; /** * This is a base class for a batching strategy that leverages existing Task-based API. * <p> * Example below shows how to build a ParSeq client for a key-value store that provides * transparent batching given existing Task-based API. Let's assume that we have an implementation * of the following key-value store interface: * <blockquote><pre> * interface KVStore { * Task{@code <String>} get(Long key); * Task{@code <Map<Long, Try<String>>>} batchGet(Collection{@code <Long>} keys); * } * </pre></blockquote> * * We can then implement a {@code TaskBatchingStrategy} in the following way (for the sake * of simplicity we assume that all keys can be grouped into one batch thus we implement * {@code SimpleTaskBatchingStrategy}): * <blockquote><pre> * public static class BatchingKVStoreClient extends SimpleTaskBatchingStrategy{@code <Long, String>} { * private final KVStore _store; * public BatchingKVStoreClient(KVStore store) { * _store = store; * } * * {@code @Override} * public void executeBatch(Integer group, Batch{@code <Long, String>} batch) { * Map{@code <Long, String>} batchResult = _store.batchGet(batch.keys()); * batch.foreach((key, promise) {@code ->} promise.done(batchResult.get(key))); * } * * {@code @Override} * public {@code Task<Map<Long, Try<String>>>} taskForBatch(Set{@code <Long>} keys) { * return _store.batchGet(keys); * } * } * </pre></blockquote> * * {@code taskForBatch} method returns a task that computes a map that for every key contains * either a success with a value or a failure. If returned map does not contain results for * some keys the tasks for which results are missing will fail. * * @author Jaroslaw Odzga (jodzga@linkedin.com) * * @param <G> Type of a Group * @param <K> Type of a Key * @param <T> Type of a Value * * @see BatchingStrategy * @see SimpleTaskBatchingStrategy */ public abstract class TaskBatchingStrategy<G, K, T> extends BatchingStrategy<G, K, T> { @Override public final void executeBatch(G group, Batch<K, T> batch) { // This method should be unreachable because we also override executeBatchWithContext throw new IllegalStateException("This method should be unreachable"); } @Override protected void executeBatchWithContext(final G group, final Batch<K, T> batch, final Context ctx) { Task<Map<K, Try<T>>> task = taskForBatch(group, batch.keys()); Task<Map<K, Try<T>>> completing = task.andThen("completePromises", map -> { batch.foreach((key, promise) -> { Try<T> result = map.get(key); if (result != null) { if (result.isFailed()) { promise.fail(result.getError()); } else { promise.done(result.get()); } } else { promise.fail(new Exception("Result for key: " + key + " not found in batch response")); } }); }); completing.getShallowTraceBuilder().setSystemHidden(true); Task<Map<K, Try<T>>> withFailureHandling = completing.onFailure("handleFailures", t -> { batch.failAll(t); }); withFailureHandling.getShallowTraceBuilder().setSystemHidden(true); ctx.run(withFailureHandling); } @Override final public String getBatchName(G group, Batch<K, T> batch) { return getBatchName(group, batch.keys()); } /** * Overriding this method allows providing custom name for a batch. Name will appear in the * ParSeq trace as a description of the task that executes the batch. * @param keys set of keys belonging to the batch that needs to be described * @param group group to be described * @return name for the batch */ public String getBatchName(G group, Set<K> keys) { return "batch(" + keys.size() + ")"; } /** * This method will be called for every batch. It returns a map that for every key contains * either a success with a value or a failure. If returned map does not contain results for * some keys the tasks for which results are missing will fail. * @param group group that represents the batch * @param keys set of keys belonging to the batch * @return A map that for every key contains either a success with a value or a failure. * If returned map does not contain results for some keys the tasks for which results are missing will fail. */ public abstract Task<Map<K, Try<T>>> taskForBatch(G group, Set<K> keys); }
linkedin/parseq
subprojects/parseq-batching/src/main/java/com/linkedin/parseq/batching/TaskBatchingStrategy.java
Java
apache-2.0
4,634
package things.wolfsoft.com.androidthings; import android.os.Build; import com.google.android.things.pio.PeripheralManagerService; import java.util.List; @SuppressWarnings("WeakerAccess") public class BoardDefaults { private static final String DEVICE_EDISON_ARDUINO = "edison_arduino"; private static final String DEVICE_EDISON = "edison"; private static final String DEVICE_JOULE = "joule"; private static final String DEVICE_RPI3 = "rpi3"; private static final String DEVICE_PICO = "imx6ul_pico"; private static final String DEVICE_VVDN = "imx6ul_iopb"; private static final String DEVICE_NXP = "imx6ul"; private static String sBoardVariant = ""; /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForRedLED() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "IO13"; case DEVICE_EDISON: return "GP45"; case DEVICE_RPI3: return "BCM6"; case DEVICE_NXP: return "GPIO4_IO20"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForGreenLED() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "IO13"; case DEVICE_EDISON: return "GP45"; case DEVICE_RPI3: return "BCM19"; case DEVICE_NXP: return "GPIO4_IO20"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForBlueLED() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "IO13"; case DEVICE_EDISON: return "GP45"; case DEVICE_RPI3: return "BCM26"; case DEVICE_NXP: return "GPIO4_IO20"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForBtnA() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "IO13"; case DEVICE_EDISON: return "GP45"; case DEVICE_RPI3: return "BCM21"; case DEVICE_NXP: return "GPIO4_IO20"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForBtnB() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "IO13"; case DEVICE_EDISON: return "GP45"; case DEVICE_RPI3: return "BCM20"; case DEVICE_NXP: return "GPIO4_IO20"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForBtnC() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "IO13"; case DEVICE_EDISON: return "GP45"; case DEVICE_RPI3: return "BCM16"; case DEVICE_NXP: return "GPIO4_IO20"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } public static String getI2cBus() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "I2C6"; case DEVICE_EDISON: return "I2C1"; case DEVICE_JOULE: return "I2C0"; case DEVICE_RPI3: return "I2C1"; case DEVICE_PICO: return "I2C2"; case DEVICE_VVDN: return "I2C4"; default: throw new IllegalArgumentException("Unknown device: " + Build.DEVICE); } } public static String getSpiBus() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "SPI1"; case DEVICE_EDISON: return "SPI2"; case DEVICE_JOULE: return "SPI0.0"; case DEVICE_RPI3: return "SPI0.0"; case DEVICE_PICO: return "SPI3.0"; case DEVICE_VVDN: return "SPI1.0"; default: throw new IllegalArgumentException("Unknown device: " + Build.DEVICE); } } public static String getSpeakerPwmPin() { switch (getBoardVariant()) { case DEVICE_EDISON_ARDUINO: return "IO3"; case DEVICE_EDISON: return "GP13"; case DEVICE_JOULE: return "PWM_0"; case DEVICE_RPI3: return "PWM1"; case DEVICE_PICO: return "PWM7"; case DEVICE_VVDN: return "PWM3"; default: throw new IllegalArgumentException("Unknown device: " + Build.DEVICE); } } private static String getBoardVariant() { if (!sBoardVariant.isEmpty()) { return sBoardVariant; } sBoardVariant = Build.DEVICE; // For the edison check the pin prefix // to always return Edison Breakout pin name when applicable. if (sBoardVariant.equals(DEVICE_EDISON)) { PeripheralManagerService pioService = new PeripheralManagerService(); List<String> gpioList = pioService.getGpioList(); if (gpioList.size() != 0) { String pin = gpioList.get(0); if (pin.startsWith("IO")) { sBoardVariant = DEVICE_EDISON_ARDUINO; } } } return sBoardVariant; } }
mwolfson/AndroidThings_RainbowHatDemo
app/src/main/java/things/wolfsoft/com/androidthings/BoardDefaults.java
Java
apache-2.0
7,433
//package com.cloudata.structured.sql; // //import static com.google.common.base.Preconditions.checkArgument; //import static com.google.common.base.Preconditions.checkNotNull; //import io.airlift.units.Duration; // //import java.io.Closeable; //import java.net.URI; //import java.util.ArrayList; //import java.util.HashSet; //import java.util.Iterator; //import java.util.List; //import java.util.Set; //import java.util.concurrent.TimeUnit; //import java.util.concurrent.atomic.AtomicLong; // //import javax.annotation.concurrent.GuardedBy; //import javax.ws.rs.WebApplicationException; //import javax.ws.rs.core.Response.Status; //import javax.ws.rs.core.UriInfo; // //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; // //import com.facebook.presto.block.BlockCursor; //import com.facebook.presto.client.Column; //import com.facebook.presto.client.FailureInfo; //import com.facebook.presto.client.QueryError; //import com.facebook.presto.client.QueryResults; //import com.facebook.presto.client.StageStats; //import com.facebook.presto.client.StatementStats; //import com.facebook.presto.execution.BufferInfo; //import com.facebook.presto.execution.QueryId; //import com.facebook.presto.execution.QueryInfo; //import com.facebook.presto.execution.QueryManager; //import com.facebook.presto.execution.QueryState; //import com.facebook.presto.execution.QueryStats; //import com.facebook.presto.execution.StageInfo; //import com.facebook.presto.execution.StageState; //import com.facebook.presto.execution.TaskInfo; //import com.facebook.presto.operator.ExchangeClient; //import com.facebook.presto.operator.Page; //import com.facebook.presto.sql.analyzer.Session; //import com.facebook.presto.tuple.TupleInfo; //import com.facebook.presto.util.IterableTransformer; //import com.google.common.base.Preconditions; //import com.google.common.base.Predicate; //import com.google.common.collect.AbstractIterator; //import com.google.common.collect.ImmutableList; //import com.google.common.collect.ImmutableSet; //import com.google.common.collect.Iterables; //import com.google.common.collect.Lists; // //public class Query implements Closeable { // // private static final Logger log = LoggerFactory.getLogger(Query.class); // // private final QueryManager queryManager; // private final QueryId queryId; // private final ExchangeClient exchangeClient; // // private final AtomicLong resultId = new AtomicLong(); // // @GuardedBy("this") // private QueryResults lastResult; // // @GuardedBy("this") // private String lastResultPath; // // @GuardedBy("this") // private List<Column> columns; // // public Query(Session session, String query, QueryManager queryManager, ExchangeClient exchangeClient) { // checkNotNull(session, "session is null"); // checkNotNull(query, "query is null"); // checkNotNull(queryManager, "queryManager is null"); // checkNotNull(exchangeClient, "exchangeClient is null"); // // this.queryManager = queryManager; // // QueryInfo queryInfo = queryManager.createQuery(session, query); // queryId = queryInfo.getQueryId(); // this.exchangeClient = exchangeClient; // } // // @Override // public void close() { // queryManager.cancelQuery(queryId); // } // // public QueryId getQueryId() { // return queryId; // } // // public synchronized QueryResults getResults(long token, UriInfo uriInfo, Duration maxWaitTime) // throws InterruptedException { // // is the a repeated request for the last results? // String requestedPath = uriInfo.getAbsolutePath().getPath(); // if (lastResultPath != null && requestedPath.equals(lastResultPath)) { // // tell query manager we are still interested in the query // queryManager.getQueryInfo(queryId); // return lastResult; // } // // if (token < resultId.get()) { // throw new WebApplicationException(Status.GONE); // } // // // if this is not a request for the next results, return not found // if (lastResult.getNextUri() == null || !requestedPath.equals(lastResult.getNextUri().getPath())) { // // unknown token // throw new WebApplicationException(Status.NOT_FOUND); // } // // return getNextResults(uriInfo, maxWaitTime); // } // // public synchronized QueryResults getNextResults(UriInfo uriInfo, Duration maxWaitTime) throws InterruptedException { // Iterable<List<Object>> data = getData(maxWaitTime); // // // get the query info before returning // // force update if query manager is closed // QueryInfo queryInfo = queryManager.getQueryInfo(queryId); // // // if we have received all of the output data and the query is not marked as done, wait for the query to finish // if (exchangeClient.isClosed() && !queryInfo.getState().isDone()) { // queryManager.waitForStateChange(queryId, queryInfo.getState(), maxWaitTime); // queryInfo = queryManager.getQueryInfo(queryId); // } // // // close exchange client if the query has failed // if (queryInfo.getState().isDone()) { // if (queryInfo.getState() != QueryState.FINISHED) { // exchangeClient.close(); // } else if (queryInfo.getOutputStage() == null) { // // For simple executions (e.g. drop table), there will never be an output stage, // // so close the exchange as soon as the query is done. // exchangeClient.close(); // // // this is a hack to suppress the warn message in the client saying that there are no columns. // // The reason for this is that the current API definition assumes that everything is a query, // // so statements without results produce an error in the client otherwise. // // // // TODO: add support to the API for non-query statements. // columns = ImmutableList.of(new Column("result", "varchar")); // data = ImmutableSet.<List<Object>> of(ImmutableList.<Object> of("true")); // } // } // // // only return a next if the query is not done or there is more data to send (due to buffering) // URI nextResultsUri = null; // if ((!queryInfo.getState().isDone()) || (!exchangeClient.isClosed())) { // nextResultsUri = createNextResultsUri(uriInfo); // } // // // first time through, self is null // QueryResults queryResults = new QueryResults(queryId.toString(), uriInfo.getRequestUriBuilder() // .replaceQuery("").replacePath(queryInfo.getSelf().getPath()).build(), // findCancelableLeafStage(queryInfo), nextResultsUri, columns, data, toStatementStats(queryInfo), // toQueryError(queryInfo)); // // // cache the last results // if (lastResult != null) { // lastResultPath = lastResult.getNextUri().getPath(); // } else { // lastResultPath = null; // } // lastResult = queryResults; // return queryResults; // } // // private synchronized Iterable<List<Object>> getData(Duration maxWait) throws InterruptedException { // // wait for query to start // QueryInfo queryInfo = queryManager.getQueryInfo(queryId); // while (maxWait.toMillis() > 1 && !isQueryStarted(queryInfo)) { // maxWait = queryManager.waitForStateChange(queryId, queryInfo.getState(), maxWait); // queryInfo = queryManager.getQueryInfo(queryId); // } // // // if query did not finish starting or does not have output, just return // if (!isQueryStarted(queryInfo) || queryInfo.getOutputStage() == null) { // return null; // } // // if (columns == null) { // columns = createColumnsList(queryInfo); // } // // updateExchangeClient(queryInfo.getOutputStage()); // // ImmutableList.Builder<RowIterable> pages = ImmutableList.builder(); // // wait up to max wait for data to arrive; then try to return at least DESIRED_RESULT_BYTES // int bytes = 0; // while (bytes < DESIRED_RESULT_BYTES) { // Page page = exchangeClient.getNextPage(maxWait); // if (page == null) { // break; // } // bytes += page.getDataSize().toBytes(); // pages.add(new RowIterable(page)); // // // only wait on first call // maxWait = new Duration(0, TimeUnit.MILLISECONDS); // } // // if (bytes == 0) { // return null; // } // // return Iterables.concat(pages.build()); // } // // private static boolean isQueryStarted(QueryInfo queryInfo) { // QueryState state = queryInfo.getState(); // return state != QueryState.QUEUED && queryInfo.getState() != QueryState.PLANNING // && queryInfo.getState() != QueryState.STARTING; // } // // private synchronized void updateExchangeClient(StageInfo outputStage) { // // update the exchange client with any additional locations // for (TaskInfo taskInfo : outputStage.getTasks()) { // List<BufferInfo> buffers = taskInfo.getOutputBuffers().getBuffers(); // Preconditions.checkState(buffers.size() == 1, "Expected a single output buffer for task %s, but found %s", // taskInfo.getTaskId(), buffers); // // String bufferId = Iterables.getOnlyElement(buffers).getBufferId(); // URI uri = uriBuilderFrom(taskInfo.getSelf()).appendPath("results").appendPath(bufferId).build(); // exchangeClient.addLocation(uri); // } // if ((outputStage.getState() != StageState.PLANNED) && (outputStage.getState() != StageState.SCHEDULING)) { // exchangeClient.noMoreLocations(); // } // } // // private synchronized URI createNextResultsUri(UriInfo uriInfo) { // return uriInfo.getBaseUriBuilder().replacePath("/v1/statement").path(queryId.toString()) // .path(String.valueOf(resultId.incrementAndGet())).replaceQuery("").build(); // } // // private static List<Column> createColumnsList(QueryInfo queryInfo) { // checkNotNull(queryInfo, "queryInfo is null"); // StageInfo outputStage = queryInfo.getOutputStage(); // if (outputStage == null) { // checkNotNull(outputStage, "outputStage is null"); // } // // List<String> names = queryInfo.getFieldNames(); // ArrayList<Type> types = new ArrayList<>(); // for (TupleInfo tupleInfo : outputStage.getTupleInfos()) { // types.addAll(tupleInfo.getTypes()); // } // // checkArgument(names.size() == types.size(), "names and types size mismatch"); // // ImmutableList.Builder<Column> list = ImmutableList.builder(); // for (int i = 0; i < names.size(); i++) { // String name = names.get(i); // Type type = types.get(i); // switch (type) { // case BOOLEAN: // list.add(new Column(name, "boolean")); // break; // case FIXED_INT_64: // list.add(new Column(name, "bigint")); // break; // case DOUBLE: // list.add(new Column(name, "double")); // break; // case VARIABLE_BINARY: // list.add(new Column(name, "varchar")); // break; // default: // throw new IllegalArgumentException("unhandled type: " + type); // } // } // return list.build(); // } // // private static StatementStats toStatementStats(QueryInfo queryInfo) { // QueryStats queryStats = queryInfo.getQueryStats(); // // return StatementStats.builder().setState(queryInfo.getState().toString()).setScheduled(isScheduled(queryInfo)) // .setNodes(globalUniqueNodes(queryInfo.getOutputStage()).size()) // .setTotalSplits(queryStats.getTotalDrivers()).setQueuedSplits(queryStats.getQueuedDrivers()) // .setRunningSplits(queryStats.getRunningDrivers()).setCompletedSplits(queryStats.getCompletedDrivers()) // .setUserTimeMillis(queryStats.getTotalUserTime().toMillis()) // .setCpuTimeMillis(queryStats.getTotalCpuTime().toMillis()) // .setWallTimeMillis(queryStats.getTotalScheduledTime().toMillis()) // .setProcessedRows(queryStats.getRawInputPositions()) // .setProcessedBytes(queryStats.getRawInputDataSize().toBytes()) // .setRootStage(toStageStats(queryInfo.getOutputStage())).build(); // } // // private static StageStats toStageStats(StageInfo stageInfo) { // if (stageInfo == null) { // return null; // } // // com.facebook.presto.execution.StageStats stageStats = stageInfo.getStageStats(); // // ImmutableList.Builder<StageStats> subStages = ImmutableList.builder(); // for (StageInfo subStage : stageInfo.getSubStages()) { // subStages.add(toStageStats(subStage)); // } // // Set<String> uniqueNodes = new HashSet<>(); // for (TaskInfo task : stageInfo.getTasks()) { // // todo add nodeId to TaskInfo // URI uri = task.getSelf(); // uniqueNodes.add(uri.getHost() + ":" + uri.getPort()); // } // // return StageStats.builder().setStageId(String.valueOf(stageInfo.getStageId().getId())) // .setState(stageInfo.getState().toString()).setDone(stageInfo.getState().isDone()) // .setNodes(uniqueNodes.size()).setTotalSplits(stageStats.getTotalDrivers()) // .setQueuedSplits(stageStats.getQueuedDrivers()).setRunningSplits(stageStats.getRunningDrivers()) // .setCompletedSplits(stageStats.getCompletedDrivers()) // .setUserTimeMillis(stageStats.getTotalUserTime().toMillis()) // .setCpuTimeMillis(stageStats.getTotalCpuTime().toMillis()) // .setWallTimeMillis(stageStats.getTotalScheduledTime().toMillis()) // .setProcessedRows(stageStats.getRawInputPositions()) // .setProcessedBytes(stageStats.getRawInputDataSize().toBytes()).setSubStages(subStages.build()).build(); // } // // private static Set<String> globalUniqueNodes(StageInfo stageInfo) { // if (stageInfo == null) { // return ImmutableSet.of(); // } // ImmutableSet.Builder<String> nodes = ImmutableSet.builder(); // for (TaskInfo task : stageInfo.getTasks()) { // // todo add nodeId to TaskInfo // URI uri = task.getSelf(); // nodes.add(uri.getHost() + ":" + uri.getPort()); // } // // for (StageInfo subStage : stageInfo.getSubStages()) { // nodes.addAll(globalUniqueNodes(subStage)); // } // return nodes.build(); // } // // private static boolean isScheduled(QueryInfo queryInfo) { // StageInfo stage = queryInfo.getOutputStage(); // if (stage == null) { // return false; // } // return IterableTransformer.on(getAllStages(stage)).transform(stageStateGetter()).all(isStageRunningOrDone()); // } // // private static Predicate<StageState> isStageRunningOrDone() { // return new Predicate<StageState>() { // @Override // public boolean apply(StageState state) { // return (state == StageState.RUNNING) || state.isDone(); // } // }; // } // // private static URI findCancelableLeafStage(QueryInfo queryInfo) { // if (queryInfo.getOutputStage() == null) { // // query is not running yet, cannot cancel leaf stage // return null; // } // // // query is running, find the leaf-most running stage // return findCancelableLeafStage(queryInfo.getOutputStage()); // } // // private static URI findCancelableLeafStage(StageInfo stage) { // // if this stage is already done, we can't cancel it // if (stage.getState().isDone()) { // return null; // } // // // attempt to find a cancelable sub stage // // check in reverse order since build side of a join will be later in the list // for (StageInfo subStage : Lists.reverse(stage.getSubStages())) { // URI leafStage = findCancelableLeafStage(subStage); // if (leafStage != null) { // return leafStage; // } // } // // // no matching sub stage, so return this stage // return stage.getSelf(); // } // // private static QueryError toQueryError(QueryInfo queryInfo) { // FailureInfo failure = queryInfo.getFailureInfo(); // if (failure == null) { // QueryState state = queryInfo.getState(); // if ((!state.isDone()) || (state == QueryState.FINISHED)) { // return null; // } // log.warn("Query %s in state %s has no failure info", queryInfo.getQueryId(), state); // failure = toFailure(new RuntimeException(format("Query is %s (reason unknown)", state))); // } // return new QueryError(failure.getMessage(), null, 0, failure.getErrorLocation(), failure); // } // // private static class RowIterable implements Iterable<List<Object>> { // private final Page page; // // private RowIterable(Page page) { // this.page = checkNotNull(page, "page is null"); // } // // @Override // public Iterator<List<Object>> iterator() { // return new RowIterator(page); // } // } // // private static class RowIterator extends AbstractIterator<List<Object>> { // private final BlockCursor[] cursors; // private final int columnCount; // // private RowIterator(Page page) { // int columnCount = 0; // cursors = new BlockCursor[page.getChannelCount()]; // for (int channel = 0; channel < cursors.length; channel++) { // cursors[channel] = page.getBlock(channel).cursor(); // columnCount = cursors[channel].getTupleInfo().getFieldCount(); // } // this.columnCount = columnCount; // } // // @Override // protected List<Object> computeNext() { // List<Object> row = new ArrayList<>(columnCount); // for (BlockCursor cursor : cursors) { // if (!cursor.advanceNextPosition()) { // Preconditions.checkState(row.isEmpty(), "Page is unaligned"); // return endOfData(); // } // // row.addAll(cursor.getTuple().toValues()); // } // return row; // } // } // }
justinsb/cloudata
cloudata-structured/src/test/java/com/cloudata/structured/sql/Query.java
Java
apache-2.0
18,974
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package net.firejack.platform.service.registry.helper; import net.firejack.platform.api.content.domain.FileInfo; import net.firejack.platform.core.config.meta.utils.DiffUtils; import net.firejack.platform.core.model.registry.NavigationElementType; import net.firejack.platform.core.model.registry.ProcessType; import net.firejack.platform.core.model.registry.RegistryNodeModel; import net.firejack.platform.core.model.registry.RegistryNodeType; import net.firejack.platform.core.model.registry.authority.PermissionModel; import net.firejack.platform.core.model.registry.authority.RoleModel; import net.firejack.platform.core.model.registry.authority.UserRoleModel; import net.firejack.platform.core.model.registry.bi.BIReportModel; import net.firejack.platform.core.model.registry.domain.DomainModel; import net.firejack.platform.core.model.registry.domain.EntityModel; import net.firejack.platform.core.model.registry.domain.PackageModel; import net.firejack.platform.core.model.registry.domain.SystemModel; import net.firejack.platform.core.model.registry.process.ProcessModel; import net.firejack.platform.core.model.registry.report.ReportModel; import net.firejack.platform.core.model.registry.resource.FolderModel; import net.firejack.platform.core.model.registry.site.NavigationElementModel; import net.firejack.platform.core.model.registry.wizard.WizardModel; import net.firejack.platform.core.model.user.IUserInfoProvider; import net.firejack.platform.core.model.user.UserModel; import net.firejack.platform.core.store.registry.*; import net.firejack.platform.core.store.registry.resource.IFolderStore; import net.firejack.platform.core.store.registry.resource.IImageResourceStore; import net.firejack.platform.core.store.registry.resource.ITextResourceStore; import net.firejack.platform.core.store.user.IUserStore; import net.firejack.platform.core.utils.MessageResolver; import net.firejack.platform.core.utils.StringUtils; import net.firejack.platform.web.mina.annotations.ProgressStatus; import net.firejack.platform.web.security.model.context.ContextLookupException; import net.firejack.platform.web.security.model.context.ContextManager; import net.firejack.platform.web.security.model.context.OPFContext; import org.apache.log4j.Logger; import org.apache.velocity.util.ClassUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; import java.util.*; @Component public class GatewayService implements IGatewayService { private static final String ID_LOOKUP_KEY = "GatewayService-id-lookup-key"; private static final Logger logger = Logger.getLogger(GatewayService.class); @Autowired @Qualifier("registryNodeStore") protected IRegistryNodeStore<RegistryNodeModel> registryNodeStore; @Autowired private IPackageStore packageStore; @Autowired private INavigationElementStore navigationElementStore; @Autowired private IRoleStore roleStore; @Autowired private IPermissionStore permissionStore; @Autowired private IUserStore userStore; @Autowired private IFolderStore folderStore; @Autowired private ITextResourceStore textResourceStore; @Autowired private IImageResourceStore imageResourceStore; private ThreadLocal<Map<String,Object>> cache; private List<NavigationElementModel> navigationElements; public void setCache(ThreadLocal<Map<String, Object>> cache) { this.cache = cache; } @ProgressStatus(weight = 5, description = "Preparation for code generation") public void prepareGateway(Long packageId) { PackageModel pkg = packageStore.findWithSystemById(packageId); if (pkg != null) { prepareNavigationElements(pkg); prepareRoles(pkg); prepareResourceContents(pkg); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Generate necessary Navigation Elements for package before generate code * @param pkg package */ private void prepareNavigationElements(PackageModel pkg) { navigationElements = new ArrayList<NavigationElementModel>(); // create Gateway navigation element NavigationElementModel mainNavigationElement = createNavigationElement("Gateway", pkg, 1); // create Login navigation element createNavigationElement("Login", mainNavigationElement, 1); // create Forgot Password navigation element createNavigationElement("Forgot Password", mainNavigationElement, 2); // create Home navigation element createNavigationElement("Home", mainNavigationElement, 3); // create Inbox navigation element createNavigationElement("Inbox", mainNavigationElement, 4); Class[] registryNodeClasses = new Class[] { DomainModel.class, EntityModel.class, ReportModel.class, BIReportModel.class, WizardModel.class, ProcessModel.class }; prepareNavigationElements(pkg, mainNavigationElement, registryNodeClasses, 5); Map<String, Object> map = cache.get(); Map<Long, String> idLookupMap = (Map<Long, String>) map.get(ID_LOOKUP_KEY); for (NavigationElementModel element : navigationElements) { navigationElementStore.save(element); if (element.getMain() != null) { Long registryNodeId = element.getMain().getId(); String lookup = idLookupMap.get(registryNodeId); if (StringUtils.isNotBlank(lookup)) { map.put(lookup, element.getUrlPath()); } } } List<NavigationElementModel> allNavigationElements = navigationElementStore.findAllByLikeLookupPrefix(mainNavigationElement.getLookup()); for (NavigationElementModel navigationElement : allNavigationElements) { boolean isExist = false; for (NavigationElementModel correctNavigationElement : navigationElements) { if (correctNavigationElement.getLookup().equals(navigationElement.getLookup())) { isExist = true; break; } } if (!isExist) { navigationElementStore.deleteRecursiveById(navigationElement.getId()); } } } private void prepareNavigationElements(RegistryNodeModel parentRegistryNode, NavigationElementModel parentNavigationElement, Class[] registryNodeClasses, Integer shift) { Map<String, Object> map = cache.get(); Map<Long, String> idMap = (Map<Long, String>) map.get(ID_LOOKUP_KEY); if (idMap == null) { idMap = new HashMap<Long, String>(); map.put(ID_LOOKUP_KEY, idMap); } List<RegistryNodeModel> registryNodeModels = registryNodeStore.findChildrenByParentIdAndTypes(parentRegistryNode.getId(), null, registryNodeClasses); for (int i = 0, registryNodeModelsSize = registryNodeModels.size(); i < registryNodeModelsSize; i++) { RegistryNodeModel registryNode = registryNodeModels.get(i); if (parentRegistryNode instanceof PackageModel || parentRegistryNode instanceof DomainModel) { if (registryNode instanceof EntityModel) { EntityModel entityModel = (EntityModel) registryNode; if (!entityModel.getAbstractEntity() && !entityModel.getTypeEntity()) { NavigationElementModel entityNavElement = createNavigationElement(registryNode.getName(), parentNavigationElement, i + shift); entityNavElement.setMain(entityModel); //map.put(entityModel.getLookup(), entityNavElement.getUrlPath()); idMap.put(entityModel.getId(), entityModel.getLookup()); } prepareNavigationElements(registryNode, parentNavigationElement, registryNodeClasses, 1); } else if (registryNode instanceof WizardModel) { NavigationElementModel entityNavElement = createNavigationElement(registryNode.getName(), parentNavigationElement, i + shift); entityNavElement.setElementType(NavigationElementType.WIZARD); entityNavElement.setPageUrl(registryNode.getLookup()); entityNavElement.setMain(registryNode); //map.put(registryNode.getLookup(), entityNavElement.getUrlPath()); idMap.put(registryNode.getId(), registryNode.getLookup()); } else if (registryNode instanceof ProcessModel) { // if (ProcessType.CREATABLE.equals(((ProcessModel) registryNode).getProcessType())) { EntityModel entityModel = (EntityModel) registryNode.getMain(); if (entityModel != null) { if (!entityModel.getAbstractEntity() && !entityModel.getTypeEntity()) { NavigationElementModel entityNavElement = createNavigationElement(registryNode.getName(), parentNavigationElement, i + shift); entityNavElement.setElementType(NavigationElementType.WORKFLOW); entityNavElement.setMain(entityModel); entityNavElement.setUrlParams(registryNode.getLookup()); ProcessModel processModel = (ProcessModel) registryNode; if (ProcessType.RELATIONAL.equals(processModel.getProcessType())) { entityNavElement.setHidden(Boolean.TRUE); } //map.put(registryNode.getLookup(), entityNavElement.getUrlPath()); idMap.put(registryNode.getId(), registryNode.getLookup()); } } // } } else { NavigationElementModel navigationElement = createNavigationElement(registryNode.getName(), parentNavigationElement, i + shift); prepareNavigationElements(registryNode, navigationElement, registryNodeClasses, 1); } } else if (parentRegistryNode instanceof EntityModel){ if (registryNode instanceof EntityModel) { EntityModel entityModel = (EntityModel) registryNode; if (!entityModel.getAbstractEntity() && !entityModel.getTypeEntity()) { NavigationElementModel entityNavElement = createNavigationElement(registryNode.getName(), parentNavigationElement, i + shift); entityNavElement.setMain(registryNode); //map.put(entityModel.getLookup(), entityNavElement.getUrlPath()); idMap.put(entityModel.getId(), entityModel.getLookup()); } prepareNavigationElements(registryNode, parentNavigationElement, registryNodeClasses, 1); } else if (registryNode instanceof ReportModel || registryNode instanceof BIReportModel) { NavigationElementModel entityNavElement = createNavigationElement(registryNode.getName(), parentNavigationElement, i + shift); entityNavElement.setMain(registryNode); //map.put(registryNode.getLookup(), entityNavElement.getUrlPath()); idMap.put(registryNode.getId(), registryNode.getLookup()); } } } } private NavigationElementModel createNavigationElement(String name, PackageModel pkg, Integer order) { String lookup = DiffUtils.lookup(pkg.getLookup(), name); NavigationElementModel navigationElementModel = navigationElementStore.findByLookup(lookup); if (navigationElementModel == null) { navigationElementModel = new NavigationElementModel(); } navigationElementModel.setName(StringUtils.capitalize(name)); navigationElementModel.setDescription("This is an auto generated navigation element for code generation."); navigationElementModel.setPath(pkg.getLookup()); navigationElementModel.setLookup(lookup); navigationElementModel.setParent(pkg); navigationElementModel.setParentPath("/" + pkg.getName()); navigationElementModel.setUrlPath("/"); navigationElementModel.setPageUrl("/home"); SystemModel system = pkg.getSystem(); if (system != null) { navigationElementModel.setServerName(system.getServerName()); navigationElementModel.setProtocol(system.getProtocol()); navigationElementModel.setPort(system.getPort()); } navigationElementModel.setSortPosition(order); navigationElements.add(navigationElementModel); return navigationElementModel; } private NavigationElementModel createNavigationElement(String name, NavigationElementModel parentNavigationElement, Integer order) { String lookup = DiffUtils.lookup(parentNavigationElement.getLookup(), name); NavigationElementModel navigationElementModel = navigationElementStore.findByLookup(lookup); if (navigationElementModel == null) { navigationElementModel = new NavigationElementModel(); } navigationElementModel.setName(StringUtils.capitalize(name)); navigationElementModel.setDescription("This is an auto generated navigation element for code generation."); navigationElementModel.setPath(parentNavigationElement.getLookup()); navigationElementModel.setLookup(lookup); navigationElementModel.setParent(parentNavigationElement); navigationElementModel.setParentPath(parentNavigationElement.getParentPath()); navigationElementModel.setServerName(parentNavigationElement.getServerName()); navigationElementModel.setProtocol(parentNavigationElement.getProtocol()); navigationElementModel.setPort(parentNavigationElement.getPort()); navigationElementModel.setElementType(NavigationElementType.PAGE); navigationElementModel.setSortPosition(order); navigationElements.add(navigationElementModel); return navigationElementModel; } private RoleModel populateRole(String roleName, PackageModel pkg) { RoleModel roleModel = new RoleModel(); roleModel.setName(roleName); roleModel.setDescription("This is an auto generated role for code generation."); roleModel.setParent(pkg); return roleModel; } private void prepareRoles(PackageModel pkg) { String packageLookup = pkg.getLookup(); RoleModel adminRoleModel = roleStore.findByLookup(packageLookup + ".admin"); if (adminRoleModel == null) { adminRoleModel = populateRole("admin", pkg); } RoleModel userRole = roleStore.findByLookup(packageLookup + ".user"); if (userRole == null) { userRole = populateRole("user", pkg); } List<PermissionModel> guestPermissions = new ArrayList<PermissionModel>(); List<PermissionModel> permissionModels = permissionStore.findAllBySearchTermWithFilter(packageLookup, null); for (PermissionModel permissionModel : permissionModels) { if (permissionModel.getLookup().equals(packageLookup + ".gateway.login") || permissionModel.getLookup().equals(packageLookup + ".gateway.forgot-password")) { guestPermissions.add(permissionModel); } } permissionModels.removeAll(guestPermissions); adminRoleModel.setPermissions(permissionModels); roleStore.save(adminRoleModel); userRole.setPermissions(permissionModels); roleStore.save(userRole); RoleModel guestRoleModel = roleStore.findByLookup(packageLookup + ".guest"); if (guestRoleModel == null) { guestRoleModel = new RoleModel(); guestRoleModel.setName("guest"); guestRoleModel.setDescription("This is an auto generated role for code generation."); guestRoleModel.setParent(pkg); } if (guestRoleModel.getPermissions() == null) { guestRoleModel.setPermissions(guestPermissions); } else { guestPermissions.removeAll(guestRoleModel.getPermissions()); guestRoleModel.getPermissions().addAll(guestPermissions); } roleStore.save(guestRoleModel); if (OPFContext.isInitialized()) { long adminId; try { IUserInfoProvider currentUserInfoProvider = ContextManager.getUserInfoProvider(); adminId = currentUserInfoProvider.getId(); } catch (ContextLookupException e) { UserModel admin = userStore.findUserByUsername("admin"); adminId = admin.getId(); } UserModel currentUser = userStore.findByIdWithRoles(adminId); UserRoleModel userRoleModel = new UserRoleModel(currentUser, adminRoleModel); currentUser.getUserRoles().add(userRoleModel); userStore.save(currentUser); } } private void prepareResourceContents(PackageModel pkg) { RegistryNodeModel rootDomain = registryNodeStore.findById(pkg.getParent().getId()); String rootDomainName = rootDomain.getName(); createTextResourceContext(pkg, "Site Name", "gateway.site-name", rootDomainName, StringUtils.capitalize(pkg.getName())); createTextResourceContext(pkg, "Site Description", "gateway.site-description"); createLogoResourceContent(pkg, "Site Logo"); int year = Calendar.getInstance().get(Calendar.YEAR); createTextResourceContext(pkg, "Copyright", "gateway.copyright", String.valueOf(year), rootDomainName); createLogoResourceContent(pkg, "Footer Site Logo"); FolderModel folderModel = folderStore.findByLookup(pkg.getLookup() + ".general"); if (folderModel == null) { folderModel = new FolderModel(); folderModel.setName("general"); folderModel.setDescription("General folder is specific folder for store general resources like Site name, Site logo and etc."); folderModel.setParent(pkg); folderStore.save(folderModel); } createTextResourceContext(folderModel, "Login Welcome Title", "gateway.login.welcome-title"); createTextResourceContext(folderModel, "Login Welcome Message", "gateway.login.welcome-message", rootDomainName); createTextResourceContext(folderModel, "Forgot Password Title", "gateway.forgot-password.title"); createTextResourceContext(folderModel, "Forgot Password Message", "gateway.forgot-password.message", rootDomainName); createTextResourceContext(folderModel, "Home Page Title", "gateway.home.page-title"); createTextResourceContext(folderModel, "Home Panel Title", "gateway.home.panel-title"); createTextResourceContext(folderModel, "Home Panel Text", "gateway.home.panel-text", rootDomainName, pkg.getName()); generateResourceContents(pkg); } private void generateResourceContents(RegistryNodeModel registryNodeModel) { Class[] registryNodeClasses = new Class[] { DomainModel.class, EntityModel.class, ReportModel.class, BIReportModel.class }; List<RegistryNodeModel> registryNodeModels = registryNodeStore.findChildrenByParentIdAndTypes(registryNodeModel.getId(), null, registryNodeClasses); for (RegistryNodeModel registryNode : registryNodeModels) { String name = StringUtils.capitalize(registryNode.getName()); if (RegistryNodeType.DOMAIN.equals(registryNode.getType())) { createTextResourceContext(registryNode, "Page Title", "gateway.domain.page-title", name); createTextResourceContext(registryNode, "Panel Title", "gateway.domain.panel-title", name); createTextResourceContext(registryNode, "Panel Text", "gateway.domain.panel-text", name); } else if (RegistryNodeType.ENTITY.equals(registryNode.getType())) { createTextResourceContext(registryNode, "Page Title", "gateway.entity.page-title", name); createTextResourceContext(registryNode, "Panel Title", "gateway.entity.panel-title", name); String description = registryNode.getDescription(); if (StringUtils.isNotBlank(description) && !description.trim().endsWith(".")) { description = description.trim() + ". "; } if (StringUtils.isBlank(description)) { description = ""; } createTextResourceContext(registryNode, "Panel Text", "gateway.entity.panel-text", description); } else if (RegistryNodeType.REPORT.equals(registryNode.getType())) { createTextResourceContext(registryNode, "Page Title", "gateway.report.page-title", name); createTextResourceContext(registryNode, "Panel Title", "gateway.report.panel-title", name); String description = registryNode.getDescription(); if (StringUtils.isNotBlank(description) && !description.trim().endsWith(".")) { description = description.trim() + ". "; } if (StringUtils.isBlank(description)) { description = ""; } createTextResourceContext(registryNode, "Panel Text", "gateway.report.panel-text", description); } else if (RegistryNodeType.BI_REPORT.equals(registryNode.getType())) { createTextResourceContext(registryNode, "Page Title", "gateway.bi-report.page-title", name); createTextResourceContext(registryNode, "Panel Title", "gateway.bi-report.panel-title", name); String description = registryNode.getDescription(); if (StringUtils.isNotBlank(description) && !description.trim().endsWith(".")) { description = description.trim() + ". "; } if (StringUtils.isBlank(description)) { description = ""; } createTextResourceContext(registryNode, "Panel Text", "gateway.bi-report.panel-text", description); } generateResourceContents(registryNode); } } private void createTextResourceContext(RegistryNodeModel parent, String name, String messageKey, String... args) { String text = MessageResolver.messageFormatting(messageKey, Locale.ENGLISH, args); textResourceStore.saveTextResource(parent, name, text); } private void createLogoResourceContent(PackageModel pkg, String name) { InputStream inputStream = ClassUtils.getResourceAsStream(this.getClass(), "templates/code/web/images/logo.png"); FileInfo fileInfo = new FileInfo("logo.png", inputStream); try { imageResourceStore.saveImageResource(pkg, name, "Prometheus Logo", fileInfo); } catch (IOException e) { logger.error("Can't save Gateway Logo.", e); } } }
firejack-open/Firejack-Platform
platform/src/main/java/net/firejack/platform/service/registry/helper/GatewayService.java
Java
apache-2.0
24,926
package dk.simplecontentprovider.demo; import android.app.ListActivity; import android.app.LoaderManager; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import dk.simplecontentprovider.demo.provider.DemoContract; public class OverviewActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> { private SimpleCursorAdapter mAdapter; public static void startActivity(Context context) { Intent intent = new Intent(context, OverviewActivity.class); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); mAdapter = new SimpleCursorAdapter(this, R.layout.item_overview, null, new String[]{DemoContract.OwnersAndPetsView.NAME, DemoContract.OwnersAndPetsView.NUMBER_OF_PETS, DemoContract.OwnersAndPetsView.PET_NAMES}, new int[]{R.id.owner_name, R.id.pet_count, R.id.pet_names}, 0); setListAdapter(mAdapter); View emptyView = getListView().getEmptyView(); if (emptyView instanceof TextView) { ((TextView) emptyView).setText("No data"); } getLoaderManager().initLoader(0, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(this, DemoContract.OwnersAndPetsView.CONTENT_URI, new String[]{DemoContract.OwnersAndPetsView._ID, DemoContract.OwnersAndPetsView.NAME, DemoContract.OwnersAndPetsView.NUMBER_OF_PETS, DemoContract.OwnersAndPetsView.PET_NAMES}, null, null, DemoContract.OwnersAndPetsView.NAME); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } }
buchandersenn/SimpleContentProvider
app/src/main/java/dk/simplecontentprovider/demo/OverviewActivity.java
Java
apache-2.0
2,179
/* * Copyright 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.gradle.api.internal.attributes; import org.gradle.api.attributes.AttributeMatchingStrategy; import org.gradle.api.attributes.CompatibilityRuleChain; import org.gradle.api.attributes.DisambiguationRuleChain; import org.gradle.api.internal.InstantiatorFactory; import org.gradle.internal.Cast; import org.gradle.internal.isolation.IsolatableFactory; import java.util.Comparator; public class DefaultAttributeMatchingStrategy<T> implements AttributeMatchingStrategy<T> { private final CompatibilityRuleChain<T> compatibilityRules; private final DisambiguationRuleChain<T> disambiguationRules; public DefaultAttributeMatchingStrategy(InstantiatorFactory instantiatorFactory, IsolatableFactory isolatableFactory) { compatibilityRules = Cast.uncheckedCast(instantiatorFactory.decorate().newInstance(DefaultCompatibilityRuleChain.class, instantiatorFactory.inject(), isolatableFactory)); disambiguationRules = Cast.uncheckedCast(instantiatorFactory.decorate().newInstance(DefaultDisambiguationRuleChain.class, instantiatorFactory.inject(), isolatableFactory)); } @Override public CompatibilityRuleChain<T> getCompatibilityRules() { return compatibilityRules; } @Override public DisambiguationRuleChain<T> getDisambiguationRules() { return disambiguationRules; } @Override public void ordered(Comparator<T> comparator) { ordered(true, comparator); } @Override public void ordered(boolean pickLast, Comparator<T> comparator) { compatibilityRules.ordered(comparator); if (pickLast) { disambiguationRules.pickLast(comparator); } else { disambiguationRules.pickFirst(comparator); } } }
lsmaira/gradle
subprojects/dependency-management/src/main/java/org/gradle/api/internal/attributes/DefaultAttributeMatchingStrategy.java
Java
apache-2.0
2,370
package com.koch.ambeth.ioc.util; /*- * #%L * jambeth-ioc * %% * Copyright (C) 2017 Koch Softwaredevelopment * %% * 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. * #L% */ public class WrappingNamedRunnable implements INamedRunnable { protected final Runnable runnable; protected final String name; public WrappingNamedRunnable(Runnable runnable, String name) { this.runnable = runnable; this.name = name; } @Override public void run() { runnable.run(); } @Override public String getName() { return name; } }
Dennis-Koch/ambeth
jambeth/jambeth-ioc/src/main/java/com/koch/ambeth/ioc/util/WrappingNamedRunnable.java
Java
apache-2.0
1,020
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert // Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2019.02.03 um 11:14:53 PM CET // package net.opengis.gml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für DirectedObservationType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="DirectedObservationType"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://www.opengis.net/gml}ObservationType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://www.opengis.net/gml}direction"/&gt; * &lt;/sequence&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DirectedObservationType", propOrder = { "direction" }) @XmlSeeAlso({ DirectedObservationAtDistanceType.class }) public class DirectedObservationType extends ObservationType { @XmlElement(required = true) protected DirectionPropertyType direction; /** * Ruft den Wert der direction-Eigenschaft ab. * * @return * possible object is * {@link DirectionPropertyType } * */ public DirectionPropertyType getDirection() { return direction; } /** * Legt den Wert der direction-Eigenschaft fest. * * @param value * allowed object is * {@link DirectionPropertyType } * */ public void setDirection(DirectionPropertyType value) { this.direction = value; } public boolean isSetDirection() { return (this.direction!= null); } }
citygml4j/citygml4j
src-gen/main/java/net/opengis/gml/DirectedObservationType.java
Java
apache-2.0
2,124
package eu.applabs.allplaytv.presenter; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.RowHeaderPresenter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import eu.applabs.allplaytv.R; import eu.applabs.allplaytv.gui.IconHeaderItem; public class IconHeaderItemPresenter extends RowHeaderPresenter { private float mUnselectedAlpha; @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup) { mUnselectedAlpha = viewGroup.getResources() .getFraction(R.fraction.lb_browse_header_unselect_alpha, 1, 1); LayoutInflater inflater = (LayoutInflater) viewGroup.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.header_category, null); view.setAlpha(mUnselectedAlpha); // Initialize icons to be at half-opacity. return new ViewHolder(view); } @Override public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) { IconHeaderItem headerItem = (IconHeaderItem) ((ListRow) item).getHeaderItem(); View rootView = viewHolder.view; rootView.setFocusable(true); ImageView iconView = (ImageView) rootView.findViewById(R.id.header_icon); iconView.setImageDrawable(headerItem.getIcon()); TextView label = (TextView) rootView.findViewById(R.id.header_label); label.setText(headerItem.getName()); } @Override public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) { // no op } @Override protected void onSelectLevelChanged(RowHeaderPresenter.ViewHolder holder) { holder.view.setAlpha(mUnselectedAlpha + holder.getSelectLevel() * (1.0f - mUnselectedAlpha)); } }
mkl87/AllPlay
allplaytv/src/main/java/eu/applabs/allplaytv/presenter/IconHeaderItemPresenter.java
Java
apache-2.0
2,077
/* * Copyright 2006-2008 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.osgi.iandt.tcclManagement; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import org.osgi.framework.AdminPermission; import org.osgi.framework.ServiceReference; import org.springframework.osgi.iandt.BaseIntegrationTest; import org.springframework.osgi.iandt.tccl.TCCLService; /** * Test for TCCL handling from the server side. This test checks that the * service provider has always priority no matter the client setting. * * @author Costin Leau * */ public class ServiceTcclTest extends BaseIntegrationTest { private static final String CLIENT_RESOURCE = "/org/springframework/osgi/iandt/tcclManagement/client-resource.properties"; private static final String SERVICE_RESOURCE = "/org/springframework/osgi/iandt/tccl/internal/internal-resource.file"; private static final String SERVICE_PUBLIC_RESOURCE = "/org/springframework/osgi/iandt/tccl/service-resource.file"; private static final String CLIENT_CLASS = "org.springframework.osgi.iandt.tcclManagement.ServiceTcclTest"; private static final String SERVICE_CLASS = "org.springframework.osgi.iandt.tccl.internal.PrivateTCCLServiceImplementation"; private static final String SERVICE_PUBLIC_CLASS = "org.springframework.osgi.iandt.tccl.TCCLService"; protected String[] getConfigLocations() { return new String[] { "/org/springframework/osgi/iandt/tcclManagement/service-context.xml" }; } protected String[] getTestBundlesNames() { return new String[] { "org.springframework.osgi.iandt,tccl," + getSpringDMVersion() }; } public void testSanity() throws Exception { ServiceReference[] refs = bundleContext.getServiceReferences("org.springframework.osgi.iandt.tccl.TCCLService", "(tccl=service-provider)"); System.out.println(bundleContext.getService(refs[0])); } public void testServiceProviderTCCLAndUnmanagedClient() throws Exception { ClassLoader loader = Thread.currentThread().getContextClassLoader(); TCCLService tccl = getUnmanagedTCCL(); assertNotSame("service provide CL hasn't been set", loader, tccl.getTCCL()); } public void testServiceProviderTCCLWithUnmanagedClientWithNullClassLoader() throws Exception { ClassLoader previous = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(null); ClassLoader cl = getUnmanagedTCCL().getTCCL(); assertNotNull("service provide CL hasn't been set", cl); } finally { Thread.currentThread().setContextClassLoader(previous); } } public void testServiceProviderTCCLAndUnmanagedClientWithPredefinedClassLoader() throws Exception { URLClassLoader dummyCL = new URLClassLoader(new URL[0]); ClassLoader previous = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(dummyCL); ClassLoader cl = getUnmanagedTCCL().getTCCL(); assertNotSame(dummyCL, cl); } finally { Thread.currentThread().setContextClassLoader(previous); } } public void testServiceProviderTCCLWithClientTCCLOnClasses() throws Exception { failToLoadClass(getClientTCCL().getTCCL(), CLIENT_CLASS); } public void testServiceProviderTCCLWithClientTCCLOnResources() throws Exception { assertNull(getClientTCCL().getTCCL().getResource(CLIENT_RESOURCE)); } public void testServiceProviderTCCLWithClientTCCLWithServiceClasses() throws Exception { ClassLoader cl = getClientTCCL().getTCCL(); cl.loadClass(SERVICE_PUBLIC_CLASS); cl.loadClass(SERVICE_CLASS); } public void testServiceProviderTCCLWithClientTCCLWithServiceResource() throws Exception { assertNotNull(getClientTCCL().getTCCL().getResource(SERVICE_PUBLIC_RESOURCE)); assertNotNull(getClientTCCL().getTCCL().getResource(SERVICE_RESOURCE)); } public void testServiceProvidedTCCLOnClasses() throws Exception { ClassLoader cl = getServiceProviderTCCL().getTCCL(); cl.loadClass(SERVICE_PUBLIC_CLASS); cl.loadClass(SERVICE_CLASS); } public void testServiceProvidedTCCLOnResources() throws Exception { assertNotNull(getServiceProviderTCCL().getTCCL().getResource(SERVICE_RESOURCE)); } public void testServiceProviderTCCLOnClientClasses() throws Exception { failToLoadClass(getServiceProviderTCCL().getTCCL(), CLIENT_CLASS); } public void testServiceProviderTCCLOnClientResources() throws Exception { assertNull(getServiceProviderTCCL().getTCCL().getResource(CLIENT_RESOURCE)); } private void failToLoadClass(ClassLoader cl, String className) { try { cl.loadClass(className); fail("shouldn't be able to load class " + className); } catch (ClassNotFoundException cnfe) { // expected } } private TCCLService getUnmanagedTCCL() { return (TCCLService) applicationContext.getBean("unmanaged"); } private TCCLService getServiceProviderTCCL() { return (TCCLService) applicationContext.getBean("service-provider"); } private TCCLService getClientTCCL() { return (TCCLService) applicationContext.getBean("client"); } // provide permission for loading class using the service bundle protected List getTestPermissions() { List perms = super.getTestPermissions(); perms.add(new AdminPermission("(name=org.springframework.osgi.iandt.tccl)", AdminPermission.CLASS)); perms.add(new AdminPermission("(name=org.springframework.osgi.iandt.tccl)", AdminPermission.RESOURCE)); return perms; } }
BeamFoundry/spring-osgi
spring-dm/integration-tests/tests/src/test/java/org/springframework/osgi/iandt/tcclManagement/ServiceTcclTest.java
Java
apache-2.0
6,124
/* * Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.core.publisher; import org.junit.jupiter.api.Test; import reactor.test.StepVerifier; public class FluxSwitchOnNextTest { @Test public void switchOnNext() { StepVerifier.create(Flux.switchOnNext(Flux.just(Flux.just("Three", "Two", "One"), Flux.just("Zero")))) .expectNext("Three") .expectNext("Two") .expectNext("One") .expectNext("Zero") .verifyComplete(); } }
reactor/reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxSwitchOnNextTest.java
Java
apache-2.0
1,106
package org.gradle.test.performance.mediummonolithicjavaproject.p275; import org.junit.Test; import static org.junit.Assert.*; public class Test5518 { Production5518 objectUnderTest = new Production5518(); @Test public void testProperty0() { Production5509 value = new Production5509(); objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { Production5513 value = new Production5513(); objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { Production5517 value = new Production5517(); objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p275/Test5518.java
Java
apache-2.0
2,174
package com.icrany.controller.blog; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import org.directwebremoting.util.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.icrany.pojo.Article; import com.icrany.pojo.User; import com.icrany.service.ArticleService; import com.icrany.service.CategoryService; import com.icrany.service.CommentService; import com.icrany.service.LinkService; import com.icrany.service.SiteConfigService; import com.icrany.service.TagService; import com.icrany.service.UserService; import com.icrany.service.imp.ArticleServiceImp; import com.icrany.service.imp.CategoryServiceImp; import com.icrany.service.imp.CommentServiceImp; import com.icrany.service.imp.LinkServiceImp; import com.icrany.service.imp.SiteConfigServiceImp; import com.icrany.service.imp.TagServiceImp; import com.icrany.service.imp.UserServiceImp; @Controller @RequestMapping(value="/jsp/blog") public class ArticleViewController { private static final Logger logger = Logger.getLogger(ArticleViewController.class); private static final String VIEW_BLOG = "blog_view"; @Autowired private CategoryService categoryService ; @Autowired private TagService tagService ; @Autowired private CommentService commentService ; @Autowired private SiteConfigService siteConfigService ; @Autowired private LinkService linkService ; @Autowired private UserService userService ; @Autowired private ArticleService articleService ; /** * 这个类是用来处理 类型之间的转换的问题,如 date --> String 之间的转换 * @param binder */ @InitBinder private void dateBinder(WebDataBinder binder) { //The date format to parse or output your dates SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //Create a new CustomDateEditor CustomDateEditor editor = new CustomDateEditor(dateFormat, true); //Register it as custom editor for the Date type binder.registerCustomEditor(Date.class, editor); } @RequestMapping(value="/blog_view") public String blogView(Map<String,Object> map, Article article){ article = articleService.queryById(article.getId()); //点击一次就自增一个文章的浏览数 article.setView(article.getView()+1); articleService.update(article); map.put("article", article); createReferenceData(map,article.getId()); return VIEW_BLOG; } /** * 保存相关主页面的信息 * @param map * @param user */ private void createReferenceData(Map<String,Object> map , int articleId){ User user = new User();//虚设的一个实例,没有任何的用处 map.put("user", userService.find(user));//默认是只有一个用户的,这个参数是没有起作用的 map.put("tags", tagService.getAllTag()); map.put("categorys", categoryService.findAllCategory()); map.put("siteConfig", siteConfigService.findAllSiteConfig());//默认只有一个站点信息 //TODO:还要存放这篇文章下的所有评论 map.put("comments", commentService.findByArticleId(articleId)); //TODO:最新的五篇文章 map.put("newestArticle", articleService.findNewestArticle()); //TODO:最新的五篇评论 map.put("newestComment",commentService.findNewestComment()); //TODO:最新的五个友情链接 map.put("newestLink", linkService.findNewestLink()); //这里是处理页面中的导航条的部分 对应的List 为 navItems , 类型值为 List<Article> List<Article> navItems = articleService.findPage(); map.put("navItems", navItems); } }
iCrany/ExtendLoveJ
Extend_loveJ(test)/src/com/icrany/controller/blog/ArticleViewController.java
Java
apache-2.0
3,984
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * The action used for activating inactive (i.e. deleted) * {@link CustomTargetingValue} objects. * * * <p>Java class for ActivateCustomTargetingValues complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ActivateCustomTargetingValues"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201511}CustomTargetingValueAction"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ActivateCustomTargetingValues") public class ActivateCustomTargetingValues extends CustomTargetingValueAction { }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/ActivateCustomTargetingValues.java
Java
apache-2.0
1,020
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.picview.request; import java.net.URL; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; /** * A task that executes an HTTP request asynchronously, without blocking the UI * thread. * * @author haeberling@google.com (Sascha Haeberling) */ public class AsyncPutTask extends AsyncTask<Void, Integer, String> { public static interface RequestCallback { public void success(String data); public void error(String message); } private static final String TAG = AsyncPutTask.class.getSimpleName(); private CachedWebPutRequestFetcher fetcher; private final String url; private final com.google.android.apps.picview.request.AsyncRequestTask.RequestCallback callback; private final boolean forceFetchFromWeb; private ProgressDialog progressDialog = null; private String errorMessage; private String data; private String method; public AsyncPutTask(CachedWebPutRequestFetcher cachedPutRequestFetcher, String url, String content,String method, boolean forceFetchFromWeb, String loadingMessage, Context context, com.google.android.apps.picview.request.AsyncRequestTask.RequestCallback requestCallback) { this.fetcher = cachedPutRequestFetcher; this.url = url; this.forceFetchFromWeb = forceFetchFromWeb; this.method = method; this.callback = requestCallback; this.data = content; } @Override protected void onPreExecute() { if (progressDialog != null) { progressDialog.show(); } } @Override protected String doInBackground(Void... params) { try { fetcher.cachedFetch(new URL(url), data, method, forceFetchFromWeb); return null; } catch (Exception e) { e.printStackTrace(); errorMessage = e.getMessage(); } return null; } @Override protected void onPostExecute(String result) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } if (result != null) { callback.success(result); } else { callback.error(errorMessage); } } }
YakindanEgitim/Picasa-Tagger
src/com/google/android/apps/picview/request/AsyncPutTask.java
Java
apache-2.0
2,632
/* * package com.esri.json.hadoop; import java.io.IOException; import org.apache.hadoop.conf.Configuration; * Obsolete - renamed to and superseded by EnclosedEsriJsonRecordReader @Deprecated in v1.2 public class EnclosedJsonRecordReader extends EnclosedEsriJsonRecordReader { public EnclosedJsonRecordReader() throws IOException { // explicit just to declare exception super(); } public EnclosedJsonRecordReader(org.apache.hadoop.mapred.InputSplit split, Configuration conf) throws IOException { super(split, conf); } } * */
Esri/spatial-framework-for-hadoop
json/src/main/java/com/esri/json/hadoop/EnclosedJsonRecordReader.java
Java
apache-2.0
552
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.speech.v1.stub; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.grpc.ProtoOperationTransformers; import com.google.api.gax.longrunning.OperationSnapshot; import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StreamingCallSettings; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.speech.v1.LongRunningRecognizeMetadata; import com.google.cloud.speech.v1.LongRunningRecognizeRequest; import com.google.cloud.speech.v1.LongRunningRecognizeResponse; import com.google.cloud.speech.v1.RecognizeRequest; import com.google.cloud.speech.v1.RecognizeResponse; import com.google.cloud.speech.v1.StreamingRecognizeRequest; import com.google.cloud.speech.v1.StreamingRecognizeResponse; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.longrunning.Operation; import java.io.IOException; import java.util.List; import javax.annotation.Generated; import org.threeten.bp.Duration; // AUTO-GENERATED DOCUMENTATION AND CLASS /** * Settings class to configure an instance of {@link SpeechStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (speech.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. For * example, to set the total timeout of recognize to 30 seconds: * * <pre> * <code> * SpeechStubSettings.Builder speechSettingsBuilder = * SpeechStubSettings.newBuilder(); * speechSettingsBuilder.recognizeSettings().getRetrySettingsBuilder() * .setTotalTimeout(Duration.ofSeconds(30)); * SpeechStubSettings speechSettings = speechSettingsBuilder.build(); * </code> * </pre> */ @Generated("by GAPIC v0.0.5") @BetaApi public class SpeechStubSettings extends StubSettings<SpeechStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build(); private final UnaryCallSettings<RecognizeRequest, RecognizeResponse> recognizeSettings; private final UnaryCallSettings<LongRunningRecognizeRequest, Operation> longRunningRecognizeSettings; private final OperationCallSettings< LongRunningRecognizeRequest, LongRunningRecognizeResponse, LongRunningRecognizeMetadata> longRunningRecognizeOperationSettings; private final StreamingCallSettings<StreamingRecognizeRequest, StreamingRecognizeResponse> streamingRecognizeSettings; /** Returns the object with the settings used for calls to recognize. */ public UnaryCallSettings<RecognizeRequest, RecognizeResponse> recognizeSettings() { return recognizeSettings; } /** Returns the object with the settings used for calls to longRunningRecognize. */ public UnaryCallSettings<LongRunningRecognizeRequest, Operation> longRunningRecognizeSettings() { return longRunningRecognizeSettings; } /** Returns the object with the settings used for calls to longRunningRecognize. */ public OperationCallSettings< LongRunningRecognizeRequest, LongRunningRecognizeResponse, LongRunningRecognizeMetadata> longRunningRecognizeOperationSettings() { return longRunningRecognizeOperationSettings; } /** Returns the object with the settings used for calls to streamingRecognize. */ public StreamingCallSettings<StreamingRecognizeRequest, StreamingRecognizeResponse> streamingRecognizeSettings() { return streamingRecognizeSettings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public SpeechStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcSpeechStub.create(this); } else { throw new UnsupportedOperationException( "Transport not supported: " + getTransportChannelProvider().getTransportName()); } } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return "speech.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(SpeechStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected SpeechStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); recognizeSettings = settingsBuilder.recognizeSettings().build(); longRunningRecognizeSettings = settingsBuilder.longRunningRecognizeSettings().build(); longRunningRecognizeOperationSettings = settingsBuilder.longRunningRecognizeOperationSettings().build(); streamingRecognizeSettings = settingsBuilder.streamingRecognizeSettings().build(); } /** Builder for SpeechStubSettings. */ public static class Builder extends StubSettings.Builder<SpeechStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder<RecognizeRequest, RecognizeResponse> recognizeSettings; private final UnaryCallSettings.Builder<LongRunningRecognizeRequest, Operation> longRunningRecognizeSettings; private final OperationCallSettings.Builder< LongRunningRecognizeRequest, LongRunningRecognizeResponse, LongRunningRecognizeMetadata> longRunningRecognizeOperationSettings; private final StreamingCallSettings.Builder< StreamingRecognizeRequest, StreamingRecognizeResponse> streamingRecognizeSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "idempotent", ImmutableSet.copyOf( Lists.<StatusCode.Code>newArrayList( StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE))); definitions.put("non_idempotent", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList())); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(100L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(60000L)) .setInitialRpcTimeout(Duration.ofMillis(1000000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(1000000L)) .setTotalTimeout(Duration.ofMillis(5000000L)) .build(); definitions.put("default", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this((ClientContext) null); } protected Builder(ClientContext clientContext) { super(clientContext); recognizeSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); longRunningRecognizeSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); longRunningRecognizeOperationSettings = OperationCallSettings.newBuilder(); streamingRecognizeSettings = StreamingCallSettings.newBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( recognizeSettings, longRunningRecognizeSettings); initDefaults(this); } private static Builder createDefault() { Builder builder = new Builder((ClientContext) null); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setEndpoint(getDefaultEndpoint()); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .recognizeSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .longRunningRecognizeSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")); builder .longRunningRecognizeOperationSettings() .setInitialCallSettings( UnaryCallSettings .<LongRunningRecognizeRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create( LongRunningRecognizeResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create( LongRunningRecognizeMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(20000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelay(Duration.ofMillis(45000L)) .setInitialRpcTimeout(Duration.ZERO) // ignored .setRpcTimeoutMultiplier(1.0) // ignored .setMaxRpcTimeout(Duration.ZERO) // ignored .setTotalTimeout(Duration.ofMillis(86400000L)) .build())); return builder; } protected Builder(SpeechStubSettings settings) { super(settings); recognizeSettings = settings.recognizeSettings.toBuilder(); longRunningRecognizeSettings = settings.longRunningRecognizeSettings.toBuilder(); longRunningRecognizeOperationSettings = settings.longRunningRecognizeOperationSettings.toBuilder(); streamingRecognizeSettings = settings.streamingRecognizeSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( recognizeSettings, longRunningRecognizeSettings); } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to recognize. */ public UnaryCallSettings.Builder<RecognizeRequest, RecognizeResponse> recognizeSettings() { return recognizeSettings; } /** Returns the builder for the settings used for calls to longRunningRecognize. */ public UnaryCallSettings.Builder<LongRunningRecognizeRequest, Operation> longRunningRecognizeSettings() { return longRunningRecognizeSettings; } /** Returns the builder for the settings used for calls to longRunningRecognize. */ public OperationCallSettings.Builder< LongRunningRecognizeRequest, LongRunningRecognizeResponse, LongRunningRecognizeMetadata> longRunningRecognizeOperationSettings() { return longRunningRecognizeOperationSettings; } /** Returns the builder for the settings used for calls to streamingRecognize. */ public StreamingCallSettings.Builder<StreamingRecognizeRequest, StreamingRecognizeResponse> streamingRecognizeSettings() { return streamingRecognizeSettings; } @Override public SpeechStubSettings build() throws IOException { return new SpeechStubSettings(this); } } }
mbrukman/gcloud-java
google-cloud-speech/src/main/java/com/google/cloud/speech/v1/stub/SpeechStubSettings.java
Java
apache-2.0
15,887
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.autoscaling.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLoadBalancers" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeLoadBalancersRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the Auto Scaling group. * </p> */ private String autoScalingGroupName; /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> */ private String nextToken; /** * <p> * The maximum number of items to return with this call. The default value is <code>100</code> and the maximum value * is <code>100</code>. * </p> */ private Integer maxRecords; /** * <p> * The name of the Auto Scaling group. * </p> * * @param autoScalingGroupName * The name of the Auto Scaling group. */ public void setAutoScalingGroupName(String autoScalingGroupName) { this.autoScalingGroupName = autoScalingGroupName; } /** * <p> * The name of the Auto Scaling group. * </p> * * @return The name of the Auto Scaling group. */ public String getAutoScalingGroupName() { return this.autoScalingGroupName; } /** * <p> * The name of the Auto Scaling group. * </p> * * @param autoScalingGroupName * The name of the Auto Scaling group. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLoadBalancersRequest withAutoScalingGroupName(String autoScalingGroupName) { setAutoScalingGroupName(autoScalingGroupName); return this; } /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> * * @param nextToken * The token for the next set of items to return. (You received this token from a previous call.) */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> * * @return The token for the next set of items to return. (You received this token from a previous call.) */ public String getNextToken() { return this.nextToken; } /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> * * @param nextToken * The token for the next set of items to return. (You received this token from a previous call.) * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLoadBalancersRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The maximum number of items to return with this call. The default value is <code>100</code> and the maximum value * is <code>100</code>. * </p> * * @param maxRecords * The maximum number of items to return with this call. The default value is <code>100</code> and the * maximum value is <code>100</code>. */ public void setMaxRecords(Integer maxRecords) { this.maxRecords = maxRecords; } /** * <p> * The maximum number of items to return with this call. The default value is <code>100</code> and the maximum value * is <code>100</code>. * </p> * * @return The maximum number of items to return with this call. The default value is <code>100</code> and the * maximum value is <code>100</code>. */ public Integer getMaxRecords() { return this.maxRecords; } /** * <p> * The maximum number of items to return with this call. The default value is <code>100</code> and the maximum value * is <code>100</code>. * </p> * * @param maxRecords * The maximum number of items to return with this call. The default value is <code>100</code> and the * maximum value is <code>100</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLoadBalancersRequest withMaxRecords(Integer maxRecords) { setMaxRecords(maxRecords); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAutoScalingGroupName() != null) sb.append("AutoScalingGroupName: ").append(getAutoScalingGroupName()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getMaxRecords() != null) sb.append("MaxRecords: ").append(getMaxRecords()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeLoadBalancersRequest == false) return false; DescribeLoadBalancersRequest other = (DescribeLoadBalancersRequest) obj; if (other.getAutoScalingGroupName() == null ^ this.getAutoScalingGroupName() == null) return false; if (other.getAutoScalingGroupName() != null && other.getAutoScalingGroupName().equals(this.getAutoScalingGroupName()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getMaxRecords() == null ^ this.getMaxRecords() == null) return false; if (other.getMaxRecords() != null && other.getMaxRecords().equals(this.getMaxRecords()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAutoScalingGroupName() == null) ? 0 : getAutoScalingGroupName().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getMaxRecords() == null) ? 0 : getMaxRecords().hashCode()); return hashCode; } @Override public DescribeLoadBalancersRequest clone() { return (DescribeLoadBalancersRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-autoscaling/src/main/java/com/amazonaws/services/autoscaling/model/DescribeLoadBalancersRequest.java
Java
apache-2.0
7,881
package fruitCalculator; public class AsianPearsDbProvider { public String[] getAllAsianFruits() { throw new RuntimeException("Not implemented yet, still waiting for documentation :("); } }
mirek-rakowski/TestAutomation
unit-tests/src/fruitCalculator/AsianPearsDbProvider.java
Java
apache-2.0
196
/* * Copyright (C) 2004-2015 Volker Bergmann (volker.bergmann@bergmann-it.de). * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.databene.commons.bean; import org.databene.commons.BeanUtil; /** * Default implementation of the {@link ClassProvider} interface. * It forwards the call to {@link BeanUtil}. * Created at 16.11.2008 07:05:10 * @since 0.4.6 * @author Volker Bergmann */ public class DefaultClassProvider implements ClassProvider { private static DefaultClassProvider instance = new DefaultClassProvider(); public static ClassProvider getInstance() { return instance; } @Override public Class<?> forName(String className) { return BeanUtil.forName(className); } public static Class<?> resolveByObjectOrDefaultInstance(String className, Object context) { ClassProvider classProvider; if (context instanceof ClassProvider) classProvider = (ClassProvider) context; else classProvider = DefaultClassProvider.getInstance(); return classProvider.forName(className); } }
aravindc/databenecommons
src/main/java/org/databene/commons/bean/DefaultClassProvider.java
Java
apache-2.0
1,631
/* * Copyright (C) 2008 ZXing 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 com.github.barcodeeye.scan.ui; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import com.github.barcodeeye.R; import com.google.zxing.ResultPoint; import com.google.zxing.ResultPointCallback; import com.google.zxing.client.android.camera.CameraManager; /** * This view is overlaid on top of the camera preview. It adds the viewfinder * rectangle and partial * transparency outside it, as well as the laser scanner animation and result * points. * * @author dswitkin@google.com (Daniel Switkin) */ public final class ViewGraphView extends View { private static final int[] SCANNER_ALPHA = { 0, 64, 128, 192, 255, 192, 128, 64 }; private static final long ANIMATION_DELAY = 80L; private static final int CURRENT_POINT_OPACITY = 0xA0; private static final int MAX_RESULT_POINTS = 20; private static final int POINT_SIZE = 6; private CameraManager cameraManager; private final Paint paint; private Bitmap resultBitmap; private final int maskColor; private final int resultColor; private final int laserColor; private final int resultPointColor; private int scannerAlpha; private List<ResultPoint> possibleResultPoints; private List<ResultPoint> lastPossibleResultPoints; // This constructor is used when the class is built from an XML resource. public ViewGraphView(Context context, AttributeSet attrs) { super(context, attrs); // Initialize these once for performance rather than calling them every time in onDraw(). paint = new Paint(Paint.ANTI_ALIAS_FLAG); Resources resources = getResources(); maskColor = resources.getColor(R.color.viewfinder_mask); resultColor = resources.getColor(R.color.result_view); laserColor = resources.getColor(R.color.viewfinder_laser); resultPointColor = resources.getColor(R.color.possible_result_points); scannerAlpha = 0; possibleResultPoints = new ArrayList<ResultPoint>(5); lastPossibleResultPoints = null; } public void setCameraManager(CameraManager cameraManager) { this.cameraManager = cameraManager; } @Override public void onDraw(Canvas canvas) { if (cameraManager == null) { return; // not ready yet, early draw before done configuring } Rect frame = cameraManager.getFramingRect(); Rect previewFrame = cameraManager.getFramingRectInPreview(); if (frame == null || previewFrame == null) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); // Draw the exterior (i.e. outside the framing rect) darkened paint.setColor(resultBitmap != null ? resultColor : maskColor); canvas.drawRect(0, 0, width, frame.top, paint); canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint); canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint); canvas.drawRect(0, frame.bottom + 1, width, height, paint); if (resultBitmap != null) { // Draw the opaque result bitmap over the scanning rectangle paint.setAlpha(CURRENT_POINT_OPACITY); canvas.drawBitmap(resultBitmap, null, frame, paint); } else { // Draw a red "laser scanner" line through the middle to show decoding is active paint.setColor(laserColor); paint.setAlpha(SCANNER_ALPHA[scannerAlpha]); scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length; int middle = frame.height() / 2 + frame.top; canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint); float scaleX = frame.width() / (float) previewFrame.width(); float scaleY = frame.height() / (float) previewFrame.height(); List<ResultPoint> currentPossible = possibleResultPoints; List<ResultPoint> currentLast = lastPossibleResultPoints; int frameLeft = frame.left; int frameTop = frame.top; if (currentPossible.isEmpty()) { lastPossibleResultPoints = null; } else { possibleResultPoints = new ArrayList<ResultPoint>(5); lastPossibleResultPoints = currentPossible; paint.setAlpha(CURRENT_POINT_OPACITY); paint.setColor(resultPointColor); synchronized (currentPossible) { for (ResultPoint point : currentPossible) { canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), frameTop + (int) (point.getY() * scaleY), POINT_SIZE, paint); } } } if (currentLast != null) { paint.setAlpha(CURRENT_POINT_OPACITY / 2); paint.setColor(resultPointColor); synchronized (currentLast) { float radius = POINT_SIZE / 2.0f; for (ResultPoint point : currentLast) { canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), frameTop + (int) (point.getY() * scaleY), radius, paint); } } } // Request another update at the animation interval, but only repaint the laser line, // not the entire viewfinder mask. postInvalidateDelayed(ANIMATION_DELAY, frame.left - POINT_SIZE, frame.top - POINT_SIZE, frame.right + POINT_SIZE, frame.bottom + POINT_SIZE); } } public void drawViewfinder() { Bitmap resultBitmap = this.resultBitmap; this.resultBitmap = null; if (resultBitmap != null) { resultBitmap.recycle(); } invalidate(); } /** * Draw a bitmap with the result points highlighted instead of the live * scanning display. * * @param barcode * An image of the decoded barcode. */ public void drawResultBitmap(Bitmap barcode) { resultBitmap = barcode; invalidate(); } public void addPossibleResultPoint(ResultPoint point) { List<ResultPoint> points = possibleResultPoints; synchronized (points) { points.add(point); int size = points.size(); if (size > MAX_RESULT_POINTS) { // trim it points.subList(0, size - MAX_RESULT_POINTS / 2).clear(); } } } public static final class ViewfinderResultPointCallback implements ResultPointCallback { private final ViewGraphView viewfinderView; public ViewfinderResultPointCallback(ViewGraphView viewfinderView) { this.viewfinderView = viewfinderView; } @Override public void foundPossibleResultPoint(ResultPoint point) { viewfinderView.addPossibleResultPoint(point); } } }
Statoil/hack3
src/com/github/barcodeeye/scan/ui/ViewGraphView.java
Java
apache-2.0
8,020
package org.zstack.image; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.http.HttpHeaders; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.header.apimediator.ApiMessageInterceptionException; import org.zstack.header.core.BypassWhenUnitTest; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.identity.Quota; import org.zstack.header.image.APIAddImageMsg; import org.zstack.header.image.ImageVO; import org.zstack.header.rest.RESTFacade; import org.zstack.header.storage.backup.*; import org.zstack.identity.QuotaUtil; import org.zstack.utils.Utils; import org.zstack.utils.logging.CLogger; import javax.persistence.TypedQuery; import java.util.Map; /** * Created by miao on 16-10-9. */ @Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class ImageQuotaUtil { private static final CLogger logger = Utils.getLogger(ImageQuotaUtil.class); @Autowired public DatabaseFacade dbf; @Autowired private ErrorFacade errf; @Autowired private CloudBus bus; @Autowired protected RESTFacade restf; public class ImageQuota { public long imageNum; public long imageSize; } @Transactional(readOnly = true) public ImageQuota getUsed(String accountUUid) { ImageQuota quota = new ImageQuota(); quota.imageSize = getUsedImageSize(accountUUid); quota.imageNum = getUsedImageNum(accountUUid); return quota; } @Transactional(readOnly = true) public long getUsedImageNum(String accountUuid) { String sql = "select count(image) " + " from ImageVO image, AccountResourceRefVO ref " + " where image.uuid = ref.resourceUuid " + " and ref.accountUuid = :auuid " + " and ref.resourceType = :rtype "; TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("auuid", accountUuid); q.setParameter("rtype", ImageVO.class.getSimpleName()); Long imageNum = q.getSingleResult(); imageNum = imageNum == null ? 0 : imageNum; return imageNum; } @Transactional(readOnly = true) public long getUsedImageSize(String accountUuid) { String sql = "select sum(image.actualSize) " + " from ImageVO image ,AccountResourceRefVO ref " + " where image.uuid = ref.resourceUuid " + " and ref.accountUuid = :auuid " + " and ref.resourceType = :rtype "; TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("auuid", accountUuid); q.setParameter("rtype", ImageVO.class.getSimpleName()); Long imageSize = q.getSingleResult(); imageSize = imageSize == null ? 0 : imageSize; return imageSize; } @BypassWhenUnitTest public void checkImageSizeQuotaUseHttpHead(APIAddImageMsg msg, Map<String, Quota.QuotaPair> pairs) { long imageSizeQuota = pairs.get(ImageQuotaConstant.IMAGE_SIZE).getValue(); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(msg.getSession().getAccountUuid()); long imageSizeAsked = getLocalImageSizeOnBackupStorage(msg); if ((imageSizeQuota == 0) || (imageSizeUsed + imageSizeAsked > imageSizeQuota)) { throw new ApiMessageInterceptionException(new QuotaUtil().buildQuataExceedError( msg.getSession().getAccountUuid(), ImageQuotaConstant.IMAGE_SIZE, imageSizeQuota)); } } public long getLocalImageSizeOnBackupStorage(APIAddImageMsg msg) { long imageSizeAsked = 0; final String url = msg.getUrl().trim(); if (url.startsWith("file:///")) { GetLocalFileSizeOnBackupStorageMsg gmsg = new GetLocalFileSizeOnBackupStorageMsg(); String bsUuid = msg.getBackupStorageUuids().get(0); gmsg.setBackupStorageUuid(bsUuid); gmsg.setUrl(url.split("://")[1]); bus.makeTargetServiceIdByResourceUuid(gmsg, BackupStorageConstant.SERVICE_ID, bsUuid); GetLocalFileSizeOnBackupStorageReply reply = (GetLocalFileSizeOnBackupStorageReply) bus.call(gmsg); if (!reply.isSuccess()) { logger.warn(String.format("cannot get image. The image url : %s. description: %s.name: %s", url, msg.getDescription(), msg.getName())); throw new OperationFailureException(reply.getError()); } else { imageSizeAsked = reply.getSize(); } } else if (url.startsWith("http") || url.startsWith("https")) { String len = null; HttpHeaders header = restf.getRESTTemplate().headForHeaders(url); try { len = header.getFirst("Content-Length"); } catch (Exception e) { logger.warn(String.format("cannot get image. The image url : %s. description: %s.name: %s", url, msg.getDescription(), msg.getName())); } imageSizeAsked = len == null ? 0 : Long.valueOf(len); } return imageSizeAsked; } }
AlanJager/zstack
image/src/main/java/org/zstack/image/ImageQuotaUtil.java
Java
apache-2.0
5,501