repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
metafacture/metafacture-core
metafacture-biblio/src/test/java/org/metafacture/biblio/pica/PicaDecoderTest.java
20668
/* * Copyright 2016-2019 Christoph Böhme and hbz * * 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.metafacture.biblio.pica; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.metafacture.framework.MissingIdException; import org.metafacture.framework.StreamReceiver; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** * Tests for class {@link PicaDecoder}. * * @author Christoph Böhme * @author Pascal Christoph (dr0i) * */ public final class PicaDecoderTest { private static final String RECORD_ID = "2809"; private static final String ENTITY_028A = "028A"; private static final String NAME_A = "a"; private static final String NAME_D = "d"; private static final String VALUE_A = "Eco"; private static final String VALUE_D = "Umberto"; private static final String COMPOSED_UTF8 = "Über"; // 'Ü' constructed from U and diacritics private static final String STANDARD_UTF8 = "Über"; // 'Ü' is a single character private static final String RECORD_MARKER = "\u001d"; private static final String FIELD_MARKER = "\u001e"; private static final String SUBFIELD_MARKER = "\u001f"; private static final String FIELD_END_MARKER = "\n"; private static final String NONNORMALIZED_RECORD_MARKER = "\n"; private static final String NONNORMALIZED_SUBFIELD_MARKER = "$"; private static final String NONNORMALIZED_FIELD_END_MARKER = "\n"; private static final String FIELD_001AT_0_TEST = "001@ " + SUBFIELD_MARKER + "0test"; private static final String FIELD_003AT_0_ID = "003@ " + SUBFIELD_MARKER + "0" + RECORD_ID; private static final String FIELD_107F_0_ID = "107F " + SUBFIELD_MARKER + "0" + RECORD_ID; private static final String FIELD_203AT_0_ID = "203@ " + SUBFIELD_MARKER + "0" + RECORD_ID; private static final String FIELD_203AT_01_0_ID = "203@/01 " + SUBFIELD_MARKER + "0" + RECORD_ID; private static final String FIELD_203AT_100_0_ID = "203@/100 " + SUBFIELD_MARKER + "0" + RECORD_ID; private static final String FIELD_021A_A_UEBER = "021A " + SUBFIELD_MARKER + "a" + COMPOSED_UTF8; private static final String FIELD_028A = ENTITY_028A + " "; private static final String NONNORMALIZED_FIELD_001AT_0_TEST = "001@ " + NONNORMALIZED_SUBFIELD_MARKER + "0test"; private static final String NONNORMALIZED_FIELD_003AT_0_ID = "003@ " + NONNORMALIZED_SUBFIELD_MARKER + "0" + RECORD_ID; private PicaDecoder picaDecoder; @Mock private StreamReceiver receiver; @Before public void setup() { MockitoAnnotations.initMocks(this); picaDecoder = new PicaDecoder(); picaDecoder.setReceiver(receiver); } @After public void cleanup() { picaDecoder.closeStream(); } @Test public void shouldParseRecordStartingWithRecordMarker() { picaDecoder.process( RECORD_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordStartingWithFieldMarker() { picaDecoder.process( FIELD_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordStartingWithSubfieldMarker() { picaDecoder.process( SUBFIELD_MARKER + NAME_A + VALUE_A + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); ordered.verify(receiver).startEntity(""); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).endEntity(); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordStartingWithEmptySubfield() { picaDecoder.process( SUBFIELD_MARKER + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordStartingWithFieldEndMarker() { picaDecoder.process( FIELD_END_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordStartingWithFieldName() { picaDecoder.process( FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordEndingWithRecordMarker() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_001AT_0_TEST + RECORD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); verify001At0Test(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordEndingWithFieldMarker() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); verify001At0Test(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordEndingWithSubfieldMarker() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + NAME_A + VALUE_A + SUBFIELD_MARKER + NAME_D + VALUE_D + SUBFIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).literal(NAME_D, VALUE_D); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordEndingWithSubfieldName() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + NAME_A + VALUE_A + SUBFIELD_MARKER + NAME_D); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).literal(NAME_D, ""); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); } @Test public void shouldParseRecordEndingWithFieldName() { // Do not skip the last field because it has no // sub fields: picaDecoder.setSkipEmptyFields(false); picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); } @Test public void shouldParseMultiLineRecordFormat() { picaDecoder.process( RECORD_MARKER + FIELD_END_MARKER + FIELD_MARKER + FIELD_001AT_0_TEST + FIELD_END_MARKER + FIELD_MARKER + FIELD_003AT_0_ID + FIELD_END_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldExtractPicaProductionNumberAfterRecordMarkerAsRecordId() { picaDecoder.process(RECORD_MARKER + FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractPicaProductionNumberAfterFieldMarkerAsRecordId() { picaDecoder.process(FIELD_MARKER + FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractPicaProductionNumberAfterFieldEndMarkerAsRecordId() { picaDecoder.process(FIELD_END_MARKER + FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractPicaProductionNumberFollowedByRecordMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + RECORD_MARKER); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractPicaProductionNumberFollowedByFieldMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + FIELD_MARKER); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractPicaProductionNumberFollowedBySubfieldMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + SUBFIELD_MARKER); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractPicaProductionNumberFollowedByFieldEndMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + FIELD_END_MARKER); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractPicaProductionNumberAtRecordEndAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractLocalProductionNumberAsRecordId() { picaDecoder.process(FIELD_107F_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractCopyControlNumberAsRecordId() { picaDecoder.process(FIELD_203AT_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractCopyControlNumberWithOccurrenceAsRecordId() { picaDecoder.process(FIELD_203AT_01_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test public void shouldExtractCopyControlNumberWithThreeDigitOccurrenceAsRecordId() { picaDecoder.process(FIELD_203AT_100_0_ID); verify(receiver).startRecord(RECORD_ID); } @Test(expected=MissingIdException.class) public void shouldThrowMissingIdExceptionIfNoRecordIdIsFound() { picaDecoder.process(FIELD_001AT_0_TEST); // Exception expected } @Test public void shouldIgnoreMatchWithinFieldData() { picaDecoder.setIgnoreMissingIdn(true); picaDecoder.process(FIELD_001AT_0_TEST + FIELD_003AT_0_ID); verify(receiver).startRecord(""); } @Test public void shouldIgnoreIncompleteMatch() { picaDecoder.setIgnoreMissingIdn(true); picaDecoder.process("003@ " + FIELD_MARKER + FIELD_001AT_0_TEST); verify(receiver).startRecord(""); } @Test public void shouldSkipUnnamedFieldsWithNoSubFields() { // Make sure that the field is skipped because // it is empty and not because it has no sub // fields: picaDecoder.setSkipEmptyFields(false); picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); } @Test public void shouldSkipUnnamedFieldsWithOnlyUnnamedSubFields() { // Make sure that the field is skipped because // it is empty and not because it only has empty // sub fields: picaDecoder.setSkipEmptyFields(false); picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + SUBFIELD_MARKER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); } @Test public void shouldNotSkipUnnamedFieldsWithSubFields() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + SUBFIELD_MARKER + NAME_A + VALUE_A + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(""); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); } @Test public void shouldSkipUnnamedSubfields() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + SUBFIELD_MARKER + NAME_A + VALUE_A + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); } @Test public void shouldSkipEmptyFieldsByDefault() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); } @Test public void shouldSkipFieldsWithOnlyUnnamedSubfieldsByDefault() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); } @Test public void shouldNotSkipEmptyFieldsIfConfigured() { picaDecoder.setSkipEmptyFields(false); picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); } @Test public void shouldNotSkipFieldsWithOnlyUnnamedSubfieldsIfConfigured() { picaDecoder.setSkipEmptyFields(false); picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); } @Test(expected=MissingIdException.class) public void shouldFailIfIdIsMissingByDefault() { picaDecoder.process( FIELD_001AT_0_TEST + FIELD_MARKER); } @Test public void shouldIgnoreMissingIdIfConfigured() { picaDecoder.setIgnoreMissingIdn(true); picaDecoder.process( FIELD_001AT_0_TEST + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); verify001At0Test(ordered); ordered.verify(receiver).endRecord(); } @Test public void shouldNotNormalizeUTF8ByDefault() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_021A_A_UEBER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); verify021AAUeber(ordered, COMPOSED_UTF8); ordered.verify(receiver).endRecord(); } @Test public void shouldNormalizeUTF8IfConfigured() { picaDecoder.setNormalizeUTF8(true); picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_021A_A_UEBER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); verify021AAUeber(ordered, STANDARD_UTF8); ordered.verify(receiver).endRecord(); } @Test public void shouldTrimWhitespaceInFieldNamesByDefault() { picaDecoder.process( " fieldname " + SUBFIELD_MARKER + "0subfield" + FIELD_MARKER + FIELD_003AT_0_ID); verify(receiver).startEntity("fieldname"); } @Test public void shouldNotTrimWhitespaceInFieldNamesIfConfigured() { picaDecoder.setTrimFieldNames(false); picaDecoder.process( " fieldname " + SUBFIELD_MARKER + "0subfield" + FIELD_MARKER + FIELD_003AT_0_ID); verify(receiver).startEntity(" fieldname "); } @Test public void nonNormalizedPica() { picaDecoder.setNormalizedSerialization(false); picaDecoder.process( NONNORMALIZED_FIELD_001AT_0_TEST + NONNORMALIZED_FIELD_END_MARKER + NONNORMALIZED_FIELD_003AT_0_ID + NONNORMALIZED_RECORD_MARKER); try { verify(receiver).startEntity("001@"); verify(receiver).literal("0", "test"); verify(receiver).startEntity("003@"); verify(receiver).literal("0", "2809"); } finally { //ensure reset to the default used by the other tests picaDecoder.setNormalizedSerialization(true); } } private void verify003At0ID(final InOrder ordered) { ordered.verify(receiver).startEntity("003@"); ordered.verify(receiver).literal("0", RECORD_ID); ordered.verify(receiver).endEntity(); } private void verify001At0Test(final InOrder ordered) { ordered.verify(receiver).startEntity("001@"); ordered.verify(receiver).literal("0", "test"); ordered.verify(receiver).endEntity(); } private void verify021AAUeber(final InOrder ordered, final String value) { ordered.verify(receiver).startEntity("021A"); ordered.verify(receiver).literal("a", value); ordered.verify(receiver).endEntity(); } }
apache-2.0
kierarad/gocd
plugin-infra/go-plugin-access/src/test/java/com/thoughtworks/go/plugin/access/elastic/ElasticAgentPluginRegistryTest.java
7628
/* * Copyright 2019 ThoughtWorks, 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.thoughtworks.go.plugin.access.elastic; import com.thoughtworks.go.domain.ClusterProfilesChangedStatus; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.plugin.access.elastic.models.AgentMetadata; import com.thoughtworks.go.plugin.infra.PluginManager; import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; public class ElasticAgentPluginRegistryTest { private static final String PLUGIN_ID = "cd.go.example.plugin"; @Mock private PluginManager pluginManager; @Mock private ElasticAgentExtension elasticAgentExtension; @Mock private GoPluginDescriptor pluginDescriptor; private ElasticAgentPluginRegistry elasticAgentPluginRegistry; @Before public void setUp() throws Exception { initMocks(this); elasticAgentPluginRegistry = new ElasticAgentPluginRegistry(pluginManager, elasticAgentExtension); when(elasticAgentExtension.canHandlePlugin(PLUGIN_ID)).thenReturn(true); when(pluginDescriptor.id()).thenReturn(PLUGIN_ID); elasticAgentPluginRegistry.pluginLoaded(pluginDescriptor); verify(elasticAgentExtension, times(1)).canHandlePlugin(PLUGIN_ID); } @Test public void shouldTalkToExtensionToCreateElasticAgent() { final Map<String, String> configuration = Collections.singletonMap("GoServerURL", "foo"); final Map<String, String> clusterConfiguration = Collections.singletonMap("GoServerURL", "foo"); final JobIdentifier jobIdentifier = new JobIdentifier(); final String autoRegisterKey = "auto-register-key"; final String environment = "test-env"; elasticAgentPluginRegistry.createAgent(PLUGIN_ID, autoRegisterKey, environment, configuration, clusterConfiguration, jobIdentifier); verify(elasticAgentExtension, times(1)).createAgent(PLUGIN_ID, autoRegisterKey, environment, configuration, clusterConfiguration, jobIdentifier); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldTalkToExtensionToExecuteServerPingCall() { final Map<String, String> clusterProfileProperties = Collections.singletonMap("GoServerURL", "foo"); elasticAgentPluginRegistry.serverPing(PLUGIN_ID, Arrays.asList(clusterProfileProperties)); verify(elasticAgentExtension, times(1)).serverPing(PLUGIN_ID, Arrays.asList(clusterProfileProperties)); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldTalkToExtensionToExecuteShouldAssignWorkCall() { final String environment = "test-env"; final JobIdentifier jobIdentifier = new JobIdentifier(); final Map<String, String> configuration = Collections.singletonMap("Image", "alpine:latest"); final Map<String, String> clusterProfileProperties = Collections.singletonMap("GoServerURL", "foo"); final AgentMetadata agentMetadata = new AgentMetadata("som-id", "Idle", "Idle", "Enabled"); elasticAgentPluginRegistry.shouldAssignWork(pluginDescriptor, agentMetadata, environment, configuration, clusterProfileProperties, jobIdentifier); verify(elasticAgentExtension, times(1)).shouldAssignWork(PLUGIN_ID, agentMetadata, environment, configuration, clusterProfileProperties, jobIdentifier); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldTalkToExtensionToGetPluginStatusReport() { List<Map<String, String>> clusterProfiles = Collections.emptyList(); elasticAgentPluginRegistry.getPluginStatusReport(PLUGIN_ID, clusterProfiles); verify(elasticAgentExtension, times(1)).getPluginStatusReport(PLUGIN_ID, clusterProfiles); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldTalkToExtensionToGetAgentStatusReport() { final JobIdentifier jobIdentifier = new JobIdentifier(); elasticAgentPluginRegistry.getAgentStatusReport(PLUGIN_ID, jobIdentifier, "some-id", null); verify(elasticAgentExtension, times(1)).getAgentStatusReport(PLUGIN_ID, jobIdentifier, "some-id", null); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldTalkToExtensionToGetClusterStatusReport() { Map<String, String> clusterProfileConfigurations = Collections.emptyMap(); elasticAgentPluginRegistry.getClusterStatusReport(PLUGIN_ID, clusterProfileConfigurations); verify(elasticAgentExtension, times(1)).getClusterStatusReport(PLUGIN_ID, clusterProfileConfigurations); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldTalkToExtensionToReportJobCompletion() { final JobIdentifier jobIdentifier = new JobIdentifier(); final String elasticAgentId = "ea_1"; final Map<String, String> elasticProfileConfiguration = Collections.singletonMap("Image", "alpine:latest"); final Map<String, String> clusterProfileConfiguration = Collections.singletonMap("ServerURL", "https://example.com/go"); elasticAgentPluginRegistry.reportJobCompletion(PLUGIN_ID, elasticAgentId, jobIdentifier, elasticProfileConfiguration, clusterProfileConfiguration); verify(elasticAgentExtension, times(1)).reportJobCompletion(PLUGIN_ID, elasticAgentId, jobIdentifier, elasticProfileConfiguration, clusterProfileConfiguration); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldTalkToExtensionToNotifyClusterProfileHasChanged() { final Map<String, String> newClusterProfileConfigurations = Collections.singletonMap("Image", "alpine:latest"); elasticAgentPluginRegistry.notifyPluginAboutClusterProfileChanged(PLUGIN_ID, ClusterProfilesChangedStatus.CREATED, null, newClusterProfileConfigurations); verify(elasticAgentExtension, times(1)).clusterProfileChanged(PLUGIN_ID, ClusterProfilesChangedStatus.CREATED, null, newClusterProfileConfigurations); verifyNoMoreInteractions(elasticAgentExtension); } @Test public void shouldNotFailEvenWhenExtensionFailsToHandleClusterProfileChangedCall() { final Map<String, String> newClusterProfileConfigurations = Collections.singletonMap("Image", "alpine:latest"); doThrow(new RuntimeException("Boom!")).when(elasticAgentExtension).clusterProfileChanged(any(), any(), any(), any()); elasticAgentPluginRegistry.notifyPluginAboutClusterProfileChanged(PLUGIN_ID, ClusterProfilesChangedStatus.CREATED, null, newClusterProfileConfigurations); verify(elasticAgentExtension, times(1)).clusterProfileChanged(PLUGIN_ID, ClusterProfilesChangedStatus.CREATED, null, newClusterProfileConfigurations); verifyNoMoreInteractions(elasticAgentExtension); } }
apache-2.0
mkjasinski/commons
payments-subscriptions/src/main/java/pl/com/softproject/commons/payment/model/PaymentStatus.java
230
/* * Copyright 2015-08-18 the original author or authors. */ package pl.com.softproject.commons.payment.model; /** * * @author Adrian Lapierre <adrian@soft-project.pl> */ public enum PaymentStatus { NEW, PENDING, MADE }
apache-2.0
bboyfeiyu/Android-CleanArchitecture
data/src/main/java/com/fernandocejas/android10/sample/data/cache/FileManager.java
4367
/** * Copyright (C) 2014 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.sample.data.cache; import android.content.Context; import android.content.SharedPreferences; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.inject.Inject; import javax.inject.Singleton; /** * Helper class to do operations on regular files/directories. */ @Singleton public class FileManager { @Inject public FileManager() {} /** * Writes a file to Disk. * This is an I/O operation and this method executes in the main thread, so it is recommended to * perform this operation using another thread. * * @param file The file to write to Disk. */ public void writeToFile(File file, String fileContent) { if (!file.exists()) { try { FileWriter writer = new FileWriter(file); writer.write(fileContent); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } } /** * Reads a content from a file. * This is an I/O operation and this method executes in the main thread, so it is recommended to * perform the operation using another thread. * * @param file The file to read from. * @return A string with the content of the file. */ public String readFileContent(File file) { StringBuilder fileContentBuilder = new StringBuilder(); if (file.exists()) { String stringLine; try { FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); while ((stringLine = bufferedReader.readLine()) != null) { fileContentBuilder.append(stringLine + "\n"); } bufferedReader.close(); fileReader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return fileContentBuilder.toString(); } /** * Returns a boolean indicating whether this file can be found on the underlying file system. * * @param file The file to check existence. * @return true if this file exists, false otherwise. */ public boolean exists(File file) { return file.exists(); } /** * Warning: Deletes the content of a directory. * This is an I/O operation and this method executes in the main thread, so it is recommended to * perform the operation using another thread. * * @param directory The directory which its content will be deleted. */ public void clearDirectory(File directory) { if (directory.exists()) { for (File file : directory.listFiles()) { file.delete(); } } } /** * Write a value to a user preferences file. * * @param context {@link android.content.Context} to retrieve android user preferences. * @param preferenceFileName A file name reprensenting where data will be written to. * @param key A string for the key that will be used to retrieve the value in the future. * @param value A long representing the value to be inserted. */ public void writeToPreferences(Context context, String preferenceFileName, String key, long value) { SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(key, value); editor.apply(); } /** * Get a value from a user preferences file. * * @param context {@link android.content.Context} to retrieve android user preferences. * @param preferenceFileName A file name representing where data will be get from. * @param key A key that will be used to retrieve the value from the preference file. * @return A long representing the value retrieved from the preferences file. */ public long getFromPreferences(Context context, String preferenceFileName, String key) { SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, Context.MODE_PRIVATE); return sharedPreferences.getLong(key, 0); } }
apache-2.0
zentol/flink
flink-state-backends/flink-statebackend-changelog/src/main/java/org/apache/flink/state/changelog/ChangelogKeyedStateBackend.java
36483
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.state.changelog; import org.apache.flink.annotation.Internal; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.state.CheckpointListener; import org.apache.flink.api.common.state.State; import org.apache.flink.api.common.state.StateDescriptor; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.checkpoint.CheckpointType; import org.apache.flink.runtime.state.AbstractKeyedStateBackend; import org.apache.flink.runtime.state.CheckpointStateOutputStream; import org.apache.flink.runtime.state.CheckpointStorageLocationReference; import org.apache.flink.runtime.state.CheckpointStorageWorkerView; import org.apache.flink.runtime.state.CheckpointStreamFactory; import org.apache.flink.runtime.state.CheckpointableKeyedStateBackend; import org.apache.flink.runtime.state.CheckpointedStateScope; import org.apache.flink.runtime.state.KeyGroupRange; import org.apache.flink.runtime.state.KeyGroupedInternalPriorityQueue; import org.apache.flink.runtime.state.Keyed; import org.apache.flink.runtime.state.KeyedStateBackend; import org.apache.flink.runtime.state.KeyedStateFunction; import org.apache.flink.runtime.state.KeyedStateHandle; import org.apache.flink.runtime.state.PriorityComparable; import org.apache.flink.runtime.state.RegisteredKeyValueStateBackendMetaInfo; import org.apache.flink.runtime.state.RegisteredPriorityQueueStateBackendMetaInfo; import org.apache.flink.runtime.state.SavepointResources; import org.apache.flink.runtime.state.SnapshotResult; import org.apache.flink.runtime.state.StateSnapshotTransformer; import org.apache.flink.runtime.state.StreamStateHandle; import org.apache.flink.runtime.state.TestableKeyedStateBackend; import org.apache.flink.runtime.state.changelog.ChangelogStateBackendHandle; import org.apache.flink.runtime.state.changelog.ChangelogStateBackendHandle.ChangelogStateBackendHandleImpl; import org.apache.flink.runtime.state.changelog.ChangelogStateHandle; import org.apache.flink.runtime.state.changelog.SequenceNumber; import org.apache.flink.runtime.state.changelog.StateChangelogWriter; import org.apache.flink.runtime.state.heap.HeapPriorityQueueElement; import org.apache.flink.runtime.state.heap.InternalKeyContext; import org.apache.flink.runtime.state.internal.InternalKvState; import org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot.BackendStateType; import org.apache.flink.runtime.state.metrics.LatencyTrackingStateFactory; import org.apache.flink.runtime.state.ttl.TtlStateFactory; import org.apache.flink.runtime.state.ttl.TtlTimeProvider; import org.apache.flink.state.changelog.restore.FunctionDelegationHelper; import org.apache.flink.util.FlinkRuntimeException; import org.apache.flink.shaded.guava30.com.google.common.io.Closer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.NoSuchElementException; import java.util.Optional; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.RunnableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.Collections.unmodifiableList; import static org.apache.flink.state.changelog.PeriodicMaterializationManager.MaterializationRunnable; import static org.apache.flink.util.Preconditions.checkNotNull; /** * A {@link KeyedStateBackend} that keeps state on the underlying delegated keyed state backend as * well as on the state change log. * * @param <K> The key by which state is keyed. */ @Internal public class ChangelogKeyedStateBackend<K> implements CheckpointableKeyedStateBackend<K>, CheckpointListener, TestableKeyedStateBackend<K> { private static final Logger LOG = LoggerFactory.getLogger(ChangelogKeyedStateBackend.class); /** * ChangelogStateBackend only supports CheckpointType.CHECKPOINT; The rest of information in * CheckpointOptions is not used in Snapshotable#snapshot(). More details in FLINK-23441. */ private static final CheckpointOptions CHECKPOINT_OPTIONS = new CheckpointOptions( CheckpointType.CHECKPOINT, CheckpointStorageLocationReference.getDefault()); private static final Map<StateDescriptor.Type, StateFactory> STATE_FACTORIES = Stream.of( Tuple2.of( StateDescriptor.Type.VALUE, (StateFactory) ChangelogValueState::create), Tuple2.of( StateDescriptor.Type.LIST, (StateFactory) ChangelogListState::create), Tuple2.of( StateDescriptor.Type.REDUCING, (StateFactory) ChangelogReducingState::create), Tuple2.of( StateDescriptor.Type.AGGREGATING, (StateFactory) ChangelogAggregatingState::create), Tuple2.of( StateDescriptor.Type.MAP, (StateFactory) ChangelogMapState::create)) .collect(Collectors.toMap(t -> t.f0, t -> t.f1)); /** delegated keyedStateBackend. */ private final AbstractKeyedStateBackend<K> keyedStateBackend; /** * This is the cache maintained by the DelegateKeyedStateBackend itself. It is not the same as * the underlying delegated keyedStateBackend. InternalKvState is a delegated state. */ private final Map<String, InternalKvState<K, ?, ?>> keyValueStatesByName; /** * Unwrapped changelog states used for recovery (not wrapped into e.g. TTL, latency tracking). */ private final Map<String, ChangelogState> changelogStates; private final Map<String, ChangelogKeyGroupedPriorityQueue<?>> priorityQueueStatesByName; private final ExecutionConfig executionConfig; private final TtlTimeProvider ttlTimeProvider; private final StateChangelogWriter<? extends ChangelogStateHandle> stateChangelogWriter; private final Closer closer = Closer.create(); private final CheckpointStreamFactory streamFactory; private ChangelogSnapshotState changelogSnapshotState; private long lastCheckpointId = -1L; private long materializedId = 0; /** last accessed partitioned state. */ @SuppressWarnings("rawtypes") private InternalKvState lastState; /** For caching the last accessed partitioned state. */ private String lastName; private final FunctionDelegationHelper functionDelegationHelper = new FunctionDelegationHelper(); /** * {@link SequenceNumber} denoting last upload range <b>start</b>, inclusive. Updated to {@link * ChangelogSnapshotState#materializedTo} when {@link #snapshot(long, long, * CheckpointStreamFactory, CheckpointOptions) starting snapshot}. Used to notify {@link * #stateChangelogWriter} about changelog ranges that were confirmed or aborted by JM. */ @Nullable private SequenceNumber lastUploadedFrom; /** * {@link SequenceNumber} denoting last upload range <b>end</b>, exclusive. Updated to {@link * org.apache.flink.runtime.state.changelog.StateChangelogWriter#lastAppendedSequenceNumber} * when {@link #snapshot(long, long, CheckpointStreamFactory, CheckpointOptions) starting * snapshot}. Used to notify {@link #stateChangelogWriter} about changelog ranges that were * confirmed or aborted by JM. */ @Nullable private SequenceNumber lastUploadedTo; private final String subtaskName; /** * Provides a unique ID for each state created by this backend instance. A mapping from this ID * to state name is written once along with metadata; afterwards, only ID is written with each * state change for efficiency. */ private short lastCreatedStateId = -1; /** Checkpoint ID mapped to Materialization ID - used to notify nested backend of completion. */ private final NavigableMap<Long, Long> materializationIdByCheckpointId = new TreeMap<>(); private long lastConfirmedMaterializationId = -1L; public ChangelogKeyedStateBackend( AbstractKeyedStateBackend<K> keyedStateBackend, String subtaskName, ExecutionConfig executionConfig, TtlTimeProvider ttlTimeProvider, StateChangelogWriter<? extends ChangelogStateHandle> stateChangelogWriter, Collection<ChangelogStateBackendHandle> initialState, CheckpointStorageWorkerView checkpointStorageWorkerView) { this.keyedStateBackend = keyedStateBackend; this.subtaskName = subtaskName; this.executionConfig = executionConfig; this.ttlTimeProvider = ttlTimeProvider; this.keyValueStatesByName = new HashMap<>(); this.priorityQueueStatesByName = new HashMap<>(); this.stateChangelogWriter = stateChangelogWriter; this.changelogStates = new HashMap<>(); this.changelogSnapshotState = completeRestore(initialState); this.streamFactory = new CheckpointStreamFactory() { @Override public CheckpointStateOutputStream createCheckpointStateOutputStream( CheckpointedStateScope scope) throws IOException { return checkpointStorageWorkerView.createTaskOwnedStateStream(); } @Override public boolean canFastDuplicate( StreamStateHandle stateHandle, CheckpointedStateScope scope) throws IOException { return false; } @Override public List<StreamStateHandle> duplicate( List<StreamStateHandle> stateHandles, CheckpointedStateScope scope) throws IOException { return null; } }; this.closer.register(keyedStateBackend); } // -------------------- CheckpointableKeyedStateBackend -------------------------------- @Override public KeyGroupRange getKeyGroupRange() { return keyedStateBackend.getKeyGroupRange(); } @Override public void close() throws IOException { closer.close(); } @Override public void setCurrentKey(K newKey) { keyedStateBackend.setCurrentKey(newKey); } @Override public K getCurrentKey() { return keyedStateBackend.getCurrentKey(); } @Override public TypeSerializer<K> getKeySerializer() { return keyedStateBackend.getKeySerializer(); } @Override public <N> Stream<K> getKeys(String state, N namespace) { return keyedStateBackend.getKeys(state, namespace); } @Override public <N> Stream<Tuple2<K, N>> getKeysAndNamespaces(String state) { return keyedStateBackend.getKeysAndNamespaces(state); } @Override public void dispose() { keyedStateBackend.dispose(); lastName = null; lastState = null; keyValueStatesByName.clear(); changelogStates.clear(); priorityQueueStatesByName.clear(); } @Override public void registerKeySelectionListener(KeySelectionListener<K> listener) { keyedStateBackend.registerKeySelectionListener(listener); } @Override public boolean deregisterKeySelectionListener(KeySelectionListener<K> listener) { return keyedStateBackend.deregisterKeySelectionListener(listener); } @Override public <N, S extends State, T> void applyToAllKeys( N namespace, TypeSerializer<N> namespaceSerializer, StateDescriptor<S, T> stateDescriptor, KeyedStateFunction<K, S> function) throws Exception { keyedStateBackend.applyToAllKeys( namespace, namespaceSerializer, stateDescriptor, function, this::getPartitionedState); } @Override @SuppressWarnings("unchecked") public <N, S extends State> S getPartitionedState( N namespace, TypeSerializer<N> namespaceSerializer, StateDescriptor<S, ?> stateDescriptor) throws Exception { checkNotNull(namespace, "Namespace"); if (lastName != null && lastName.equals(stateDescriptor.getName())) { lastState.setCurrentNamespace(namespace); return (S) lastState; } final InternalKvState<K, ?, ?> previous = keyValueStatesByName.get(stateDescriptor.getName()); if (previous != null) { lastState = previous; lastState.setCurrentNamespace(namespace); lastName = stateDescriptor.getName(); functionDelegationHelper.addOrUpdate(stateDescriptor); return (S) previous; } final S state = getOrCreateKeyedState(namespaceSerializer, stateDescriptor); final InternalKvState<K, N, ?> kvState = (InternalKvState<K, N, ?>) state; lastName = stateDescriptor.getName(); lastState = kvState; kvState.setCurrentNamespace(namespace); return state; } @Nonnull @Override public RunnableFuture<SnapshotResult<KeyedStateHandle>> snapshot( long checkpointId, long timestamp, @Nonnull CheckpointStreamFactory streamFactory, @Nonnull CheckpointOptions checkpointOptions) throws Exception { // The range to upload may overlap with the previous one(s). To reuse them, we could store // the previous results either here in the backend or in the writer. However, // materialization may truncate only a part of the previous result and the backend would // have to split it somehow for the former option, so the latter is used. lastCheckpointId = checkpointId; lastUploadedFrom = changelogSnapshotState.lastMaterializedTo(); lastUploadedTo = stateChangelogWriter.lastAppendedSequenceNumber().next(); LOG.info( "snapshot of {} for checkpoint {}, change range: {}..{}", subtaskName, checkpointId, lastUploadedFrom, lastUploadedTo); ChangelogSnapshotState changelogStateBackendStateCopy = changelogSnapshotState; materializationIdByCheckpointId.put( checkpointId, changelogStateBackendStateCopy.materializationID); return toRunnableFuture( stateChangelogWriter .persist(lastUploadedFrom) .thenApply( delta -> buildSnapshotResult( delta, changelogStateBackendStateCopy))); } private SnapshotResult<KeyedStateHandle> buildSnapshotResult( ChangelogStateHandle delta, ChangelogSnapshotState changelogStateBackendStateCopy) { // collections don't change once started and handles are immutable List<ChangelogStateHandle> prevDeltaCopy = new ArrayList<>(changelogStateBackendStateCopy.getRestoredNonMaterialized()); long persistedSizeOfThisCheckpoint = 0L; if (delta != null && delta.getStateSize() > 0) { prevDeltaCopy.add(delta); persistedSizeOfThisCheckpoint += delta.getCheckpointedSize(); } if (prevDeltaCopy.isEmpty() && changelogStateBackendStateCopy.getMaterializedSnapshot().isEmpty()) { return SnapshotResult.empty(); } else { List<KeyedStateHandle> materializedSnapshot = changelogStateBackendStateCopy.getMaterializedSnapshot(); return SnapshotResult.of( new ChangelogStateBackendHandleImpl( materializedSnapshot, prevDeltaCopy, getKeyGroupRange(), changelogStateBackendStateCopy.materializationID, persistedSizeOfThisCheckpoint)); } } @Nonnull @Override @SuppressWarnings("unchecked") public <T extends HeapPriorityQueueElement & PriorityComparable<? super T> & Keyed<?>> KeyGroupedInternalPriorityQueue<T> create( @Nonnull String stateName, @Nonnull TypeSerializer<T> byteOrderedElementSerializer) { ChangelogKeyGroupedPriorityQueue<T> queue = (ChangelogKeyGroupedPriorityQueue<T>) priorityQueueStatesByName.get(stateName); if (queue == null) { PriorityQueueStateChangeLoggerImpl<K, T> priorityQueueStateChangeLogger = new PriorityQueueStateChangeLoggerImpl<>( byteOrderedElementSerializer, keyedStateBackend.getKeyContext(), stateChangelogWriter, new RegisteredPriorityQueueStateBackendMetaInfo<>( stateName, byteOrderedElementSerializer), ++lastCreatedStateId); closer.register(priorityQueueStateChangeLogger); queue = new ChangelogKeyGroupedPriorityQueue<>( keyedStateBackend.create(stateName, byteOrderedElementSerializer), priorityQueueStateChangeLogger, byteOrderedElementSerializer); priorityQueueStatesByName.put(stateName, queue); } return queue; } @VisibleForTesting @Override public int numKeyValueStateEntries() { return keyedStateBackend.numKeyValueStateEntries(); } @Override public boolean isSafeToReuseKVState() { return keyedStateBackend.isSafeToReuseKVState(); } @Nonnull @Override public SavepointResources<K> savepoint() throws Exception { return keyedStateBackend.savepoint(); } // -------------------- CheckpointListener -------------------------------- @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { if (lastCheckpointId == checkpointId) { // Notify the writer so that it can re-use the previous uploads. Do NOT notify it about // a range status change if it is not relevant anymore. Otherwise, it could CONFIRM a // newer upload instead of the previous one. This newer upload could then be re-used // while in fact JM has discarded its results. // This might change if the log ownership changes (the method won't likely be needed). stateChangelogWriter.confirm(lastUploadedFrom, lastUploadedTo); } Long materializationID = materializationIdByCheckpointId.remove(checkpointId); if (materializationID != null) { if (materializationID > lastConfirmedMaterializationId) { keyedStateBackend.notifyCheckpointComplete(materializationID); lastConfirmedMaterializationId = materializationID; } } materializationIdByCheckpointId.headMap(checkpointId, true).clear(); } @Override public void notifyCheckpointAborted(long checkpointId) throws Exception { if (lastCheckpointId == checkpointId) { // Notify the writer so that it can clean up. Do NOT notify it about a range status // change if it is not relevant anymore. Otherwise, it could DISCARD a newer upload // instead of the previous one. Rely on truncation for the cleanup in this case. // This might change if the log ownership changes (the method won't likely be needed). stateChangelogWriter.reset(lastUploadedFrom, lastUploadedTo); } // TODO: Consider notifying nested state backend about checkpoint abortion (FLINK-25850) } // -------- Methods not simply delegating to wrapped state backend --------- @Override @SuppressWarnings("unchecked") public <N, S extends State, T> S getOrCreateKeyedState( TypeSerializer<N> namespaceSerializer, StateDescriptor<S, T> stateDescriptor) throws Exception { checkNotNull(namespaceSerializer, "Namespace serializer"); checkNotNull( getKeySerializer(), "State key serializer has not been configured in the config. " + "This operation cannot use partitioned state."); InternalKvState<K, ?, ?> kvState = keyValueStatesByName.get(stateDescriptor.getName()); // todo: support state migration (in FLINK-23143) // This method is currently called both on recovery and on user access. // So keyValueStatesByName may contain an entry for user-requested state which will // prevent state migration (in contrast to other backends). if (kvState == null) { if (!stateDescriptor.isSerializerInitialized()) { stateDescriptor.initializeSerializerUnlessSet(executionConfig); } kvState = LatencyTrackingStateFactory.createStateAndWrapWithLatencyTrackingIfEnabled( TtlStateFactory.createStateAndWrapWithTtlIfEnabled( namespaceSerializer, stateDescriptor, this, ttlTimeProvider), stateDescriptor, keyedStateBackend.getLatencyTrackingStateConfig()); keyValueStatesByName.put(stateDescriptor.getName(), kvState); keyedStateBackend.publishQueryableStateIfEnabled(stateDescriptor, kvState); } functionDelegationHelper.addOrUpdate(stateDescriptor); return (S) kvState; } @Nonnull @Override @SuppressWarnings("unchecked") public <N, SV, SEV, S extends State, IS extends S> IS createInternalState( @Nonnull TypeSerializer<N> namespaceSerializer, @Nonnull StateDescriptor<S, SV> stateDesc, @Nonnull StateSnapshotTransformer.StateSnapshotTransformFactory<SEV> snapshotTransformFactory) throws Exception { StateFactory stateFactory = STATE_FACTORIES.get(stateDesc.getType()); if (stateFactory == null) { String message = String.format( "State %s is not supported by %s", stateDesc.getClass(), this.getClass()); throw new FlinkRuntimeException(message); } RegisteredKeyValueStateBackendMetaInfo<N, SV> meta = new RegisteredKeyValueStateBackendMetaInfo<>( stateDesc.getType(), stateDesc.getName(), namespaceSerializer, stateDesc.getSerializer(), (StateSnapshotTransformer.StateSnapshotTransformFactory<SV>) snapshotTransformFactory); InternalKvState<K, N, SV> state = keyedStateBackend.createInternalState( namespaceSerializer, stateDesc, snapshotTransformFactory); KvStateChangeLoggerImpl<K, SV, N> kvStateChangeLogger = new KvStateChangeLoggerImpl<>( state.getKeySerializer(), state.getNamespaceSerializer(), state.getValueSerializer(), keyedStateBackend.getKeyContext(), stateChangelogWriter, meta, stateDesc.getTtlConfig(), stateDesc.getDefaultValue(), ++lastCreatedStateId); closer.register(kvStateChangeLogger); IS is = stateFactory.create( state, kvStateChangeLogger, keyedStateBackend /* pass the nested backend as key context so that it get key updates on recovery*/); changelogStates.put(stateDesc.getName(), (ChangelogState) is); return is; } public void registerCloseable(@Nullable Closeable closeable) { closer.register(closeable); } private ChangelogSnapshotState completeRestore( Collection<ChangelogStateBackendHandle> stateHandles) { long materializationId = 0L; List<KeyedStateHandle> materialized = new ArrayList<>(); List<ChangelogStateHandle> restoredNonMaterialized = new ArrayList<>(); for (ChangelogStateBackendHandle h : stateHandles) { if (h != null) { materialized.addAll(h.getMaterializedStateHandles()); restoredNonMaterialized.addAll(h.getNonMaterializedStateHandles()); // choose max materializationID to handle rescaling materializationId = Math.max(materializationId, h.getMaterializationID()); } } this.materializedId = materializationId + 1; return new ChangelogSnapshotState( materialized, restoredNonMaterialized, stateChangelogWriter.initialSequenceNumber(), materializationId); } /** * Initialize state materialization so that materialized data can be persisted durably and * included into the checkpoint. * * <p>This method is not thread safe. It should be called either under a lock or through task * mailbox executor. * * @return a tuple of - future snapshot result from the underlying state backend - a {@link * SequenceNumber} identifying the latest change in the changelog */ public Optional<MaterializationRunnable> initMaterialization() throws Exception { SequenceNumber upTo = stateChangelogWriter.lastAppendedSequenceNumber().next(); SequenceNumber lastMaterializedTo = changelogSnapshotState.lastMaterializedTo(); LOG.info( "Initialize Materialization. Current changelog writers last append to sequence number {}", upTo); if (upTo.compareTo(lastMaterializedTo) > 0) { LOG.info("Starting materialization from {} : {}", lastMaterializedTo, upTo); // This ID is not needed for materialization; But since we are re-using the // streamFactory that is designed for state backend snapshot, which requires unique // checkpoint ID. A faked materialized Id is provided here. long materializationID = materializedId++; MaterializationRunnable materializationRunnable = new MaterializationRunnable( keyedStateBackend.snapshot( materializationID, System.currentTimeMillis(), // TODO: implement its own streamFactory. streamFactory, CHECKPOINT_OPTIONS), materializationID, upTo); // log metadata after materialization is triggered for (ChangelogState changelogState : changelogStates.values()) { changelogState.resetWritingMetaFlag(); } for (ChangelogKeyGroupedPriorityQueue<?> priorityQueueState : priorityQueueStatesByName.values()) { priorityQueueState.resetWritingMetaFlag(); } return Optional.of(materializationRunnable); } else { LOG.debug( "Skip materialization, last materialized to {} : last log to {}", lastMaterializedTo, upTo); return Optional.empty(); } } /** * This method is not thread safe. It should be called either under a lock or through task * mailbox executor. */ public void updateChangelogSnapshotState( SnapshotResult<KeyedStateHandle> materializedSnapshot, long materializationID, SequenceNumber upTo) throws Exception { LOG.info( "Task {} finishes materialization, updates the snapshotState upTo {} : {}", subtaskName, upTo, materializedSnapshot); changelogSnapshotState = new ChangelogSnapshotState( getMaterializedResult(materializedSnapshot), Collections.emptyList(), upTo, materializationID); stateChangelogWriter.truncate(upTo); } // TODO: this method may change after the ownership PR private List<KeyedStateHandle> getMaterializedResult( @Nonnull SnapshotResult<KeyedStateHandle> materializedSnapshot) { KeyedStateHandle jobManagerOwned = materializedSnapshot.getJobManagerOwnedSnapshot(); return jobManagerOwned == null ? emptyList() : singletonList(jobManagerOwned); } @Override public KeyedStateBackend<K> getDelegatedKeyedStateBackend(boolean recursive) { return keyedStateBackend.getDelegatedKeyedStateBackend(recursive); } // Factory function interface private interface StateFactory { <K, N, SV, S extends State, IS extends S> IS create( InternalKvState<K, N, SV> kvState, KvStateChangeLogger<SV, N> changeLogger, InternalKeyContext<K> keyContext) throws Exception; } /** * @param name state name * @param type state type (the only supported type currently are: {@link * BackendStateType#KEY_VALUE key value}, {@link BackendStateType#PRIORITY_QUEUE priority * queue}) * @return an existing state, i.e. the one that was already created. The returned state will not * apply TTL to the passed values, regardless of the TTL settings. This prevents double * applying of TTL (recovered values are TTL values if TTL was enabled). The state will, * however, use TTL serializer if TTL is enabled. WARN: only valid during the recovery. * @throws NoSuchElementException if the state wasn't created * @throws UnsupportedOperationException if state type is not supported */ public ChangelogState getExistingStateForRecovery(String name, BackendStateType type) throws NoSuchElementException, UnsupportedOperationException { ChangelogState state; switch (type) { case KEY_VALUE: state = changelogStates.get(name); break; case PRIORITY_QUEUE: state = priorityQueueStatesByName.get(name); break; default: throw new UnsupportedOperationException( String.format("Unknown state type %s (%s)", type, name)); } if (state == null) { throw new NoSuchElementException(String.format("%s state %s not found", type, name)); } return state; } private static <T> RunnableFuture<T> toRunnableFuture(CompletableFuture<T> f) { return new RunnableFuture<T>() { @Override public void run() { f.join(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return f.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return f.isCancelled(); } @Override public boolean isDone() { return f.isDone(); } @Override public T get() throws InterruptedException, ExecutionException { return f.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return f.get(timeout, unit); } }; } /** * Snapshot State for ChangelogKeyedStatebackend. * * <p>It includes three parts: - materialized snapshot from the underlying delegated state * backend - non-materialized part in the current changelog - non-materialized changelog, from * previous logs (before failover or rescaling) */ private static class ChangelogSnapshotState { /** * Materialized snapshot from the underlying delegated state backend. Set initially on * restore and later upon materialization. */ private final List<KeyedStateHandle> materializedSnapshot; /** * The {@link SequenceNumber} up to which the state is materialized, exclusive. This * indicates the non-materialized part of the current changelog. */ private final SequenceNumber materializedTo; /** * Non-materialized changelog, from previous logs. Set initially on restore and later * cleared upon materialization. */ private final List<ChangelogStateHandle> restoredNonMaterialized; /** ID of this materialization corresponding to the nested backend checkpoint ID. */ private final long materializationID; public ChangelogSnapshotState( List<KeyedStateHandle> materializedSnapshot, List<ChangelogStateHandle> restoredNonMaterialized, SequenceNumber materializedTo, long materializationID) { this.materializedSnapshot = unmodifiableList((materializedSnapshot)); this.restoredNonMaterialized = unmodifiableList(restoredNonMaterialized); this.materializedTo = materializedTo; this.materializationID = materializationID; } public List<KeyedStateHandle> getMaterializedSnapshot() { return materializedSnapshot; } public SequenceNumber lastMaterializedTo() { return materializedTo; } public List<ChangelogStateHandle> getRestoredNonMaterialized() { return restoredNonMaterialized; } public long getMaterializationID() { return materializationID; } } @VisibleForTesting StateChangelogWriter<? extends ChangelogStateHandle> getChangelogWriter() { return stateChangelogWriter; } }
apache-2.0
japkit/japkit
japkit-test/src/main/java/de/japkit/test/members/common/comment/CommentTrigger.java
763
package de.japkit.test.members.common.comment; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import de.japkit.metaannotations.Trigger; /** * The trigger annotation for the example. Refers to the template describing the * class to be generated. */ @Documented @Trigger(template = CommentTemplate.class) @Target(ElementType.TYPE) public @interface CommentTrigger { /** * All trigger annotations in japkit must have this annotation value. When * generating a class, the trigger annotation is copied to the generated * class and shadow is set to false to mark it as a copy. * * @return true means, it is a copy of the original annotation. */ boolean shadow() default false; }
apache-2.0
drankye/SSM
smart-common/src/main/java/org/smartdata/utils/JaasLoginUtil.java
8627
/** * 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.smartdata.utils; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.Subject; import javax.security.auth.kerberos.KerberosPrincipal; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import java.io.File; import java.io.IOException; import java.security.Principal; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Jaas utilities for Smart login. */ public class JaasLoginUtil { public static final Logger LOG = LoggerFactory.getLogger(JaasLoginUtil.class); public static final boolean ENABLE_DEBUG = true; private static String getKrb5LoginModuleName() { return System.getProperty("java.vendor").contains("IBM") ? "com.ibm.security.auth.module.Krb5LoginModule" : "com.sun.security.auth.module.Krb5LoginModule"; } /** * Log a user in from a tgt ticket. * * @throws IOException */ public static synchronized Subject loginUserFromTgtTicket(String smartSecurity) throws IOException { TICKET_KERBEROS_OPTIONS.put("smartSecurity", smartSecurity); Subject subject = new Subject(); Configuration conf = new SmartJaasConf(); String confName = "ticket-kerberos"; LoginContext loginContext = null; try { loginContext = new LoginContext(confName, subject, null, conf); } catch (LoginException e) { throw new IOException("Fail to create LoginContext for " + e); } try { loginContext.login(); LOG.info("Login successful for user " + subject.getPrincipals().iterator().next().getName()); } catch (LoginException e) { throw new IOException("Login failure for " + e); } return loginContext.getSubject(); } /** * Smart Jaas config. */ static class SmartJaasConf extends Configuration { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { return new AppConfigurationEntry[]{ TICKET_KERBEROS_LOGIN}; } } private static final Map<String, String> BASIC_JAAS_OPTIONS = new HashMap<String, String>(); static { String jaasEnvVar = System.getenv("SMART_JAAS_DEBUG"); if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) { BASIC_JAAS_OPTIONS.put("debug", String.valueOf(ENABLE_DEBUG)); } } private static final Map<String, String> TICKET_KERBEROS_OPTIONS = new HashMap<String, String>(); static { TICKET_KERBEROS_OPTIONS.put("doNotPrompt", "true"); TICKET_KERBEROS_OPTIONS.put("useTgtTicket", "true"); TICKET_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS); } private static final AppConfigurationEntry TICKET_KERBEROS_LOGIN = new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL, TICKET_KERBEROS_OPTIONS); public static Subject loginUsingTicketCache(String principal) throws IOException { String ticketCache = System.getenv("KRB5CCNAME"); return loginUsingTicketCache(principal, ticketCache); } @VisibleForTesting static Subject loginUsingTicketCache( String principal, String ticketCacheFileName) throws IOException { Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(principal)); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); Configuration conf = useTicketCache(principal, ticketCacheFileName); String confName = "TicketCacheConf"; LoginContext loginContext = null; try { loginContext = new LoginContext(confName, subject, null, conf); } catch (LoginException e) { throw new IOException("Fail to create LoginContext for " + e); } try { loginContext.login(); LOG.info("Login successful for user " + subject.getPrincipals().iterator().next().getName()); } catch (LoginException e) { throw new IOException("Login failure for " + e); } return loginContext.getSubject(); } public static Subject loginUsingKeytab( String principal, File keytabFile) throws IOException { Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(principal)); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); Configuration conf = useKeytab(principal, keytabFile); String confName = "KeytabConf"; LoginContext loginContext = null; try { loginContext = new LoginContext(confName, subject, null, conf); LOG.info("Login successful for user " + subject.getPrincipals().iterator().next().getName()); } catch (LoginException e) { throw new IOException("Faill to create LoginContext for " + e); } try { loginContext.login(); } catch (LoginException e) { throw new IOException("Login failure for " + e); } return loginContext.getSubject(); } public static Configuration useTicketCache(String principal, String ticketCacheFileName) { return new TicketCacheJaasConf(principal, ticketCacheFileName); } public static Configuration useKeytab(String principal, File keytabFile) { return new KeytabJaasConf(principal, keytabFile); } static class TicketCacheJaasConf extends Configuration { private String principal; private String ticketCacheFileName; TicketCacheJaasConf(String principal, String ticketCacheFileName) { this.principal = principal; this.ticketCacheFileName = ticketCacheFileName; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { Map<String, String> options = new HashMap<String, String>(); options.put("principal", principal); options.put("storeKey", "false"); options.put("doNotPrompt", "false"); options.put("useTicketCache", "true"); options.put("renewTGT", "true"); options.put("refreshKrb5Config", "true"); options.put("isInitiator", "true"); if (ticketCacheFileName != null) { if (System.getProperty("java.vendor").contains("IBM")) { // The first value searched when "useDefaultCcache" is used. System.setProperty("KRB5CCNAME", ticketCacheFileName); } else { options.put("ticketCache", ticketCacheFileName); } } options.putAll(BASIC_JAAS_OPTIONS); return new AppConfigurationEntry[]{ new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)}; } } static class KeytabJaasConf extends Configuration { private String principal; private File keytabFile; KeytabJaasConf(String principal, File keytab) { this.principal = principal; this.keytabFile = keytab; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { Map<String, String> options = new HashMap<String, String>(); options.put("keyTab", keytabFile.getAbsolutePath()); options.put("principal", principal); options.put("useKeyTab", "true"); options.put("storeKey", "true"); options.put("doNotPrompt", "true"); options.put("renewTGT", "false"); options.put("refreshKrb5Config", "true"); options.put("isInitiator", "true"); options.putAll(BASIC_JAAS_OPTIONS); return new AppConfigurationEntry[]{ new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)}; } } }
apache-2.0
daedric/buck
src/com/facebook/buck/intellij/ideabuck/tests/integration/com/facebook/buck/intellij/ideabuck/endtoend/BuckCopyPasteProcessorTest.java
1863
/* * Copyright 2017-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.intellij.ideabuck.endtoend; import com.facebook.buck.intellij.ideabuck.format.BuckCopyPasteProcessor; public class BuckCopyPasteProcessorTest extends BuckTestCase { private void doTest(String pasteText, String expected) { String testPath = "formatter/paste/environment.BUCK"; BuckCopyPasteProcessor processor = new BuckCopyPasteProcessor(); myFixture.configureByFile(testPath); String actual = processor.preprocessOnPaste( getProject(), myFixture.getFile(), myFixture.getEditor(), pasteText, null); assertEquals(actual, expected); } public void testPasteSingleTarget1() { doTest(" \n //foo:test \n \n", "'//foo:test',"); } public void testPasteSingleTarget2() { doTest("//foo:test\n\n\n", "'//foo:test',"); } public void testPasteSingleTarget3() { doTest("foo:test", "'//foo:test',"); } public void testPasteMultiLineTargets() { doTest( " //foo:test \n\n :another\n foo:bar\n", "'//foo:test',\n':another',\n'//foo:bar',"); } public void testPasteMultiWithInvalidTarget() { doTest( "\n //first:one\nthisoneisinvalid \n", "\n //first:one\nthisoneisinvalid \n"); } }
apache-2.0
antoinesd/weld-core
environments/se/core/src/test/java/org/jboss/weld/environment/se/test/isolation/CameraDecorator.java
422
package org.jboss.weld.environment.se.test.isolation; import javax.decorator.Decorator; import javax.decorator.Delegate; import javax.inject.Inject; @Decorator public class CameraDecorator implements Camera { @Inject @Delegate private Camera delegate; public static int invocations = 0; @Override public void capture() { invocations++; delegate.capture(); } }
apache-2.0
huihoo/olat
olat7.8/src/main/java/org/olat/presentation/course/editor/PublishStep01.java
6252
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * 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,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <p> */ package org.olat.presentation.course.editor; import org.olat.data.repository.RepositoryEntry; import org.olat.presentation.framework.core.UserRequest; import org.olat.presentation.framework.core.components.form.flexible.FormItemContainer; import org.olat.presentation.framework.core.components.form.flexible.elements.SingleSelection; import org.olat.presentation.framework.core.components.form.flexible.impl.Form; import org.olat.presentation.framework.core.components.form.flexible.impl.FormLayoutContainer; import org.olat.presentation.framework.core.control.Controller; import org.olat.presentation.framework.core.control.WindowControl; import org.olat.presentation.framework.core.control.generic.wizard.BasicStep; import org.olat.presentation.framework.core.control.generic.wizard.PrevNextFinishConfig; import org.olat.presentation.framework.core.control.generic.wizard.Step; import org.olat.presentation.framework.core.control.generic.wizard.StepFormBasicController; import org.olat.presentation.framework.core.control.generic.wizard.StepFormController; import org.olat.presentation.framework.core.control.generic.wizard.StepsEvent; import org.olat.presentation.framework.core.control.generic.wizard.StepsRunContext; import org.olat.presentation.framework.core.translator.PackageTranslator; import org.olat.presentation.framework.core.translator.PackageUtil; import org.olat.presentation.repository.PropPupForm; /** * Description:<br> * TODO: patrickb Class Description for PublishStep01 * <P> * Initial Date: 21.01.2008 <br> * * @author patrickb */ class PublishStep01 extends BasicStep { private PrevNextFinishConfig prevNextConfig; private final boolean hasPublishableChanges; public PublishStep01(final UserRequest ureq, final boolean hasPublishableChanges) { super(ureq); setI18nTitleAndDescr("publish.access.header", null); this.hasPublishableChanges = hasPublishableChanges; if (hasPublishableChanges) { setNextStep(new PublishStep00a(ureq)); prevNextConfig = PrevNextFinishConfig.BACK_NEXT_FINISH; } else { setNextStep(Step.NOSTEP); prevNextConfig = PrevNextFinishConfig.BACK_FINISH; } } /** */ @Override public PrevNextFinishConfig getInitialPrevNextFinishConfig() { // can go back and finish immediately return prevNextConfig; } /** * org.olat.presentation.framework.control.generic.wizard.StepsRunContext, org.olat.presentation.framework.components.form.flexible.impl.Form) */ @Override public StepFormController getStepController(final UserRequest ureq, final WindowControl wControl, final StepsRunContext stepsRunContext, final Form form) { return new PublishStep01AccessForm(ureq, wControl, form, stepsRunContext, hasPublishableChanges); } class PublishStep01AccessForm extends StepFormBasicController { private SingleSelection accessSelbox; private final String selectedAccess; private final boolean hasPublishableChanges2; PublishStep01AccessForm(final UserRequest ureq, final WindowControl control, final Form rootForm, final StepsRunContext runContext, final boolean hasPublishableChanges2) { super(ureq, control, rootForm, runContext, LAYOUT_VERTICAL, null); this.hasPublishableChanges2 = hasPublishableChanges2; selectedAccess = (String) getFromRunContext("selectedCourseAccess"); initForm(ureq); } @Override protected void doDispose() { // TODO Auto-generated method stub } @Override protected void formOK(final UserRequest ureq) { final String newAccess = accessSelbox.getKey(accessSelbox.getSelected()); if (!selectedAccess.equals(newAccess)) { // only change if access was changed addToRunContext("changedaccess", newAccess); } if (hasPublishableChanges2) { fireEvent(ureq, StepsEvent.ACTIVATE_NEXT); } else { fireEvent(ureq, StepsEvent.INFORM_FINISHED); } } @Override @SuppressWarnings("unused") protected void initForm(final FormItemContainer formLayout, final Controller listener, final UserRequest ureq) { final PackageTranslator pt = (PackageTranslator) PackageUtil.createPackageTranslator(PropPupForm.class, getLocale(), getTranslator()); final FormItemContainer fic = FormLayoutContainer.createCustomFormLayout("access", pt, this.velocity_root + "/publish_courseaccess.html"); formLayout.add(fic); final String[] keys = new String[] { "" + RepositoryEntry.ACC_OWNERS, "" + RepositoryEntry.ACC_OWNERS_AUTHORS, "" + RepositoryEntry.ACC_USERS, "" + RepositoryEntry.ACC_USERS_GUESTS }; final String[] values = new String[] { pt.translate("cif.access.owners"), pt.translate("cif.access.owners_authors"), pt.translate("cif.access.users"), pt.translate("cif.access.users_guests"), }; // use the addDropDownSingleselect method with null as label i18n - key, because there is no label to set. OLAT-3682 accessSelbox = uifactory.addDropdownSingleselect("accessBox", null, fic, keys, values, null); accessSelbox.select(selectedAccess, true); } } }
apache-2.0
lengyubing/wint
wint-framework/src/main/java/wint/sessionx/filter/FilterManager.java
257
package wint.sessionx.filter; import java.util.Map; /** * User: longyi * Date: 14-2-26 * Time: 下午1:20 */ public interface FilterManager { void addFilter(Filter filter); FilterContext performFilters(Map<String, Object> initAttributes); }
apache-2.0
FasterXML/jackson-databind
src/main/java/com/fasterxml/jackson/databind/util/RawValue.java
3964
package com.fasterxml.jackson.databind.util; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.SerializableString; import com.fasterxml.jackson.databind.JsonSerializable; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; /** * Helper class used to encapsulate "raw values", pre-encoded textual content * that can be output as opaque value with no quoting/escaping, using * {@link com.fasterxml.jackson.core.JsonGenerator#writeRawValue(String)}. * It may be stored in {@link TokenBuffer}, as well as in Tree Model * ({@link com.fasterxml.jackson.databind.JsonNode}) * * @since 2.6 */ public class RawValue implements JsonSerializable { /** * Contents to serialize. Untyped because there are multiple types that are * supported: {@link java.lang.String}, {@link JsonSerializable}, {@link SerializableString}. */ protected Object _value; public RawValue(String v) { _value = v; } public RawValue(SerializableString v) { _value = v; } public RawValue(JsonSerializable v) { _value = v; } /** * Constructor that may be used by sub-classes, and allows passing value * types other than ones for which explicit constructor exists. Caller has to * take care that values of types not supported by base implementation are * handled properly, usually by overriding some of existing serialization * methods. */ protected RawValue(Object value, boolean bogus) { _value = value; } /** * Accessor for returning enclosed raw value in whatever form it was created in * (usually {@link java.lang.String}, {link SerializableString}, or any {@link JsonSerializable}). */ public Object rawValue() { return _value; } @Override public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { if (_value instanceof JsonSerializable) { ((JsonSerializable) _value).serialize(gen, serializers); } else { _serialize(gen); } } @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { if (_value instanceof JsonSerializable) { ((JsonSerializable) _value).serializeWithType(gen, serializers, typeSer); } else if (_value instanceof SerializableString) { /* Since these are not really to be deserialized (with or without type info), * just re-route as regular write, which will create one... hopefully it works */ serialize(gen, serializers); } } public void serialize(JsonGenerator gen) throws IOException { if (_value instanceof JsonSerializable) { // No SerializerProvider passed, must go via generator, callback gen.writeObject(_value); } else { _serialize(gen); } } protected void _serialize(JsonGenerator gen) throws IOException { if (_value instanceof SerializableString) { gen.writeRawValue((SerializableString) _value); } else { gen.writeRawValue(String.valueOf(_value)); } } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof RawValue)) return false; RawValue other = (RawValue) o; if (_value == other._value) { return true; } return (_value != null) && _value.equals(other._value); } @Override public int hashCode() { return (_value == null) ? 0 : _value.hashCode(); } @Override public String toString() { return String.format("[RawValue of type %s]", ClassUtil.classNameOf(_value)); } }
apache-2.0
sweble/osr-common
utils-parent/utils-testing/src/main/java/de/fau/cs/osr/utils/TestNameAnnotation.java
986
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * 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 de.fau.cs.osr.utils; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface TestNameAnnotation { String annotation(); }
apache-2.0
akdasari/SparkCore
spark-framework/src/main/java/org/sparkcommerce/core/store/dao/ZipCodeDaoImpl.java
4695
/* * #%L * SparkCommerce Framework * %% * Copyright (C) 2009 - 2013 Spark Commerce * %% * 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% */ package org.sparkcommerce.core.store.dao; import org.sparkcommerce.core.store.domain.ZipCode; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.List; @Repository("blZipCodeDao") public class ZipCodeDaoImpl implements ZipCodeDao { @PersistenceContext(unitName="blPU") private EntityManager em; @SuppressWarnings("unchecked") public ZipCode findZipCodeByZipCode(Integer zipCode) { Query query = em.createNamedQuery("BC_FIND_ZIP_CODE_BY_ZIP_CODE"); query.setHint("org.hibernate.cacheable", true); query.setParameter("zipCode", zipCode); List<ZipCode> result = query.getResultList(); return (result.size() > 0) ? result.get(0) : null; } @SuppressWarnings("unchecked") public ZipCode findBestZipCode(String pCity, String pCounty, String pState, Integer pZipCode, Long pZipGeo) { // If we have a zip geo, use it if ( pZipGeo != null ) { Query query = em.createNamedQuery("FIND_ZIP_WITH_GEO"); query.setHint("org.hibernate.cacheable", true); query.setParameter("geo", pZipGeo); query.setParameter("city", pCity); query.setParameter("zipCode", pZipCode); query.setParameter("state", pState); List<ZipCode> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } } // If we have a county, try and find a match if ( pCounty != null && !"".equals(pCounty.trim()) ) { Query query = em.createNamedQuery("FIND_ZIP_WITH_COUNTY"); query.setHint("org.hibernate.cacheable", true); query.setParameter("county", pCounty); query.setParameter("city", pCity); query.setParameter("zipCode", pZipCode); query.setParameter("state", pState); List<ZipCode> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } } { // first try for exact match with city, state, zip Query query = em.createNamedQuery("FIND_ZIP_WITH_CITY_STATE_ZIP"); query.setHint("org.hibernate.cacheable", true); query.setParameter("city", pCity); query.setParameter("zipCode", pZipCode); query.setParameter("state", pState); List<ZipCode> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } } { // now try soundex match with soundex(city),state,zip Query query = em.createNamedQuery("FIND_ZIP_WITH_SOUNDEX"); query.setHint("org.hibernate.cacheable", true); query.setParameter("city", pCity); query.setParameter("zipCode", pZipCode); query.setParameter("state", pState); List<ZipCode> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } } { // now try state and zip Query query = em.createNamedQuery("FIND_ZIP_WITH_STATE_ZIP"); query.setHint("org.hibernate.cacheable", true); query.setParameter("zipCode", pZipCode); query.setParameter("state", pState); List<ZipCode> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } } { // finally just try state Query query = em.createNamedQuery("FIND_ZIP_WITH_STATE"); query.setHint("org.hibernate.cacheable", true); query.setParameter("state", pState); List<ZipCode> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } } return null; } }
apache-2.0
fabric8io/openshift-elasticsearch-plugin
src/main/java/io/fabric8/elasticsearch/plugin/ConfigurationSettings.java
5962
/** * Copyright (C) 2015 Red Hat, 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 io.fabric8.elasticsearch.plugin; public interface ConfigurationSettings extends KibanaIndexMode{ /** Searchguard settings here **/ static final String SEARCHGUARD_AUTHENTICATION_PROXY_HEADER = "searchguard.authentication.proxy.header"; static final String SEARCHGUARD_CONFIG_INDEX_NAME = "searchguard.config_index_name"; static final String SEARCHGUARD_ROLE_TYPE = "roles"; static final String SEARCHGUARD_MAPPING_TYPE = "rolesmapping"; static final String SEARCHGUARD_CONFIG_ID = "0"; static final String[] SEARCHGUARD_INITIAL_CONFIGS = new String[] { "config", "roles", "rolesmapping", "actiongroups", "internalusers" }; static final String SEARCHGUARD_ADMIN_DN = "searchguard.authcz.admin_dn"; static final String SG_CONFIG_SETTING_PATH = "searchguard.config.path"; static final String SG_CLIENT_KS_PATH = "openshift.searchguard.keystore.path"; static final String SG_CLIENT_TS_PATH = "openshift.searchguard.truststore.path"; static final String SG_CLIENT_KS_PASS = "openshift.searchguard.keystore.password"; static final String SG_CLIENT_TS_PASS = "openshift.searchguard.truststore.password"; static final String SG_CLIENT_KS_TYPE = "openshift.searchguard.keystore.type"; static final String SG_CLIENT_TS_TYPE = "openshift.searchguard.truststore.type"; static final String DEFAULT_SEARCHGUARD_ADMIN_DN = "CN=system.admin,OU=client,O=client,L=Test,C=DE"; static final String DEFAULT_SG_CONFIG_SETTING_PATH = "/opt/app-root/src/sgconfig/"; static final String DEFAULT_SG_CLIENT_KS_PATH = "/usr/share/elasticsearch/config/admin.jks"; static final String DEFAULT_SG_CLIENT_TS_PATH = "/usr/share/elasticsearch/config/logging-es.truststore.jks"; static final String DEFAULT_SG_CLIENT_KS_PASS = "kspass"; static final String DEFAULT_SG_CLIENT_TS_PASS = "tspass"; static final String DEFAULT_SG_CLIENT_KS_TYPE = "JKS"; static final String DEFAULT_SG_CLIENT_TS_TYPE = "JKS"; /** Searchguard settings here **/ /** Kibana settings here **/ static final String KIBANA_CONFIG_INDEX_NAME = "kibana.config_index_name"; static final String KIBANA_CONFIG_VERSION = "kibana.version"; static final String KIBANA_VERSION_HEADER = "kibana.version.header"; static final String DEFAULT_KIBANA_VERSION = "5.6.16"; static final String DEFAULT_KIBANA_VERSION_HEADER = "kbn-version"; /** Kibana settings here **/ /** * The maximum time time in milliseconds to wait for SearchGuard to sync the * ACL from a write from this plugin until load by searchguard */ /** OpenShift settings here **/ static final String OPENSHIFT_ES_KIBANA_SEED_MAPPINGS_APP = "io.fabric8.elasticsearch.kibana.mapping.app"; static final String OPENSHIFT_ES_KIBANA_SEED_MAPPINGS_OPERATIONS = "io.fabric8.elasticsearch.kibana.mapping.ops"; static final String OPENSHIFT_ES_KIBANA_SEED_MAPPINGS_EMPTY = "io.fabric8.elasticsearch.kibana.mapping.empty"; static final String OPENSHIFT_ES_USER_PROFILE_PREFIX = "io.fabric8.elasticsearch.acl.user_profile_prefix"; static final String OPENSHIFT_CONFIG_OPS_ALLOW_CLUSTER_READER = "openshift.operations.allow_cluster_reader"; static final String OPENSHIFT_CONFIG_OPS_PROJECTS = "openshift.operations.project.names"; static final String[] DEFAULT_OPENSHIFT_OPS_PROJECTS = new String[] { "default", "openshift", "openshift-infra", "kube-system" }; static final String OPENSHIFT_REQUEST_CONTEXT = "x-openshift-request-context"; static final String SYNC_AND_SEED = "x-openshift-sync-and-seed-acls"; static final String DEFAULT_AUTH_PROXY_HEADER = "X-Proxy-Remote-User"; static final String DEFAULT_SECURITY_CONFIG_INDEX = "searchguard"; static final String DEFAULT_USER_PROFILE_PREFIX = ".kibana"; static final String[] DEFAULT_WHITELISTED_USERS = new String[] { "$logging.$infra.$fluentd", "$logging.$infra.$kibana", "$logging.$infra.$curator" }; static final String [] DEFAULT_KIBANA_OPS_INDEX_PATTERNS = new String[] { ".operations.*", ".orphaned.*", "project.*", ".all" }; static final String OPENSHIFT_ACL_EXPIRE_IN_MILLIS = "openshift.acl.expire_in_millis"; static final String OPENSHIFT_CONTEXT_CACHE_MAXSIZE = "openshift.context.cache.maxsize"; static final String OPENSHIFT_CONTEXT_CACHE_EXPIRE_SECONDS = "openshift.context.cache.expireseconds"; static final int DEFAULT_OPENSHIFT_CONTEXT_CACHE_MAXSIZE = 500; static final long DEFAULT_OPENSHIFT_CONTEXT_CACHE_EXPIRE_SECONDS = 120; /** * The strategy to use for generating roles and role mappings */ static final String OPENSHIFT_ACL_ROLE_STRATEGY = "openshift.acl.role_strategy"; static final String DEFAULT_ACL_ROLE_STRATEGY = "user"; /** * List of index patterns to create for operations users */ static final String OPENSHIFT_KIBANA_OPS_INDEX_PATTERNS = "openshift.kibana.ops_index_patterns"; static final String OPENSHIFT_CONFIG_TIME_FIELD_NAME = "openshift.config.time_field_name"; static final String OPENSHIFT_CONFIG_COMMON_DATA_MODEL = "openshift.config.use_common_data_model"; static final String OPENSHIFT_CONFIG_PROJECT_INDEX_PREFIX = "openshift.config.project_index_prefix"; static final String OPENSHIFT_DEFAULT_PROJECT_INDEX_PREFIX = "project"; }
apache-2.0
akirakw/asakusafw
dsl-project/asakusa-dsl-vocabulary/src/main/java/com/asakusafw/vocabulary/flow/graph/FlowIn.java
2507
/** * Copyright 2011-2019 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.vocabulary.flow.graph; import java.text.MessageFormat; import com.asakusafw.vocabulary.flow.In; /** * Represents an input of flow graph. * @param <T> the data type */ public final class FlowIn<T> implements In<T> { private final InputDescription description; private final FlowElementResolver resolver; /** * Creates a new instance. * @param description the description * @throws IllegalArgumentException if the parameter is {@code null} */ public FlowIn(InputDescription description) { if (description == null) { throw new IllegalArgumentException("description must not be null"); //$NON-NLS-1$ } this.description = description; this.resolver = new FlowElementResolver(description); } /** * Creates a new instance. * @param <T> the data type * @param description the description * @return the created instance * @throws IllegalArgumentException if the parameter is {@code null} */ public static <T> FlowIn<T> newInstance(InputDescription description) { return new FlowIn<>(description); } /** * Returns the description of this input. * @return the description */ public InputDescription getDescription() { return description; } /** * Returns the corresponding {@link FlowElement} object. * @return the corresponding {@link FlowElement} object */ public FlowElement getFlowElement() { return resolver.getElement(); } @Override public FlowElementOutput toOutputPort() { return resolver.getOutput(InputDescription.OUTPUT_PORT_NAME); } @Override public String toString() { return MessageFormat.format( "{0}({1})", //$NON-NLS-1$ getDescription(), getFlowElement()); } }
apache-2.0
apache/ant-ivyde
org.apache.ivyde.eclipse/src/java/org/apache/ivyde/internal/eclipse/ui/wizards/IvyNewWizardPage.java
9446
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivyde.internal.eclipse.ui.wizards; import org.apache.ivyde.internal.eclipse.IvyPlugin; import org.apache.ivyde.internal.eclipse.ui.preferences.PreferenceConstants; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ContainerSelectionDialog; /** * The "New" wizard page allows setting the container for the new file as well as the file name. The * page will only accept file name without the extension OR with the extension that matches the * expected one (ivy.xml). */ public class IvyNewWizardPage extends WizardPage { private Text containerText; private Text fileText; private Text orgText; private Text moduleText; private Combo statusText; private final ISelection selection; /** * Constructor for SampleNewWizardPage. * * @param selection ISelection */ public IvyNewWizardPage(ISelection selection) { super("wizardPage"); setTitle("Ivy File"); setDescription("This wizard creates a new ivy.xml file " + "that can be opened by the Ivy multi-page editor."); this.selection = selection; } /** * @see org.eclipse.jface.dialogs.IDialogPage#createControl(Composite) * @param parent Composite */ public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); container.setLayout(layout); // CheckStyle:MagicNumber| OFF layout.numColumns = 3; layout.verticalSpacing = 9; // CheckStyle:MagicNumber| ON Label label = new Label(container, SWT.NULL); label.setText("&Container:"); containerText = new Text(container, SWT.BORDER | SWT.SINGLE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); containerText.setLayoutData(gd); containerText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { dialogChanged(); } }); Button button = new Button(container, SWT.PUSH); button.setText("Browse..."); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleBrowse(); } }); label = new Label(container, SWT.NULL); label.setText("&File name:"); fileText = new Text(container, SWT.BORDER | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; fileText.setLayoutData(gd); fileText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { dialogChanged(); } }); label = new Label(container, SWT.NULL); label.setText("&Organisation:"); orgText = new Text(container, SWT.BORDER | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; orgText.setLayoutData(gd); orgText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { dialogChanged(); } }); label = new Label(container, SWT.NULL); label.setText("&Module name:"); moduleText = new Text(container, SWT.BORDER | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; moduleText.setLayoutData(gd); moduleText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { dialogChanged(); } }); label = new Label(container, SWT.NULL); label.setText("&Status:"); statusText = new Combo(container, SWT.READ_ONLY | SWT.DROP_DOWN); statusText.add("integration"); statusText.add("milestone"); statusText.add("release"); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; statusText.setLayoutData(gd); statusText.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { dialogChanged(); } }); initialize(); dialogChanged(); setControl(container); } /** * Tests if the current workbench selection is a suitable container to use. */ private void initialize() { if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() > 1) { return; } Object obj = ssel.getFirstElement(); if (obj instanceof IResource) { IContainer container; if (obj instanceof IContainer) { container = (IContainer) obj; } else { container = ((IResource) obj).getParent(); } containerText.setText(container.getFullPath().toString()); moduleText.setText(container.getProject().getName()); } } fileText.setText("ivy.xml"); statusText.select(0); orgText.setText(IvyPlugin.getDefault().getPreferenceStore().getString( PreferenceConstants.ORGANISATION)); } /** * Uses the standard container selection dialog to choose the new value for the container field. */ private void handleBrowse() { ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin .getWorkspace().getRoot(), false, "Select new file container"); if (dialog.open() == ContainerSelectionDialog.OK) { Object[] result = dialog.getResult(); if (result.length == 1) { containerText.setText(result[0].toString()); } } } /** * Ensures that both text fields are set. */ private void dialogChanged() { IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember( new Path(getContainerName())); String fileName = getFileName(); if (getContainerName().length() == 0) { updateStatus("File container must be specified"); return; } if (container == null || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) { updateStatus("File container must exist"); return; } if (!container.isAccessible()) { updateStatus("Project must be writable"); return; } if (fileName.length() == 0) { updateStatus("File name must be specified"); return; } if (fileName.replace('\\', '/').indexOf('/', 1) > 0) { updateStatus("File name must be valid"); return; } int dotLoc = fileName.lastIndexOf('.'); if (dotLoc != -1) { String ext = fileName.substring(dotLoc + 1); if (!ext.equalsIgnoreCase("xml")) { updateStatus("File extension must be \".xml\""); return; } } updateStatus(null); } private void updateStatus(String message) { setErrorMessage(message); setPageComplete(message == null); } public String getContainerName() { return containerText.getText(); } public String getFileName() { return fileText.getText(); } public String getOrganisationName() { return orgText.getText(); } public String getModuleName() { return moduleText.getText(); } public String getStatus() { return statusText.getText(); } }
apache-2.0
googlearchive/androidpay-quickstart
app/src/main/java/com/google/android/gms/samples/wallet/BikestoreApplication.java
2071
/* * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.samples.wallet; import android.app.Application; import android.content.SharedPreferences; public class BikestoreApplication extends Application { private static final String USER_PREFS = "com.google.android.gms.samples.wallet.USER_PREFS"; private static final String KEY_USERNAME = "com.google.android.gms.samples.wallet.KEY_USERNAME"; private String mUserName; // Not being saved in shared preferences to let users try new addresses // between app invocations private boolean mAddressValidForPromo; private SharedPreferences mPrefs; @Override public void onCreate() { super.onCreate(); mPrefs = getSharedPreferences(USER_PREFS, MODE_PRIVATE); mUserName = mPrefs.getString(KEY_USERNAME, null); } public boolean isLoggedIn() { return mUserName != null; } public void login(String userName) { mUserName = userName; mPrefs.edit().putString(KEY_USERNAME, mUserName).commit(); } public void logout() { mUserName = null; mPrefs.edit().remove(KEY_USERNAME).commit(); } public String getAccountName() { return mPrefs.getString(KEY_USERNAME, null); } public boolean isAddressValidForPromo() { return mAddressValidForPromo; } public void setAddressValidForPromo(boolean addressValidForPromo) { this.mAddressValidForPromo = addressValidForPromo; } }
apache-2.0
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/commands/EventMediatorInputConnectorCreateCommand.java
3143
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.EventMediator; import org.wso2.developerstudio.eclipse.gmf.esb.EventMediatorInputConnector; /** * @generated */ public class EventMediatorInputConnectorCreateCommand extends EditElementCommand { /** * @generated */ public EventMediatorInputConnectorCreateCommand(CreateElementRequest req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * * @generated */ protected EObject getElementToEdit() { EObject container = ((CreateElementRequest) getRequest()).getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { EventMediator container = (EventMediator) getElementToEdit(); if (container.getInputConnector() != null) { return false; } return true; } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { EventMediatorInputConnector newElement = EsbFactory.eINSTANCE.createEventMediatorInputConnector(); EventMediator owner = (EventMediator) getElementToEdit(); owner.setInputConnector(newElement); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(EventMediatorInputConnector newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }
apache-2.0
Ztiany/Repository
Android/Media/AndroidMediaPlayer/app/src/main/java/com/ztiany/mediaplayer/android/player/MediaController.java
4380
package com.ztiany.mediaplayer.android.player; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.widget.FrameLayout; /** * 控制器基础行为封装 * * @author Ztiany * Email: ztiany3@gmail.com * Date : 2017-10-16 15:54 */ public class MediaController extends FrameLayout { private static final long UPDATE_INTERVAL = 200; private Handler mHandler; private IMediaPlayer mIMediaPlayer; protected int mCurrentState; public MediaController(@NonNull Context context) { this(context, null); } public MediaController(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public MediaController(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); mHandler = new Handler(Looper.getMainLooper()); } void initCurrentState(int currentState) { mCurrentState = currentState; onInitStateSet(); } /** * Runnable used to run code on an interval to update counters and seeker,用于实时更新播放进度 */ private final Runnable mUpdateCounters = new Runnable() { @Override public void run() { if (mHandler == null || mIMediaPlayer == null || !mIMediaPlayer.isPrepared()) { return; } int pos = mIMediaPlayer.getCurrentPosition(); final int dur = mIMediaPlayer.getDuration(); if (pos > dur) { pos = dur; } onVideoProgressUpdate(pos, dur); if (mHandler != null) { mHandler.postDelayed(this, UPDATE_INTERVAL); } } }; public void setMediaPlayer(IMediaPlayer iMediaPlayer) { mIMediaPlayer = iMediaPlayer; mIMediaPlayer.setCallback(new VideoCallback() { @Override public void onBuffering(int percent) { MediaController.this.onVideoBuffering(percent); } @Override public void onError(Exception e) { mHandler.removeCallbacks(mUpdateCounters); MediaController.this.onError(e); } }); } void onStateChanged(int state) { if (mCurrentState == state) { return; } mCurrentState = state; switch (mCurrentState) { case AndroidMediaPlayer.State.STATE_PAUSED: onPaused(); break; case AndroidMediaPlayer.State.STATE_PLAYING: mHandler.post(mUpdateCounters); onPlaying(); break; case AndroidMediaPlayer.State.STATE_IDLE: mHandler.removeCallbacks(mUpdateCounters); onIdle(); break; case AndroidMediaPlayer.State.STATE_COMPLETED: mHandler.removeCallbacks(mUpdateCounters); onCompletion(); break; case AndroidMediaPlayer.State.STATE_PREPARED: onPrepared(); break; case AndroidMediaPlayer.State.STATE_PREPARING: onPreparing(); break; case AndroidMediaPlayer.State.STATE_BUFFERING_PLAYING: onBufferingPlaying(); break; case AndroidMediaPlayer.State.STATE_BUFFERING_PAUSED: onBufferPaused(); break; default: break; } } //@formatter:off protected void onInitStateSet() {} protected void onRemoved() { mIMediaPlayer.setCallback(null); } protected void onError(Exception e) {} protected void onVideoBuffering(int percent) {} protected void onVideoProgressUpdate(int pos, int dur) {} protected void onPlaying() {} protected void onBufferPaused() { } protected void onBufferingPlaying() {} protected void onIdle() {} protected void onCompletion(){} protected void onPaused( ){} protected void onPreparing( ){} protected void onPrepared( ){} //@formatter:on }
apache-2.0
Soya93/Extract-Refactoring
platform/platform-api/src/com/intellij/util/ui/Animator.java
5097
/* * 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.ui; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.util.concurrency.EdtExecutorService; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.awt.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public abstract class Animator implements Disposable { private final String myName; private final int myTotalFrames; private final int myCycleDuration; private final boolean myForward; private final boolean myRepeatable; private ScheduledFuture<?> myTicker; private int myCurrentFrame; private long myStartTime; private long myStartDeltaTime; private boolean myInitialStep; private volatile boolean myDisposed = false; public Animator(@NonNls final String name, final int totalFrames, final int cycleDuration, boolean repeatable) { this(name, totalFrames, cycleDuration, repeatable, true); } public Animator(@NonNls final String name, final int totalFrames, final int cycleDuration, boolean repeatable, boolean forward) { myName = name; myTotalFrames = totalFrames; myCycleDuration = cycleDuration; myRepeatable = repeatable; myForward = forward; reset(); if (skipAnimation()) { animationDone(); } } private void onTick() { if (isDisposed()) return; if (myInitialStep) { myInitialStep = false; myStartTime = System.currentTimeMillis() - myStartDeltaTime; // keep animation state on suspend paint(); return; } double cycleTime = System.currentTimeMillis() - myStartTime; if (cycleTime < 0) return; // currentTimeMillis() is not monotonic - let's pretend that animation didn't changed long newFrame = (long)(cycleTime * myTotalFrames / myCycleDuration); if (myRepeatable) { newFrame %= myTotalFrames; } if (newFrame == myCurrentFrame) return; if (!myRepeatable && newFrame >= myTotalFrames) { animationDone(); return; } myCurrentFrame = (int)newFrame; paint(); } private void paint() { paintNow(myForward ? myCurrentFrame : myTotalFrames - myCurrentFrame - 1, myTotalFrames, myCycleDuration); } private void animationDone() { stopTicker(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { paintCycleEnd(); } }); } private void stopTicker() { if (myTicker != null) { myTicker.cancel(false); myTicker = null; } } protected void paintCycleEnd() { } public void suspend() { myStartDeltaTime = System.currentTimeMillis() - myStartTime; myInitialStep = true; stopTicker(); } public void resume() { if (skipAnimation()) { animationDone(); return; } if (myCycleDuration == 0) { myCurrentFrame = myTotalFrames - 1; paint(); animationDone(); } else if (myTicker == null) { myTicker = EdtExecutorService.getScheduledExecutorInstance().scheduleWithFixedDelay(new Runnable() { @Override public void run() { onTick(); } @Override public String toString() { return "Scheduled "+Animator.this; } }, 0, myCycleDuration * 1000 / myTotalFrames, TimeUnit.MICROSECONDS); } } private static boolean skipAnimation() { if (GraphicsEnvironment.isHeadless()) { return true; } Application app = ApplicationManager.getApplication(); return app != null && app.isUnitTestMode(); } public abstract void paintNow(int frame, int totalFrames, int cycle); @Override public void dispose() { stopTicker(); myDisposed = true; } public boolean isRunning() { return myTicker != null; } public void reset() { myCurrentFrame = 0; myStartDeltaTime = 0; myInitialStep = true; } public final boolean isForward() { return myForward; } public boolean isDisposed() { return myDisposed; } @Override public String toString() { ScheduledFuture<?> future = myTicker; return "Animator '"+myName+"' @" + System.identityHashCode(this) + (future == null || future.isDone() ? " (stopped)": " (running "+myCurrentFrame+"/"+myTotalFrames +" frame)"); } }
apache-2.0
APICloud-com/Java-sdk
src/main/java/com/apicloud/sdk/api/Resource.java
14044
package com.apicloud.sdk.api; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import com.alibaba.fastjson.JSONObject; import com.apicloud.sdk.utils.HttpUtils; /** * 操作数据云api * @author wangjinzhen * @time 21/05/2015 * @version 0.0.1 */ public class Resource{ //headers参数 private Map<String,String> headers = new HashMap<String,String>(); private String domain = "https://d.apicloud.com"; /** * @param appId * @param appKey * @param domain 为空或者null为默认https */ public Resource(String appId,String appKey,String domain){ if(null!=domain&&!"".equals(domain)){ this.domain = domain; } headers.put("X-APICloud-AppId", appId); headers.put("X-APICloud-AppKey", HttpUtils.encrypt(appId,appKey,"SHA-1")); } @SuppressWarnings("unused") private Resource() {} /** 对象 ------begin------ **/ /** * 创建对象 * @param object 对象名称 * @param property 对象所具有的属性 * @return */ public JSONObject createObject(String object,JSONObject property){ //校验是否传递参数 if(property==null){ property = new JSONObject(); } handleFile(property); headers.put("Content-Type", "application/json"); String url = domain+"/mcm/api/"+object; return HttpUtils.doPost(url, headers, null,property.toJSONString()); } /** * 根据id获取对象 * @param object 对象名称 * @param id 对象Id * @return */ public JSONObject getObject(String object,String id){ String url = domain+"/mcm/api/"+object+"/"+id; return HttpUtils.doGet(url, headers); } /** * 获取所有对象 * @param object 对象名称 * @return */ public JSONObject getObjects(String object){ String url = domain+"/mcm/api/"+object; return HttpUtils.doGet(url, headers); } /** * 更新对象 * @param object * @param id * @param property * @return */ public JSONObject updateObject(String object,String id,JSONObject property){ headers.put("Content-Type", "application/json"); if(property==null||property.size()==0){ return JSONObject.parseObject("{status:0,msg:\"请至少更新一个字段\"}"); } String url = domain+"/mcm/api/"+object+"/"+id; return HttpUtils.doPut(url,headers,property.toJSONString()); } /** * 删除对象 * @param object 对象名称 * @param id 对象Id * @return */ public JSONObject deleteObject(String object,String id){ String url = domain+"/mcm/api/"+object+"/"+id; return HttpUtils.doDelete(url, headers); } /** * 统计对象数量 * @param object 对象名称 * @return */ public JSONObject getObjectCount(String object){ String url = domain+"/mcm/api/"+object+"/count"; return HttpUtils.doGet(url, headers); } /** * 判断对象是否存在 * @param object 对象名称 * @param id 对象Id * @return */ public JSONObject checkObjectExists(String object,String id){ String url = domain+"/mcm/api/"+object+"/"+id+"/exists"; return HttpUtils.doGet(url, headers); } /** 对象 ------end------ **/ /** Relation对象 ------begin------ **/ /** * 获取关联对象 * @param object * @param id * @param relationObject * @return */ public JSONObject getRelationObject(String object,String id,String relationObject){ String url = domain+"/mcm/api/"+object+"/"+id+"/"+relationObject; return HttpUtils.doGet(url, headers); } /** * 创建关联对象 * @param object * @param id * @param relationObject * @return */ public JSONObject createRelationObject(String object,String id,String relationObject,JSONObject property){ //处理文件参数 handleFile(property); String url = domain+"/mcm/api/"+object+"/"+id+"/"+relationObject; Map<String,String> propertyMap = new HashMap<String,String>(); Set<String> propertySet = property.keySet(); Iterator<String> iterProperty = propertySet.iterator(); while(iterProperty.hasNext()){ String key = iterProperty.next(); propertyMap.put(key, property.getString(key)); } headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); return HttpUtils.doPost(url, headers,propertyMap,""); } /** * 统计关联对象数量 * @param object * @param id * @param relationObject * @return */ public JSONObject getRelationObjectCount(String object,String id,String relationObject){ String url = domain+"/mcm/api/"+object+"/"+id+"/"+relationObject+"/count"; return HttpUtils.doGet(url, headers); } /** * 删除所有关联对象 * @param object * @param id * @param relationObject * @return */ public JSONObject deleteRelationObject(String object,String id,String relationObject){ String url = domain+"/mcm/api/"+object+"/"+id+"/"+relationObject; return HttpUtils.doDelete(url, headers); } /** Relation对象 ------end------ **/ /** 用户 ------begin------ **/ /** * 创建用户 * @param property * @return */ public JSONObject createUser(JSONObject property){ //校验是否传递参数 if(property==null){ return JSONObject.parseObject("{status:0,msg:\"请传递参数\"}"); } String userName = property.getString("username"); if(null==userName||"".equals(userName)){ return JSONObject.parseObject("{status:0,msg:\"姓名不能为空\"}"); } String password = property.getString("password"); if(null==password||"".equals(password)){ return JSONObject.parseObject("{status:0,msg:\"密码不能为空\"}"); } //处理文件参数 handleFile(property); headers.put("Content-Type", "application/json"); String url = domain+"/mcm/api/user"; return HttpUtils.doPost(url, headers, null,property.toJSONString()); } /** * 用户登录 * @param userName * @param password * @return */ public JSONObject userLogin(String userName,String passWord){ headers.put("Content-Type", "application/json"); if(null==userName||"".equals(userName)){ return JSONObject.parseObject("{status:0,msg:\"姓名不能为空\"}"); } if(null==passWord||"".equals(passWord)){ return JSONObject.parseObject("{status:0,msg:\"密码不能为空\"}"); } String url = domain+"/mcm/api/user/login"; JSONObject property = new JSONObject(); property.put("username", userName); property.put("password", passWord); JSONObject returnJson = HttpUtils.doPost(url, headers, null,property.toJSONString()); handleAuthorization(returnJson); return returnJson; } /** * 请求验证Email * @param property * @return */ public JSONObject verifyEmail(JSONObject property){ headers.put("Content-Type", "application/json"); //校验是否传递参数 if(property==null){ return JSONObject.parseObject("{status:0,msg:\"请传递参数\"}"); } String userName = property.getString("username"); if(null==userName||"".equals(userName)){ return JSONObject.parseObject("{status:0,msg:\"姓名不能为空\"}"); } String email = property.getString("email"); if(null==email||"".equals(email)){ return JSONObject.parseObject("{status:0,msg:\"邮箱不能为空\"}"); } String url = domain+"/mcm/api/user/verifyEmail"; return HttpUtils.doPost(url, headers, null,property.toJSONString()); } /** * 密码重置 * @param property * @return */ public JSONObject resetRequest(JSONObject property){ headers.put("Content-Type", "application/json"); //校验是否传递参数 if(property==null){ return JSONObject.parseObject("{status:0,msg:\"请传递参数\"}"); } String userName = property.getString("username"); if(null==userName||"".equals(userName)){ return JSONObject.parseObject("{status:0,msg:\"姓名不能为空\"}"); } String email = property.getString("email"); if(null==email||"".equals(email)){ return JSONObject.parseObject("{status:0,msg:\"邮箱不能为空\"}"); } String url = domain+"/mcm/api/user/resetRequest"; return HttpUtils.doPost(url, headers, null,property.toJSONString()); } /** * 获取用户 * @param authorization login 返回的id * @param userId * @return */ public JSONObject getUser(String userId){ headers.put("Content-Type", "application/json"); String url = domain+"/mcm/api/user/"+userId; return HttpUtils.doGet(url, headers); } /** * 更新用户 * @param authorization * @param userId * @param property 需要更新的属性 * @return */ public JSONObject updateUser(String userId,JSONObject property){ headers.put("Content-Type", "application/json"); if(null==property){ property = new JSONObject(); } String url = domain+"/mcm/api/user/"+userId; return HttpUtils.doPut(url, headers, property.toJSONString()); } /** * 删除用户 * @param authorization * @param userId * @return */ public JSONObject deleteUser(String userId){ headers.put("Content-Type", "application/json"); String url = domain+"/mcm/api/user/"+userId; return HttpUtils.doDelete(url, headers); } /** * 登出 * @param authorization * @return */ public JSONObject loginOut(){ headers.put("Content-Type", "application/json"); String url = domain+"/mcm/api/user/logout"; return HttpUtils.doPost(url, headers, null, ""); } /** 用户 ------end------ **/ /** 角色 ------end------ **/ /** * 创建角色 * @param property * @return */ public JSONObject createRole(JSONObject property){ //校验是否传递参数 if(property==null){ return JSONObject.parseObject("{status:0,msg:\"请传递参数\"}"); } //处理文件参数 handleFile(property); headers.put("Content-Type", "application/json"); String url = domain+"/mcm/api/role"; return HttpUtils.doPost(url, headers, null,property.toJSONString()); } /** * 根据Id获取角色 * @param id * @return */ public JSONObject getRole(String id){ String url = domain+"/mcm/api/role/"+id; return HttpUtils.doGet(url, headers); } /** * 根据id更新角色 * @param id * @param property * @return */ public JSONObject updateRole(String id,JSONObject property){ //校验是否传递参数 if(property==null){ return JSONObject.parseObject("{status:0,msg:\"请传递参数\"}"); } headers.put("Content-Type", "application/json"); String url = domain+"/mcm/api/role/"+id; return HttpUtils.doPut(url, headers,property.toJSONString()); } /** * 根据Id删除角色 * @param id * @return */ public JSONObject deleteRole(String id){ String url = domain+"/mcm/api/role/"+id; return HttpUtils.doDelete(url, headers); } /** 角色 ------end------ **/ /** 批量操作------begin------ **/ /** * @param prams * @return */ public JSONObject batch(JSONObject params){ //校验是否传递参数 if(params==null){ return JSONObject.parseObject("{status:0,msg:\"请传递参数\"}"); } String url = domain+"/mcm/api/batch"; headers.put("Content-Type", "application/json"); return HttpUtils.doPost(url, headers, null, params.toJSONString()); } /** 批量操作------end------ **/ /** 文件(file)------begin------ **/ /** * 文件上传 * @param fileName * @return */ public JSONObject upload(String filePath){ if(null==filePath||"".equals(filePath)){ return JSONObject.parseObject("{status:0,msg:\"路径不能为空\"}"); } String url = domain+"/mcm/api/file"; return HttpUtils.doUpload(url, filePath , headers, new HashMap<String,String>()); } /** 文件(file)------end------ **/ /** 更新操作符------begin------ **/ /** * @param id * @param params * @return */ public JSONObject updateModel(String object,String id,JSONObject params){ //校验是否传递参数 if(params==null){ return JSONObject.parseObject("{status:0,msg:\"请传递参数\"}"); } String url = domain+"/mcm/api/"+object+"/"+id; return HttpUtils.doPut(url, headers, params.toJSONString()); } /** 更新操作符------end------ **/ /** 条件过滤------begin------ **/ /** * 按照条件过滤 * @param object * @param filter * @return */ public JSONObject doFilterSearch(String object,String filter){ if(null==object||"".equals(object)){ return JSONObject.parseObject("{status:0,msg:\"请确定查询对象\"}"); } String url = domain+"/mcm/api/"+object+"?filter="; try { url += URLEncoder.encode(filter, "utf-8"); } catch (UnsupportedEncodingException e) { } return HttpUtils.doGet(url, headers); } /** 条件过滤------end------ **/ /** 安全相关------begin------**/ /** * 设置权限验证码 * @param authorization */ public void setAuthorization(String authorization){ if(null!=authorization&&!"".equals(authorization)){ headers.put("authorization", authorization); } } /** 安全相关------end------**/ /** * 查看参数中是否含有file对象,如果有的话,先上传,在将返回的信息替换掉原来的file对象 * @param property */ private void handleFile(JSONObject property) { //查看values中是否有file对象 Set<String> keySet = property.keySet(); Iterator<String> keyIter = keySet.iterator(); while(keyIter.hasNext()){ String key = keyIter.next(); Object obj = property.get(key); if(null!=obj&&obj instanceof File){ File file = (File)obj; if(file.exists()&&file.isFile()){ JSONObject fileJson = upload(file.getPath()); property.put(key, fileJson.toJSONString()); } } } } /** * @param returnJson * 处理login返回来的authorization,登录以后缓存用户的校验码 */ private void handleAuthorization(JSONObject returnJson) { String key = returnJson.getString("id"); if(null!=key&&!"".equals(key)){ headers.put("authorization", key); } } }
apache-2.0
spinnaker/front50
front50-oracle/src/main/java/com/netflix/spinnaker/front50/config/OracleProperties.java
2383
/* * Copyright (c) 2017, 2018 Oracle Corporation and/or its affiliates. All rights reserved. * * The contents of this file are subject to the Apache License Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * If a copy of the Apache License Version 2.0 was not distributed with this file, * You can obtain one at https://www.apache.org/licenses/LICENSE-2.0.html */ package com.netflix.spinnaker.front50.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("spinnaker.oracle") public class OracleProperties { private String bucketName = "_spinnaker_front50_data"; private String namespace; private String compartmentId; private String region = "us-phoenix-1"; private String userId; private String fingerprint; private String sshPrivateKeyFilePath; private String privateKeyPassphrase; private String tenancyId; public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getCompartmentId() { return compartmentId; } public void setCompartmentId(String compartmentId) { this.compartmentId = compartmentId; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getFingerprint() { return fingerprint; } public void setFingerprint(String fingerprint) { this.fingerprint = fingerprint; } public String getSshPrivateKeyFilePath() { return sshPrivateKeyFilePath; } public void setSshPrivateKeyFilePath(String sshPrivateKeyFilePath) { this.sshPrivateKeyFilePath = sshPrivateKeyFilePath; } public String getPrivateKeyPassphrase() { return privateKeyPassphrase; } public void setPrivateKeyPassphrase(String privateKeyPassphrase) { this.privateKeyPassphrase = privateKeyPassphrase; } public String getTenancyId() { return tenancyId; } public void setTenancyId(String tenancyId) { this.tenancyId = tenancyId; } }
apache-2.0
Juklab/edmundo
namecard.java
107
import greenfoot.*; public class namecard extends object { public void act() { } }
apache-2.0
monetate/druid
processing/src/main/java/org/apache/druid/segment/DimensionDictionary.java
5885
/* * 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.druid.segment; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import javax.annotation.Nullable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Buildable dictionary for some comparable type. Values are unsorted, or rather sorted in the order which they are * added. A {@link SortedDimensionDictionary} can be constructed with a mapping of ids from this dictionary to the * sorted dictionary with the {@link #sort()} method. * * This dictionary is thread-safe. */ public class DimensionDictionary<T extends Comparable<T>> { public static final int ABSENT_VALUE_ID = -1; private final Class<T> cls; @Nullable private T minValue = null; @Nullable private T maxValue = null; private volatile int idForNull = ABSENT_VALUE_ID; private final AtomicLong sizeInBytes = new AtomicLong(0L); private final Object2IntMap<T> valueToId = new Object2IntOpenHashMap<>(); private final List<T> idToValue = new ArrayList<>(); private final ReentrantReadWriteLock lock; public DimensionDictionary(Class<T> cls) { this.cls = cls; this.lock = new ReentrantReadWriteLock(); valueToId.defaultReturnValue(ABSENT_VALUE_ID); } public int getId(@Nullable T value) { lock.readLock().lock(); try { if (value == null) { return idForNull; } return valueToId.getInt(value); } finally { lock.readLock().unlock(); } } @Nullable public T getValue(int id) { lock.readLock().lock(); try { if (id == idForNull) { return null; } return idToValue.get(id); } finally { lock.readLock().unlock(); } } public T[] getValues(int[] ids) { T[] values = (T[]) Array.newInstance(cls, ids.length); lock.readLock().lock(); try { for (int i = 0; i < ids.length; i++) { values[i] = (ids[i] == idForNull) ? null : idToValue.get(ids[i]); } return values; } finally { lock.readLock().unlock(); } } public int size() { lock.readLock().lock(); try { // using idToValue rather than valueToId because the valueToId doesn't account null value, if it is present. return idToValue.size(); } finally { lock.readLock().unlock(); } } /** * Gets the current size of this dictionary in bytes. * * @throws IllegalStateException if size computation is disabled. */ public long sizeInBytes() { if (!computeOnHeapSize()) { throw new IllegalStateException("On-heap size computation is disabled"); } return sizeInBytes.get(); } public int add(@Nullable T originalValue) { lock.writeLock().lock(); try { if (originalValue == null) { if (idForNull == ABSENT_VALUE_ID) { idForNull = idToValue.size(); idToValue.add(null); } return idForNull; } int prev = valueToId.getInt(originalValue); if (prev >= 0) { return prev; } final int index = idToValue.size(); valueToId.put(originalValue, index); idToValue.add(originalValue); if (computeOnHeapSize()) { // Add size of new dim value and 2 references (valueToId and idToValue) sizeInBytes.addAndGet(estimateSizeOfValue(originalValue) + 2L * Long.BYTES); } minValue = minValue == null || minValue.compareTo(originalValue) > 0 ? originalValue : minValue; maxValue = maxValue == null || maxValue.compareTo(originalValue) < 0 ? originalValue : maxValue; return index; } finally { lock.writeLock().unlock(); } } public T getMinValue() { lock.readLock().lock(); try { return minValue; } finally { lock.readLock().unlock(); } } public T getMaxValue() { lock.readLock().lock(); try { return maxValue; } finally { lock.readLock().unlock(); } } public int getIdForNull() { return idForNull; } public SortedDimensionDictionary<T> sort() { lock.readLock().lock(); try { return new SortedDimensionDictionary<T>(idToValue, idToValue.size()); } finally { lock.readLock().unlock(); } } /** * Estimates the size of the dimension value in bytes. This method is called * only when a new dimension value is being added to the lookup. * * @throws UnsupportedOperationException Implementations that want to estimate * memory must override this method. */ public long estimateSizeOfValue(T value) { throw new UnsupportedOperationException(); } /** * Whether on-heap size of this dictionary should be computed. * * @return false, by default. Implementations that want to estimate memory * must override this method. */ public boolean computeOnHeapSize() { return false; } }
apache-2.0
IBMStreams/streamsx.health
ingest/vines/com.ibm.streamsx.health.vines/src/main/java/com/ibm/streamsx/health/vines/model/TermArray.java
453
/******************************************************************************* * Copyright (C) 2017 International Business Machines Corporation * All Rights Reserved *******************************************************************************/ package com.ibm.streamsx.health.vines.model; import java.util.ArrayList; public class TermArray extends ArrayList<ITermValue> implements ITerm { private static final long serialVersionUID = 1L; }
apache-2.0
zdary/intellij-community
platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java
14640
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui; import com.google.common.annotations.VisibleForTesting; import com.intellij.ide.PowerSaveMode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.ScalableIcon; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.icons.CopyableIcon; import com.intellij.ui.icons.RowIcon; import com.intellij.ui.scale.ScaleType; import com.intellij.ui.tabs.impl.TabLabel; import com.intellij.util.Alarm; import com.intellij.util.Function; import com.intellij.util.IconUtil; import com.intellij.util.SlowOperations; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.JBScalableIcon; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.function.BiConsumer; public final class DeferredIconImpl<T> extends JBScalableIcon implements DeferredIcon, RetrievableIcon, IconWithToolTip, CopyableIcon { private static final Logger LOG = Logger.getInstance(DeferredIconImpl.class); private static final int MIN_AUTO_UPDATE_MILLIS = 950; private static final RepaintScheduler ourRepaintScheduler = new RepaintScheduler(); private final @NotNull Icon myDelegateIcon; private volatile @NotNull Icon myScaledDelegateIcon; private DeferredIconImpl<T> myScaledIconCache; private java.util.function.Function<? super T, ? extends Icon> myEvaluator; private volatile boolean myIsScheduled; private final T myParam; private static final Icon EMPTY_ICON = EmptyIcon.create(16).withIconPreScaled(false); private final boolean myNeedReadAction; private boolean myDone; private final boolean myAutoUpdatable; private long myLastCalcTime; private long myLastTimeSpent; private static final ExecutorService ourIconCalculatingExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("IconCalculating Pool", 1); private final BiConsumer<DeferredIcon, Icon> myEvalListener; private DeferredIconImpl(@NotNull DeferredIconImpl<T> icon) { super(icon); myDelegateIcon = icon.myDelegateIcon; myScaledDelegateIcon = icon.myDelegateIcon; myScaledIconCache = null; myEvaluator = icon.myEvaluator; myIsScheduled = icon.myIsScheduled; myParam = icon.myParam; myNeedReadAction = icon.myNeedReadAction; myDone = icon.myDone; myAutoUpdatable = icon.myAutoUpdatable; myLastCalcTime = icon.myLastCalcTime; myLastTimeSpent = icon.myLastTimeSpent; myEvalListener = icon.myEvalListener; } @Override public @NotNull DeferredIconImpl<T> copy() { return new DeferredIconImpl<>(this); } @NotNull @Override public DeferredIconImpl<T> scale(float scale) { if (getScale() == scale) { return this; } DeferredIconImpl<T> icon = myScaledIconCache; if (icon == null || icon.getScale() != scale) { icon = new DeferredIconImpl<>(this); icon.setScale(ScaleType.OBJ_SCALE.of(scale)); myScaledIconCache = icon; } icon.myScaledDelegateIcon = IconUtil.scale(icon.myDelegateIcon, null, scale); return icon; } DeferredIconImpl(Icon baseIcon, T param, @NotNull java.util.function.Function<? super T, ? extends Icon> evaluator, @NotNull BiConsumer<DeferredIcon, Icon> listener, boolean autoUpdatable) { this(baseIcon, param, true, evaluator, listener, autoUpdatable); } public static <T> @NotNull DeferredIcon withoutReadAction(Icon baseIcon, T param, @NotNull java.util.function.Function<? super T, ? extends Icon> evaluator) { return new DeferredIconImpl<>(baseIcon, param, false, evaluator, null, false); } public DeferredIconImpl(Icon baseIcon, T param, final boolean needReadAction, @NotNull Function<? super T, ? extends Icon> evaluator) { this(baseIcon, param, needReadAction, t -> evaluator.fun(t), null, false); } private DeferredIconImpl(Icon baseIcon, T param, boolean needReadAction, @NotNull java.util.function.Function<? super T, ? extends Icon> evaluator, @Nullable BiConsumer<DeferredIcon, Icon> listener, boolean autoUpdatable) { myParam = param; myDelegateIcon = nonNull(baseIcon); myScaledDelegateIcon = myDelegateIcon; myScaledIconCache = null; myEvaluator = evaluator; myNeedReadAction = needReadAction; myEvalListener = listener; myAutoUpdatable = autoUpdatable; checkDelegationDepth(); } @NotNull @Override public Icon getBaseIcon() { return myDelegateIcon; } private void checkDelegationDepth() { int depth = 0; DeferredIconImpl<?> each = this; while (each.myScaledDelegateIcon instanceof DeferredIconImpl && depth < 50) { depth++; each = (DeferredIconImpl<?>)each.myScaledDelegateIcon; } if (depth >= 50) { LOG.error("Too deep deferred icon nesting"); } } @NotNull private static Icon nonNull(@Nullable Icon icon) { return icon == null ? EMPTY_ICON : icon; } @Override public void paintIcon(Component c, @NotNull Graphics g, int x, int y) { Icon scaledDelegateIcon = myScaledDelegateIcon; if (!(scaledDelegateIcon instanceof DeferredIconImpl && ((DeferredIconImpl<?>)scaledDelegateIcon).myScaledDelegateIcon instanceof DeferredIconImpl)) { //SOE protection scaledDelegateIcon.paintIcon(c, g, x, y); } if (isDone() || myIsScheduled || PowerSaveMode.isEnabled()) { return; } scheduleEvaluation(c, x, y); } @VisibleForTesting Future<?> scheduleEvaluation(Component c, int x, int y) { myIsScheduled = true; final Component target = getTarget(c); final Component paintingParent = SwingUtilities.getAncestorOfClass(PaintingParent.class, c); final Rectangle paintingParentRec = paintingParent == null ? null : ((PaintingParent)paintingParent).getChildRec(c); return ourIconCalculatingExecutor.submit(() -> { int oldWidth = myScaledDelegateIcon.getIconWidth(); final Icon[] evaluated = new Icon[1]; final long startTime = System.currentTimeMillis(); if (myNeedReadAction) { boolean result = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(() -> { IconDeferrerImpl.evaluateDeferred(() -> evaluated[0] = evaluate()); if (myAutoUpdatable) { myLastCalcTime = System.currentTimeMillis(); myLastTimeSpent = myLastCalcTime - startTime; } }); if (!result) { myIsScheduled = false; return; } } else { IconDeferrerImpl.evaluateDeferred(() -> evaluated[0] = evaluate()); if (myAutoUpdatable) { myLastCalcTime = System.currentTimeMillis(); myLastTimeSpent = myLastCalcTime - startTime; } } final Icon result = evaluated[0]; myScaledDelegateIcon = result; checkDelegationDepth(); boolean shouldRevalidate = Registry.is("ide.tree.deferred.icon.invalidates.cache") && myScaledDelegateIcon.getIconWidth() != oldWidth; ApplicationManager.getApplication().invokeLater(() -> { setDone(result); if (equalIcons(result, myDelegateIcon)) { return; } Component actualTarget = target; if (actualTarget != null && SwingUtilities.getWindowAncestor(actualTarget) == null) { actualTarget = paintingParent; if (actualTarget == null || SwingUtilities.getWindowAncestor(actualTarget) == null) { actualTarget = null; } } if (actualTarget == null) { return; } // revalidate will not work: JTree caches size of nodes if (shouldRevalidate && actualTarget instanceof JTree) { TreeUtil.invalidateCacheAndRepaint(((JTree)actualTarget).getUI()); } if (c == actualTarget) { c.repaint(x, y, getIconWidth(), getIconHeight()); } else { ourRepaintScheduler.pushDirtyComponent(actualTarget, paintingParentRec); } }, ModalityState.any()); }); } private static Component getTarget(Component c) { final Component target; final Container list = SwingUtilities.getAncestorOfClass(JList.class, c); if (list != null) { target = list; } else { final Container tree = SwingUtilities.getAncestorOfClass(JTree.class, c); if (tree != null) { target = tree; } else { final Container table = SwingUtilities.getAncestorOfClass(JTable.class, c); if (table != null) { target = table; } else { final Container box = SwingUtilities.getAncestorOfClass(JComboBox.class, c); if (box != null) { target = box; } else { final Container tabLabel = SwingUtilities.getAncestorOfClass(TabLabel.class, c); target = tabLabel == null ? c : tabLabel; } } } } return target; } private void setDone(@NotNull Icon result) { if (myEvalListener != null) { myEvalListener.accept(this, result); } myDone = true; if (!myAutoUpdatable) { myEvaluator = null; } } @NotNull @Override public Icon retrieveIcon() { if (isDone()) { return myScaledDelegateIcon; } try (var ignored = SlowOperations.allowSlowOperations(SlowOperations.RENDERING)) { return evaluate(); } } public boolean isNeedReadAction() { return myNeedReadAction; } @NotNull @Override public Icon evaluate() { Icon result; try { result = nonNull(myEvaluator.apply(myParam)); } catch (IndexNotReadyException e) { result = EMPTY_ICON; } if (ApplicationManager.getApplication().isUnitTestMode()) { checkDoesntReferenceThis(result); } if (getScale() != 1f && result instanceof ScalableIcon) { result = ((ScalableIcon)result).scale(getScale()); } return result; } private void checkDoesntReferenceThis(final Icon icon) { if (icon == this) { throw new IllegalStateException("Loop in icons delegation"); } if (icon instanceof DeferredIconImpl) { checkDoesntReferenceThis(((DeferredIconImpl<?>)icon).myScaledDelegateIcon); } else if (icon instanceof LayeredIcon) { for (Icon layer : ((LayeredIcon)icon).getAllLayers()) { checkDoesntReferenceThis(layer); } } else if (icon instanceof com.intellij.ui.icons.RowIcon) { final com.intellij.ui.icons.RowIcon rowIcon = (RowIcon)icon; final int count = rowIcon.getIconCount(); for (int i = 0; i < count; i++) { checkDoesntReferenceThis(rowIcon.getIcon(i)); } } } @Override public int getIconWidth() { return myScaledDelegateIcon.getIconWidth(); } @Override public int getIconHeight() { return myScaledDelegateIcon.getIconHeight(); } @Override public String getToolTip(boolean composite) { if (myScaledDelegateIcon instanceof IconWithToolTip) { return ((IconWithToolTip) myScaledDelegateIcon).getToolTip(composite); } return null; } public boolean isDone() { if (myAutoUpdatable && myDone && myLastCalcTime > 0 && System.currentTimeMillis() - myLastCalcTime > Math.max(MIN_AUTO_UPDATE_MILLIS, 10 * myLastTimeSpent)) { myDone = false; myIsScheduled = false; } return myDone; } private static final class RepaintScheduler { private final Alarm myAlarm = new Alarm(); private final Set<RepaintRequest> myQueue = new LinkedHashSet<>(); private void pushDirtyComponent(@NotNull Component c, final Rectangle rec) { ApplicationManager.getApplication().assertIsDispatchThread(); // assert myQueue accessed from EDT only myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { for (RepaintRequest each : myQueue) { Rectangle r = each.rectangle; if (r == null) { each.component.repaint(); } else { each.component.repaint(r.x, r.y, r.width, r.height); } } myQueue.clear(); }, 50); myQueue.add(new RepaintRequest(c, rec)); } } private static final class RepaintRequest { final Component component; final Rectangle rectangle; private RepaintRequest(@NotNull Component component, @Nullable Rectangle rectangle) { this.component = component; this.rectangle = rectangle; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RepaintRequest request = (RepaintRequest)o; return component.equals(request.component) && Objects.equals(rectangle, request.rectangle); } @Override public int hashCode() { int result = component.hashCode(); result = 31 * result + (rectangle != null ? rectangle.hashCode() : 0); return result; } } @Override public boolean equals(Object obj) { return obj instanceof DeferredIconImpl && paramsEqual(this, (DeferredIconImpl<?>)obj); } @Override public int hashCode() { return Objects.hash(myParam, myScaledDelegateIcon); } static boolean equalIcons(Icon icon1, Icon icon2) { if (icon1 instanceof DeferredIconImpl && icon2 instanceof DeferredIconImpl) { return paramsEqual((DeferredIconImpl<?>)icon1, (DeferredIconImpl<?>)icon2); } return Objects.equals(icon1, icon2); } private static boolean paramsEqual(@NotNull DeferredIconImpl<?> icon1, @NotNull DeferredIconImpl<?> icon2) { return Comparing.equal(icon1.myParam, icon2.myParam) && equalIcons(icon1.myScaledDelegateIcon, icon2.myScaledDelegateIcon); } @Override public String toString() { return "Deferred. Base=" + myScaledDelegateIcon; } }
apache-2.0
planecyc/Java
day24/code/day24_Thread/src/cn/itcast_10/ThreadPoolDemo.java
776
package cn.itcast_10; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /* * ÇóºÍ°¸Àý */ public class ThreadPoolDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { // ´´½¨Ï̳߳ضÔÏó ExecutorService pool = Executors.newFixedThreadPool(3); // Ìá½»Êý¾Ý Future<Integer> f1 = pool.submit(new MyCallable(10)); Future<Integer> f2 = pool.submit(new MyCallable(50)); Future<Integer> f3 = pool.submit(new MyCallable(100)); Integer i1 = f1.get(); Integer i2 = f2.get(); Integer i3 = f3.get(); System.out.println(i1); System.out.println(i2); System.out.println(i3); pool.shutdown(); } }
artistic-2.0
AeroGlass/g3m
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/EffectWithForce.java
584
package org.glob3.mobile.generated; public abstract class EffectWithForce extends Effect { private double _force; private final double _friction; protected EffectWithForce(double force, double friction) { _force = force; _friction = friction; } protected final double getForce() { return _force; } public void doStep(G3MRenderContext rc, TimeInterval when) { _force *= _friction; } public boolean isDone(G3MRenderContext rc, TimeInterval when) { return (IMathUtils.instance().abs(_force) < 0.005); } }
bsd-2-clause
Stephan202/jaxb2-basics
runtime/src/test/java/org/hisrc/xml/bind/tests/dogs/Dog.java
687
package org.hisrc.xml.bind.tests.dogs; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; public class Dog extends JAXBElement<DogType> { public static final QName NAME = new QName("dog"); private static final long serialVersionUID = 1L; public Dog(DogType value) { super(NAME, DogType.class, value); } public Dog(String dogName, DogType value) { super(NAME, DogType.class, value); // if (value != null) { // value.setName(dogName); // } } @Override public QName getName() { final DogType value = getValue(); if (value != null && value.getName() != null) { return new QName(value.getName()); } else { return super.getName(); } } }
bsd-2-clause
Galigeo/mapfish-print
core/src/main/java/org/mapfish/print/processor/map/scalebar/ScalebarDrawer.java
8895
package org.mapfish.print.processor.map.scalebar; import org.mapfish.print.attribute.ScalebarAttribute.ScalebarAttributeValues; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; /** * Base class for drawing a scale bar. */ public abstract class ScalebarDrawer { /** * The graphics context. */ private final Graphics2D graphics2d; /** * Parameters for rendering the scalebar. */ private final ScaleBarRenderSettings settings; /** * Parameters for the scalebar. */ private final ScalebarAttributeValues params; /** * Constructor. * @param graphics2d The graphics context. * @param settings Parameters for rendering the scalebar. */ public ScalebarDrawer(final Graphics2D graphics2d, final ScaleBarRenderSettings settings) { this.graphics2d = graphics2d; this.settings = settings; this.params = settings.getParams(); } /** * Start the rendering of the scalebar. */ public final void draw() { final AffineTransform transform = getAlignmentTransform(); // draw the background box this.graphics2d.setTransform(transform); this.graphics2d.setColor(this.params.getBackgroundColor()); this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height); //sets the transformation for drawing the labels and do it final AffineTransform labelTransform = new AffineTransform(transform); setLabelTranslate(labelTransform); this.graphics2d.setTransform(labelTransform); this.graphics2d.setColor(this.params.getFontColor()); drawLabels(this.params.getOrientation()); //sets the transformation for drawing the bar and do it final AffineTransform lineTransform = new AffineTransform(transform); setLineTranslate(lineTransform); if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT || this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) { final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1); lineTransform.concatenate(rotate); } this.graphics2d.setTransform(lineTransform); this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth())); this.graphics2d.setColor(this.params.getColor()); drawBar(); } /** * Create a transformation which takes the alignment settings into account. */ private AffineTransform getAlignmentTransform() { final int offsetX; switch (this.settings.getParams().getAlign()) { case LEFT: offsetX = 0; break; case RIGHT: offsetX = this.settings.getMaxSize().width - this.settings.getSize().width; break; case CENTER: default: offsetX = (int) Math.floor(this.settings.getMaxSize().width / 2.0 - this.settings.getSize().width / 2.0); break; } final int offsetY; switch (this.settings.getParams().getVerticalAlign()) { case TOP: offsetY = 0; break; case BOTTOM: offsetY = this.settings.getMaxSize().height - this.settings.getSize().height; break; case MIDDLE: default: offsetY = (int) Math.floor(this.settings.getMaxSize().height / 2.0 - this.settings.getSize().height / 2.0); break; } return AffineTransform.getTranslateInstance(offsetX, offsetY); } private void setLineTranslate(final AffineTransform lineTransform) { if (this.params.getOrientation() == Orientation.HORIZONTAL_LABELS_BELOW) { lineTransform.translate( this.settings.getPadding() + this.settings.getLeftLabelMargin(), this.settings.getPadding() + this.settings.getBarSize()); } else if (this.params.getOrientation() == Orientation.HORIZONTAL_LABELS_ABOVE) { lineTransform.translate( this.settings.getPadding() + this.settings.getLeftLabelMargin(), this.settings.getPadding() + this.settings.getBarSize() + this.settings.getLabelDistance() + this.settings.getMaxLabelSize().height); } else if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT) { lineTransform.translate( this.settings.getPadding() + this.settings.getMaxLabelSize().width + this.settings.getLabelDistance(), this.settings.getPadding() + this.settings.getTopLabelMargin()); } else if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) { lineTransform.translate( this.settings.getPadding(), this.settings.getPadding() + this.settings.getTopLabelMargin()); } } private void setLabelTranslate(final AffineTransform labelTransform) { if (this.params.getOrientation() == Orientation.HORIZONTAL_LABELS_BELOW) { labelTransform.translate( this.settings.getPadding() + this.settings.getLeftLabelMargin(), this.settings.getPadding() + this.settings.getBarSize() + this.settings.getLabelDistance() + this.settings.getMaxLabelSize().height); } else if (this.params.getOrientation() == Orientation.HORIZONTAL_LABELS_ABOVE) { labelTransform.translate( this.settings.getPadding() + this.settings.getLeftLabelMargin(), this.settings.getPadding() + this.settings.getMaxLabelSize().height); } else if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT) { labelTransform.translate( this.settings.getPadding(), this.settings.getPadding() + this.settings.getTopLabelMargin()); } else if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) { labelTransform.translate( this.settings.getPadding() + this.settings.getBarSize() + this.settings.getLabelDistance(), this.settings.getPadding() + this.settings.getTopLabelMargin()); } } /** * Draws the bar itself. The transformation is setup in a manner where the * bar should be drawn into the rectangle (0, 0) (intervals*intervalWidth, -barSize). */ protected abstract void drawBar(); private float getTotalLength(final Orientation orientation) { if (orientation.isHorizontal()) { return this.settings.getIntervalLengthInPixels() * this.params.intervals + this.settings.getLeftLabelMargin() + this.settings.getRightLabelMargin(); } else { return this.settings.getIntervalLengthInPixels() * this.params.intervals + this.settings.getTopLabelMargin() + this.settings.getBottomLabelMargin(); } } private void drawLabels(final Orientation orientation) { float prevPos = getTotalLength(orientation); for (int i = this.settings.getLabels().size() - 1; i >= 0; i--) { final Label label = this.settings.getLabels().get(i); final float posX; final float posY; final float newPos; final boolean shouldSkipLabel; if (orientation.isHorizontal()) { final float offsetH = -label.getWidth() / 2; posX = label.getGraphicOffset() + offsetH; posY = 0; shouldSkipLabel = label.getGraphicOffset() + Math.abs(offsetH) > prevPos - 1; newPos = label.getGraphicOffset() - Math.abs(offsetH); } else { final float offsetV = label.getHeight() / 2; if (orientation == Orientation.VERTICAL_LABELS_LEFT) { posX = this.settings.getMaxLabelSize().width - label.getWidth(); } else { posX = 0; } posY = label.getGraphicOffset() + offsetV; shouldSkipLabel = label.getGraphicOffset() + offsetV > prevPos - 1; newPos = label.getGraphicOffset() - Math.abs(offsetV); } if (!shouldSkipLabel) { label.getLabelLayout().draw(this.graphics2d, posX, posY); prevPos = newPos; } else { //the label would be written over the previous one => ignore it } } } public final Graphics2D getGraphics2d() { return this.graphics2d; } public final ScaleBarRenderSettings getSettings() { return this.settings; } public final ScalebarAttributeValues getParams() { return this.params; } }
bsd-2-clause
synergynet/synergynet2.1
SynergySpace2.1/src_synergynet/synergynet/table/apps/splasher/SplasherApp.java
3382
/* * Copyright (c) 2009 University of Durham, England * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'SynergySpace' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package synergynet.table.apps.splasher; import java.net.URL; import java.util.ArrayList; import java.util.List; import com.jme.scene.Geometry; import com.jme.scene.shape.Quad; import synergynet.table.animationsystem.AnimationSystem; import synergynet.table.animationsystem.animations.SplashSequence; import synergynet.table.animationsystem.animelements.AnimationSequence; import synergynet.table.animationsystem.animelements.ApplicationActivator; import synergynet.table.appregistry.ApplicationInfo; import synergynet.table.apps.DefaultSynergyNetApp; import synergynet.table.gfx.GFXUtils; import synergyspace.jme.gfx.twod.ImageQuadFactory; public class SplasherApp extends DefaultSynergyNetApp { protected AnimationSequence seq; protected Quad splash; protected ApplicationInfo nextApp; protected URL imageURL = SplasherApp.class.getResource("synergyspacelogo.png"); protected float imgWidth = 200; public SplasherApp(ApplicationInfo info) { super(info); // TODO Auto-generated constructor stub } public void setNextApp(ApplicationInfo nextApp) { this.nextApp = nextApp; } @Override public void addContent() { } public void setSplashImageURL(URL imgURL, float imgWidth) { this.imageURL = imgURL; this.imgWidth = imgWidth; } public void splash() { seq = new AnimationSequence(); List<Geometry> splashings = new ArrayList<Geometry>(); splash = ImageQuadFactory.createQuadWithUncompressedImageResource("splash", imgWidth, imageURL, ImageQuadFactory.ALPHA_ENABLE); GFXUtils.centerOrthogonalSpatial(splash); splashings.add(splash); orthoNode.attachChild(splash); seq.addAnimationElement(new SplashSequence(splashings, 2, 3f)); seq.addAnimationElement(new ApplicationActivator(nextApp)); AnimationSystem.getInstance().add(seq); } }
bsd-2-clause
Clashsoft/Dyvil
library/src/main/java/dyvil/collection/impl/AbstractArrayMap.java
12142
package dyvil.collection.impl; import dyvil.annotation.internal.NonNull; import dyvil.annotation.internal.Nullable; import dyvil.collection.*; import dyvil.util.None; import dyvil.util.Option; import dyvil.util.Some; import java.io.IOException; import java.util.Iterator; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.Consumer; @SuppressWarnings("unchecked") public abstract class AbstractArrayMap<K, V> implements Map<K, V> { protected class ArrayMapEntry implements Entry<K, V> { private static final long serialVersionUID = -967348930318928118L; private int index; public ArrayMapEntry(int index) { this.index = index; } @Override public K getKey() { return (K) AbstractArrayMap.this.keys[this.index]; } @Override public V getValue() { return (V) AbstractArrayMap.this.values[this.index]; } @Override public String toString() { return Entry.entryToString(this); } @Override public boolean equals(Object obj) { return Entry.entryEquals(this, obj); } @Override public int hashCode() { return Entry.entryHashCode(this); } } private static final long serialVersionUID = -4958236535555733690L; protected static final int DEFAULT_CAPACITY = 16; protected transient int size; protected transient Object @NonNull [] keys; protected transient Object @NonNull [] values; public AbstractArrayMap() { this.keys = new Object[DEFAULT_CAPACITY]; this.values = new Object[DEFAULT_CAPACITY]; } protected AbstractArrayMap(int capacity) { this.keys = new Object[capacity]; this.values = new Object[capacity]; } public AbstractArrayMap(K @NonNull [] keys, V @NonNull [] values) { int size = keys.length; if (size != values.length) { throw new IllegalArgumentException("keys.length != values.length"); } this.keys = new Object[size]; System.arraycopy(keys, 0, this.keys, 0, size); this.values = new Object[size]; System.arraycopy(values, 0, this.values, 0, size); this.size = size; } public AbstractArrayMap(K @NonNull [] keys, V @NonNull [] values, int size) { if (keys.length < size) { throw new IllegalArgumentException("keys.length < size"); } if (values.length < size) { throw new IllegalArgumentException("values.length < size"); } this.keys = new Object[size]; System.arraycopy(keys, 0, this.keys, 0, size); this.values = new Object[size]; System.arraycopy(values, 0, this.values, 0, size); this.size = size; } public AbstractArrayMap(K @NonNull [] keys, V @NonNull [] values, @SuppressWarnings("UnusedParameters") boolean trusted) { this.keys = keys; this.values = values; this.size = keys.length; } public AbstractArrayMap(K @NonNull [] keys, V @NonNull [] values, int size, @SuppressWarnings("UnusedParameters") boolean trusted) { this.keys = keys; this.values = values; this.size = size; } public AbstractArrayMap(Entry<? extends K, ? extends V> @NonNull [] entries) { this(entries.length); for (Entry<? extends K, ? extends V> entry : entries) { this.putInternal(entry.getKey(), entry.getValue()); } } public AbstractArrayMap(@NonNull Iterable<? extends @NonNull Entry<? extends K, ? extends V>> iterable) { this(); this.loadEntries(iterable); } public AbstractArrayMap(@NonNull SizedIterable<? extends @NonNull Entry<? extends K, ? extends V>> iterable) { this(iterable.size()); this.loadEntries(iterable); } public AbstractArrayMap(@NonNull Set<? extends @NonNull Entry<? extends K, ? extends V>> set) { this(set.size()); this.loadDistinctEntries(set); } public AbstractArrayMap(@NonNull Map<? extends K, ? extends V> map) { this(map.size()); this.loadDistinctEntries(map); } public AbstractArrayMap(@NonNull AbstractArrayMap<? extends K, ? extends V> map) { this.size = map.size; this.keys = map.keys.clone(); this.values = map.values.clone(); } private void loadEntries(@NonNull Iterable<? extends @NonNull Entry<? extends K, ? extends V>> iterable) { for (Entry<? extends K, ? extends V> entry : iterable) { this.putInternal(entry.getKey(), entry.getValue()); } } private void loadDistinctEntries(@NonNull Iterable<? extends @NonNull Entry<? extends K, ? extends V>> iterable) { int index = 0; for (Entry<? extends K, ? extends V> entry : iterable) { this.keys[index] = entry.getKey(); this.values[index] = entry.getValue(); index++; } this.size = index; } @Override public int size() { return this.size; } @Override public boolean isEmpty() { return this.size == 0; } protected abstract class ArrayIterator<R> implements Iterator<R> { protected int index; @Override public boolean hasNext() { return this.index < AbstractArrayMap.this.size; } @Override public void remove() { if (this.index == 0) { throw new IllegalStateException(); } AbstractArrayMap.this.removeAt(this.index--); } } @NonNull @Override public Iterator<Entry<K, V>> iterator() { return new ArrayIterator<Entry<K, V>>() { @NonNull @Override public Entry<K, V> next() { return new ArrayMapEntry(this.index++); } }; } @NonNull @Override public Iterator<K> keyIterator() { return new ArrayIterator<K>() { @Override public K next() { return (K) AbstractArrayMap.this.keys[this.index++]; } }; } @NonNull @Override public Iterator<V> valueIterator() { return new ArrayIterator<V>() { @NonNull @Override public V next() { return (V) AbstractArrayMap.this.values[this.index++]; } }; } protected void putNew(K key, V value) { int index = this.size++; if (index >= this.keys.length) { int newCapacity = (int) (this.size * 1.1F); Object[] newKeys = new Object[newCapacity]; Object[] newValues = new Object[newCapacity]; System.arraycopy(this.keys, 0, newKeys, 0, index); System.arraycopy(this.values, 0, newValues, 0, index); this.keys = newKeys; this.values = newValues; } this.keys[index] = key; this.values[index] = value; } @Nullable protected V putInternal(K key, V value) { for (int i = 0; i < this.size; i++) { if (Objects.equals(key, this.keys[i])) { V oldValue = (V) this.values[i]; this.values[i] = value; return oldValue; } } this.putNew(key, value); return null; } protected abstract void removeAt(int index); @Override public void forEach(@NonNull Consumer<? super Entry<K, V>> action) { for (int i = 0; i < this.size; i++) { action.accept(new ArrayMapEntry(i)); } } @Override public void forEach(@NonNull BiConsumer<? super K, ? super V> action) { for (int i = 0; i < this.size; i++) { action.accept((K) this.keys[i], (V) this.values[i]); } } @Override public void forEachKey(@NonNull Consumer<? super K> action) { for (int i = 0; i < this.size; i++) { action.accept((K) this.keys[i]); } } @Override public void forEachValue(@NonNull Consumer<? super V> action) { for (int i = 0; i < this.size; i++) { action.accept((V) this.values[i]); } } @Override public boolean containsKey(@Nullable Object key) { if (key == null) { for (int i = 0; i < this.size; i++) { if (this.keys[i] == null) { return true; } } return false; } for (int i = 0; i < this.size; i++) { if (key.equals(this.keys[i])) { return true; } } return false; } @Override public boolean contains(@Nullable Object key, @Nullable Object value) { if (key == null) { for (int i = 0; i < this.size; i++) { if (this.keys[i] == null && (value == null ? this.values[i] == null : value.equals(this.values[i]))) { return true; } } return false; } for (int i = 0; i < this.size; i++) { if (key.equals(this.keys[i]) && (value == null ? this.values[i] == null : value.equals(this.values[i]))) { return true; } } return false; } @Override public boolean containsValue(@Nullable Object value) { if (value == null) { for (int i = 0; i < this.size; i++) { if (this.values[i] == null) { return true; } } return false; } for (int i = 0; i < this.size; i++) { if (value.equals(this.values[i])) { return true; } } return false; } protected int getIndex(@Nullable Object key) { if (key == null) { for (int i = 0; i < this.size; i++) { if (this.keys[i] == null) { return i; } } return -1; } for (int i = 0; i < this.size; i++) { if (key.equals(this.keys[i])) { return i; } } return -1; } @Override public @Nullable V get(Object key) { final int index = this.getIndex(key); if (index < 0) { return null; } return (V) this.values[index]; } @NonNull @Override public Option<V> getOption(@Nullable Object key) { if (key == null) { for (int i = 0; i < this.size; i++) { if (this.keys[i] == null) { return new Some<>((V) this.values[i]); } } return (Option<V>) None.instance; } for (int i = 0; i < this.size; i++) { if (key.equals(this.keys[i])) { return new Some<>((V) this.values[i]); } } return (Option<V>) None.instance; } @Override public void toArray(int index, @NonNull Entry<K, V> @NonNull [] store) { for (int i = 0; i < this.size; i++) { store[index++] = new ArrayMapEntry(i); } } @Override public void toKeyArray(int index, Object @NonNull [] store) { System.arraycopy(this.keys, 0, store, index, this.size); } @Override public void toValueArray(int index, Object @NonNull [] store) { System.arraycopy(this.values, 0, store, index, this.size); } @NonNull @Override public <RK, RV> MutableMap<RK, RV> emptyCopy() { return new dyvil.collection.mutable.ArrayMap<>(); } @NonNull @Override public <RK, RV> MutableMap<RK, RV> emptyCopy(int capacity) { return new dyvil.collection.mutable.ArrayMap<>(capacity); } @NonNull @Override public MutableMap<K, V> mutableCopy() { return new dyvil.collection.mutable.ArrayMap<>(this); } @NonNull @Override public ImmutableMap<K, V> immutableCopy() { return new dyvil.collection.immutable.ArrayMap<>(this); } @Override public <RK, RV> ImmutableMap.Builder<RK, RV> immutableBuilder() { return dyvil.collection.immutable.ArrayMap.builder(); } @Override public <RK, RV> ImmutableMap.Builder<RK, RV> immutableBuilder(int capacity) { return dyvil.collection.immutable.ArrayMap.builder(capacity); } @Override public java.util.Map<K, V> toJava() { java.util.LinkedHashMap<K, V> map = new java.util.LinkedHashMap<>(this.size); for (int i = 0; i < this.size; i++) { map.put((K) this.keys[i], (V) this.values[i]); } return map; } @Override public String toString() { if (this.size <= 0) { return Map.EMPTY_STRING; } final StringBuilder builder = new StringBuilder(Map.START_STRING); builder.append(this.keys[0]).append(Map.KEY_VALUE_SEPARATOR_STRING).append(this.values[0]); for (int i = 1; i < this.size; i++) { builder.append(Map.ENTRY_SEPARATOR_STRING); builder.append(this.keys[i]).append(Map.KEY_VALUE_SEPARATOR_STRING).append(this.values[i]); } return builder.append(END_STRING).toString(); } @Override public boolean equals(Object obj) { return Map.mapEquals(this, obj); } @Override public int hashCode() { return Map.mapHashCode(this); } private void writeObject(java.io.@NonNull ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(this.size); for (int i = 0; i < this.size; i++) { out.writeObject(this.keys[i]); out.writeObject(this.values[i]); } } private void readObject(java.io.@NonNull ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.size = in.readInt(); this.keys = new Object[this.size]; this.values = new Object[this.size]; for (int i = 0; i < this.size; i++) { this.keys[i] = in.readObject(); this.values[i] = in.readObject(); } } }
bsd-3-clause
sahara-labs/rig-client
src/au/edu/uts/eng/remotelabs/rigclient/intf/types/tests/MaintenanceRequestTypeTester.java
4334
/** * SAHARA Rig Client * * Software abstraction of physical rig to provide rig session control * and rig device control. Automatically tests rig hardware and reports * the rig status to ensure rig goodness. * * @license See LICENSE in the top level directory for complete license terms. * * Copyright (c) 2009, University of Technology, Sydney * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Technology, Sydney nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Michael Diponio (mdiponio) * @date 12th December 2009 * * Changelog: * - 12/12/2009 - mdiponio - Initial file creation. */ package au.edu.uts.eng.remotelabs.rigclient.intf.types.tests; import java.io.ByteArrayInputStream; import junit.framework.TestCase; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.StAXUtils; import org.junit.Test; import au.edu.uts.eng.remotelabs.rigclient.intf.types.MaintenanceRequestType; import au.edu.uts.eng.remotelabs.rigclient.intf.types.SetMaintenance; /** * Tests the {@link MaintenanceRequestType} class. */ public class MaintenanceRequestTypeTester extends TestCase { @Test public void testParse() throws Exception { String xml = "<ns1:setMaintenance xmlns:ns1=\"http://remotelabs.eng.uts.edu.au/rigclient/protocol\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns1:MaintenanceRequestType\">\n" + " <identityToken>abc123</identityToken>\n" + " <requestor>mdiponio</requestor>\n" + " <putOffline>false</putOffline>\n" + " <runTests>true</runTests>\n" + " </ns1:setMaintenance>"; MaintenanceRequestType request = MaintenanceRequestType.Factory.parse( StAXUtils.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()))); assertEquals("mdiponio", request.getRequestor()); assertEquals("abc123", request.getIdentityToken()); assertFalse(request.getPutOffline()); assertTrue(request.getRunTests()); } @Test public void testSerialize() throws Exception { MaintenanceRequestType obj = new MaintenanceRequestType(); obj.setIdentityToken("abc123"); obj.setRequestor("tmachet"); obj.setPutOffline(false); obj.setRunTests(false); OMElement ele = obj.getOMElement(SetMaintenance.MY_QNAME, OMAbstractFactory.getOMFactory()); String str = ele.toStringWithConsume(); assertFalse(str.isEmpty()); assertTrue(str.contains("<identityToken>abc123</identityToken>")); assertTrue(str.contains("<requestor>tmachet</requestor>")); assertTrue(str.contains("<putOffline>false</putOffline>")); assertTrue(str.contains("<runTests>false</runTests>")); } }
bsd-3-clause
Team4550/2012_1583_Robot
src/com/rop/outputs/Elevator.java
840
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.rop.outputs; import edu.wpi.first.wpilibj.Relay; /** * * @author Adam */ public class Elevator { private static Elevator INSTANCE = null; Relay spike = null; private Elevator() { spike = new Relay(1); spike.setDirection(Relay.Direction.kForward); } public static Elevator getInstance() { if (INSTANCE == null) INSTANCE = new Elevator(); return INSTANCE; } public void turnOn() { spike.set(Relay.Value.kForward); } public void turnOff() { spike.set(Relay.Value.kOff); } public void test(boolean flag) { if (flag) turnOn(); else turnOff(); } }
bsd-3-clause
interdroid/ibis-ipl
src/ibis/ipl/impl/stacking/lrmc/LrmcIbis.java
12871
package ibis.ipl.impl.stacking.lrmc; import ibis.ipl.Credentials; import ibis.ipl.Ibis; import ibis.ipl.IbisCapabilities; import ibis.ipl.IbisConfigurationException; import ibis.ipl.IbisCreationFailedException; import ibis.ipl.IbisFactory; import ibis.ipl.IbisIdentifier; import ibis.ipl.MessageUpcall; import ibis.ipl.NoSuchPropertyException; import ibis.ipl.PortType; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortConnectUpcall; import ibis.ipl.Registry; import ibis.ipl.RegistryEventHandler; import ibis.ipl.SendPort; import ibis.ipl.SendPortDisconnectUpcall; import ibis.ipl.impl.stacking.lrmc.util.DynamicObjectArray; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LrmcIbis implements Ibis { private static final Logger logger = LoggerFactory .getLogger(LrmcIbis.class); static final PortType additionalPortType = new PortType( PortType.SERIALIZATION_DATA, PortType.COMMUNICATION_RELIABLE, PortType.CONNECTION_MANY_TO_ONE, PortType.RECEIVE_AUTO_UPCALLS); private static class EventHandler implements RegistryEventHandler { RegistryEventHandler h; LrmcIbis ibis; EventHandler(RegistryEventHandler h, LrmcIbis ibis) { this.h = h; this.ibis = ibis; } public void joined(IbisIdentifier id) { ibis.addIbis(id); if (h != null) { h.joined(id); } } public void left(IbisIdentifier id) { ibis.removeIbis(id); if (h != null) { h.left(id); } } public void died(IbisIdentifier id) { ibis.removeIbis(id); if (h != null) { h.died(id); } } public void gotSignal(String s, IbisIdentifier id) { if (h != null) { h.gotSignal(s, id); } } public void electionResult(String electionName, IbisIdentifier winner) { if (h != null) { h.electionResult(electionName, winner); } } public void poolClosed() { if (h != null) { h.poolClosed(); } } public void poolTerminated(IbisIdentifier source) { if (h != null) { h.poolTerminated(source); } } } Ibis base; int myID; PortType[] portTypes; IbisCapabilities capabilities; private int nextIbisID = 0; private BitSet diedIbises = new BitSet(); HashMap<IbisIdentifier, Integer> knownIbis = new HashMap<IbisIdentifier, Integer>(); DynamicObjectArray<IbisIdentifier> ibisList = new DynamicObjectArray<IbisIdentifier>(); HashMap<String, Multicaster> multicasters = new HashMap<String, Multicaster>(); public LrmcIbis(IbisFactory factory, RegistryEventHandler registryEventHandler, Properties userProperties, IbisCapabilities capabilities, Credentials credentials, byte[] applicationTag, PortType[] portTypes, String specifiedSubImplementation, LrmcIbisStarter lrmcIbisStarter) throws IbisCreationFailedException { List<PortType> requiredPortTypes = new ArrayList<PortType>(); logger.info("Constructor LRMC Ibis"); if (specifiedSubImplementation == null) { throw new IbisCreationFailedException( "LrmcIbis: child Ibis implementation not specified"); } EventHandler h = null; if (registryEventHandler != null) { h = new EventHandler(registryEventHandler, this); } this.portTypes = portTypes; this.capabilities = capabilities; // add additional port-type as a requirement, and remove port-types // that we deal with ourselves. for (PortType portType: portTypes) { if (! ourPortType(portType)) { requiredPortTypes.add(portType); } } requiredPortTypes.add(additionalPortType); base = factory.createIbis(h, capabilities, userProperties, credentials, applicationTag, requiredPortTypes.toArray(new PortType[requiredPortTypes.size()]), specifiedSubImplementation); } public synchronized void addIbis(IbisIdentifier ibis) { if (!knownIbis.containsKey(ibis)) { knownIbis.put(ibis, new Integer(nextIbisID)); ibisList.put(nextIbisID, ibis); logger.info("Adding Ibis " + nextIbisID + " " + ibis); if (ibis.equals(identifier())) { logger.info("I am " + nextIbisID + " " + ibis); myID = nextIbisID; } nextIbisID++; notifyAll(); } } synchronized IbisIdentifier getId(int id) { if (diedIbises.get(id)) { return null; } IbisIdentifier ibisID = ibisList.get(id); if (ibisID == null) { try { wait(10000); } catch (Exception e) { // ignored } return ibisList.get(id); } return ibisID; } synchronized int getIbisID(IbisIdentifier ibis) { Integer s = knownIbis.get(ibis); if (s != null) { return s.intValue(); } else { logger.debug("Ibis " + ibis + " not known!"); return -1; } } public synchronized void removeIbis(IbisIdentifier ibis) { Integer tmp = knownIbis.remove(ibis); if (tmp != null) { logger.info("Removing ibis " + tmp.intValue() + " " + ibis); ibisList.remove(tmp.intValue()); } diedIbises.set(tmp.intValue()); } synchronized Multicaster getMulticaster(String name, PortType portType) throws IOException { Multicaster om = multicasters.get(name); if (om == null) { om = new Multicaster(this, portType, name); multicasters.put(name, om); } else { if (!om.portType.equals(portType)) { throw new IOException("Mismatch in port types for name " + name); } } return om; } public String getVersion() { return "LrmcIbis on top of " + base.getVersion(); } public SendPort createSendPort(PortType portType, String name, SendPortDisconnectUpcall cU, Properties props) throws IOException { matchPortType(portType); if (ourPortType(portType)) { if (name == null) { throw new IOException("Anonymous ports not supported"); } if (cU != null && !portType.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "connection upcalls not supported by this porttype"); } synchronized (this) { Multicaster mc = getMulticaster(name, portType); if (mc.sendPort != null) { throw new IOException( "A sendport with the same name already exists"); } mc.sendPort = new LrmcSendPort(mc, this, props); return mc.sendPort; } } return new StackingSendPort(portType, this, name, cU, props); } public ReceivePort createReceivePort(PortType portType, String name, MessageUpcall u, ReceivePortConnectUpcall cU, Properties props) throws IOException { matchPortType(portType); if (ourPortType(portType)) { if (name == null) { throw new IOException("Anonymous ports not supported"); } if (cU != null && !portType.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "connection upcalls not supported by this porttype"); } if (u != null && !portType.hasCapability(PortType.RECEIVE_AUTO_UPCALLS)) { throw new IbisConfigurationException( "upcalls not supported by this porttype"); } if (u == null && !portType.hasCapability(PortType.RECEIVE_EXPLICIT)) { throw new IbisConfigurationException( "explicit receive not supported by this porttype"); } synchronized (this) { Multicaster mc = getMulticaster(name, portType); if (mc.receivePort != null) { throw new IOException( "A receiveport with the same name already exists"); } mc.receivePort = new LrmcReceivePort(mc, this, u, props); return mc.receivePort; } } return new StackingReceivePort(portType, this, name, u, cU, props); } public ReceivePort createReceivePort(PortType portType, String receivePortName) throws IOException { return createReceivePort(portType, receivePortName, null, null, null); } public ReceivePort createReceivePort(PortType portType, String receivePortName, MessageUpcall messageUpcall) throws IOException { return createReceivePort(portType, receivePortName, messageUpcall, null, null); } public ReceivePort createReceivePort(PortType portType, String receivePortName, ReceivePortConnectUpcall receivePortConnectUpcall) throws IOException { return createReceivePort(portType, receivePortName, null, receivePortConnectUpcall, null); } public ibis.ipl.SendPort createSendPort(PortType tp) throws IOException { return createSendPort(tp, null, null, null); } public ibis.ipl.SendPort createSendPort(PortType tp, String name) throws IOException { return createSendPort(tp, name, null, null); } private void matchPortType(PortType tp) { boolean matched = false; for (PortType p : portTypes) { if (tp.equals(p)) { matched = true; } } if (!matched) { throw new IbisConfigurationException("PortType " + tp + " not specified when creating this Ibis instance"); } } public void end() throws IOException { for (Map.Entry<String, Multicaster> x : multicasters.entrySet()) { x.getValue().done(); } base.end(); } public Registry registry() { // return new // ibis.ipl.impl.registry.ForwardingRegistry(base.registry()); return base.registry(); } public Map<String, String> managementProperties() { return base.managementProperties(); } public String getManagementProperty(String key) throws NoSuchPropertyException { return base.getManagementProperty(key); } public void setManagementProperties(Map<String, String> properties) throws NoSuchPropertyException { base.setManagementProperties(properties); } public void setManagementProperty(String key, String val) throws NoSuchPropertyException { base.setManagementProperty(key, val); } public void printManagementProperties(PrintStream stream) { base.printManagementProperties(stream); } public void poll() throws IOException { base.poll(); } public IbisIdentifier identifier() { return base.identifier(); } public Properties properties() { return base.properties(); } /** * Determines if the specified port type is one that is implemented * by Lrmc ibis. * @param tp the port type * @return <code>true</code> if LRMC Ibis deals with this port type, * <code>false</code> if it is to be passed on to an underlying ibis. */ private static boolean ourPortType(PortType tp) { return (tp.hasCapability(PortType.CONNECTION_MANY_TO_MANY) || tp .hasCapability(PortType.CONNECTION_ONE_TO_MANY)) && !tp.hasCapability(PortType.COMMUNICATION_RELIABLE) && !tp.hasCapability(PortType.CONNECTION_UPCALLS) && !tp.hasCapability(PortType.CONNECTION_DOWNCALLS) && !tp.hasCapability(PortType.COMMUNICATION_NUMBERED) && !tp.hasCapability(PortType.COMMUNICATION_FIFO); } }
bsd-3-clause
MaTriXy/fresco
imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormats.java
2941
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.imageformat; import com.facebook.common.internal.ImmutableList; import java.util.ArrayList; import java.util.List; /** * Default image formats that Fresco supports. */ public final class DefaultImageFormats { public static final ImageFormat JPEG = new ImageFormat("JPEG", "jpeg"); public static final ImageFormat PNG = new ImageFormat("PNG", "png"); public static final ImageFormat GIF = new ImageFormat("GIF", "gif"); public static final ImageFormat BMP = new ImageFormat("BMP", "bmp"); public static final ImageFormat WEBP_SIMPLE = new ImageFormat("WEBP_SIMPLE", "webp"); public static final ImageFormat WEBP_LOSSLESS = new ImageFormat("WEBP_LOSSLESS", "webp"); public static final ImageFormat WEBP_EXTENDED = new ImageFormat("WEBP_EXTENDED", "webp"); public static final ImageFormat WEBP_EXTENDED_WITH_ALPHA = new ImageFormat("WEBP_EXTENDED_WITH_ALPHA", "webp"); public static final ImageFormat WEBP_ANIMATED = new ImageFormat("WEBP_ANIMATED", "webp"); private static ImmutableList<ImageFormat> sAllDefaultFormats; /** * Check if the given image format is a WebP image format (static or animated). * * @param imageFormat the image format to check * @return true if WebP format */ public static boolean isWebpFormat(ImageFormat imageFormat) { return isStaticWebpFormat(imageFormat) || imageFormat == WEBP_ANIMATED; } /** * Check if the given image format is static WebP (not animated). * * @param imageFormat the image format to check * @return true if static WebP */ public static boolean isStaticWebpFormat(ImageFormat imageFormat) { return imageFormat == WEBP_SIMPLE || imageFormat == WEBP_LOSSLESS || imageFormat == WEBP_EXTENDED || imageFormat == WEBP_EXTENDED_WITH_ALPHA; } /** * Get all default formats supported by Fresco. * Does not include {@link ImageFormat#UNKNOWN}. * * @return all supported default formats */ public static List<ImageFormat> getDefaultFormats() { if (sAllDefaultFormats == null) { List<ImageFormat> mDefaultFormats = new ArrayList<>(9); mDefaultFormats.add(JPEG); mDefaultFormats.add(PNG); mDefaultFormats.add(GIF); mDefaultFormats.add(BMP); mDefaultFormats.add(WEBP_SIMPLE); mDefaultFormats.add(WEBP_LOSSLESS); mDefaultFormats.add(WEBP_EXTENDED); mDefaultFormats.add(WEBP_EXTENDED_WITH_ALPHA); mDefaultFormats.add(WEBP_ANIMATED); sAllDefaultFormats = ImmutableList.copyOf(mDefaultFormats); } return sAllDefaultFormats; } private DefaultImageFormats() { } }
bsd-3-clause
anildahiya/sdl_android
base/src/main/java/com/smartdevicelink/proxy/callbacks/OnServiceEnded.java
2086
/* * Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the SmartDeviceLink Consortium, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.smartdevicelink.proxy.callbacks; import com.smartdevicelink.protocol.enums.SessionType; public class OnServiceEnded extends InternalProxyMessage { private SessionType sessionType; public OnServiceEnded() { super(InternalProxyMessage.OnServiceEnded); } public OnServiceEnded(SessionType sessionType) { super(InternalProxyMessage.OnServiceEnded); this.sessionType = sessionType; } public SessionType getSessionType() { return this.sessionType; } }
bsd-3-clause
iamedu/dari
db/src/main/java/com/psddev/dari/db/UnsupportedIndexException.java
708
package com.psddev.dari.db; @SuppressWarnings("serial") public class UnsupportedIndexException extends UnsupportedOperationException { private final Object reader; private final String field; public UnsupportedIndexException(Object reader, String field) { this.reader = reader; this.field = field; } public Object getReader() { return reader; } public String getField() { return field; } // --- Throwable support --- @Override public String getMessage() { return String.format( "[%s] field is not indexed in [%s]!", getField(), getReader().getClass().getSimpleName()); } }
bsd-3-clause
LWJGL-CI/lwjgl3
modules/lwjgl/xxhash/src/generated/java/org/lwjgl/util/xxhash/XXH32Canonical.java
10608
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.util.xxhash; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * Canonical (big endian) representation of {@code XXH32_hash_t}. * * <h3>Layout</h3> * * <pre><code> * struct XXH32_canonical_t { * unsigned char {@link #digest}[4]; * }</code></pre> */ @NativeType("struct XXH32_canonical_t") public class XXH32Canonical extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int DIGEST; static { Layout layout = __struct( __array(1, 4) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); DIGEST = layout.offsetof(0); } /** * Creates a {@code XXH32Canonical} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public XXH32Canonical(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** hash bytes, big endian */ @NativeType("unsigned char[4]") public ByteBuffer digest() { return ndigest(address()); } /** hash bytes, big endian */ @NativeType("unsigned char") public byte digest(int index) { return ndigest(address(), index); } // ----------------------------------- /** Returns a new {@code XXH32Canonical} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static XXH32Canonical malloc() { return wrap(XXH32Canonical.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code XXH32Canonical} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static XXH32Canonical calloc() { return wrap(XXH32Canonical.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code XXH32Canonical} instance allocated with {@link BufferUtils}. */ public static XXH32Canonical create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(XXH32Canonical.class, memAddress(container), container); } /** Returns a new {@code XXH32Canonical} instance for the specified memory address. */ public static XXH32Canonical create(long address) { return wrap(XXH32Canonical.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static XXH32Canonical createSafe(long address) { return address == NULL ? null : wrap(XXH32Canonical.class, address); } /** * Returns a new {@link XXH32Canonical.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static XXH32Canonical.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link XXH32Canonical.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static XXH32Canonical.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link XXH32Canonical.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static XXH32Canonical.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link XXH32Canonical.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static XXH32Canonical.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static XXH32Canonical.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static XXH32Canonical mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static XXH32Canonical callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static XXH32Canonical mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static XXH32Canonical callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static XXH32Canonical.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static XXH32Canonical.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static XXH32Canonical.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static XXH32Canonical.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code XXH32Canonical} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static XXH32Canonical malloc(MemoryStack stack) { return wrap(XXH32Canonical.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code XXH32Canonical} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static XXH32Canonical calloc(MemoryStack stack) { return wrap(XXH32Canonical.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link XXH32Canonical.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static XXH32Canonical.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link XXH32Canonical.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static XXH32Canonical.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #digest}. */ public static ByteBuffer ndigest(long struct) { return memByteBuffer(struct + XXH32Canonical.DIGEST, 4); } /** Unsafe version of {@link #digest(int) digest}. */ public static byte ndigest(long struct, int index) { return UNSAFE.getByte(null, struct + XXH32Canonical.DIGEST + check(index, 4) * 1); } // ----------------------------------- /** An array of {@link XXH32Canonical} structs. */ public static class Buffer extends StructBuffer<XXH32Canonical, Buffer> implements NativeResource { private static final XXH32Canonical ELEMENT_FACTORY = XXH32Canonical.create(-1L); /** * Creates a new {@code XXH32Canonical.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link XXH32Canonical#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected XXH32Canonical getElementFactory() { return ELEMENT_FACTORY; } /** @return a {@link ByteBuffer} view of the {@link XXH32Canonical#digest} field. */ @NativeType("unsigned char[4]") public ByteBuffer digest() { return XXH32Canonical.ndigest(address()); } /** @return the value at the specified index of the {@link XXH32Canonical#digest} field. */ @NativeType("unsigned char") public byte digest(int index) { return XXH32Canonical.ndigest(address(), index); } } }
bsd-3-clause
ravikumar10/genyris
src/org/genyris/task/SleepFunction.java
1055
// Copyright 2009 Peter William Birch <birchb@genyis.org> // // This software may be used and distributed according to the terms // of the Genyris License, in the file "LICENSE", incorporated herein by reference. // package org.genyris.task; import org.genyris.core.Bignum; import org.genyris.core.Exp; import org.genyris.exception.GenyrisException; import org.genyris.exception.GenyrisInterruptedException; import org.genyris.interp.Closure; import org.genyris.interp.Environment; import org.genyris.interp.Interpreter; public class SleepFunction extends TaskFunction { public SleepFunction(Interpreter interp) { super(interp, "sleep", true); } public Exp bindAndExecute(Closure proc, Exp[] arguments, Environment envForBindOperations) throws GenyrisException { checkArguments(arguments, 1); try { Thread.sleep(((Bignum)arguments[0]).bigDecimalValue().longValue()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new GenyrisInterruptedException(e.getMessage()); } return NIL; } }
bsd-3-clause
majianxiong/maera
osgi/events/src/main/java/org/maera/plugin/osgi/event/PluginServiceDependencyWaitEvent.java
589
package org.maera.plugin.osgi.event; import org.osgi.framework.Filter; /** * Events that are fired when OSGi services are waiting to be resolved. * * @since 0.1 */ public interface PluginServiceDependencyWaitEvent { /** * @return the filter used for the resolution. May be null. */ Filter getFilter(); /** * @return the Spring bean name for the service reference. May be null. */ String getBeanName(); /** * @return the key for the plugin waiting for the dependency. May be null if unknown. */ String getPluginKey(); }
bsd-3-clause
standevgd/gooddata-java
src/test/java/com/gooddata/dataset/TaskStateTest.java
1141
/* * Copyright (C) 2004-2017, GoodData(R) Corporation. All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE.txt file in the root directory of this source tree. */ package com.gooddata.dataset; import org.testng.annotations.Test; import java.io.IOException; import static com.gooddata.util.ResourceUtils.readObjectFromResource; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.text.MatchesPattern.matchesPattern; public class TaskStateTest { @Test public void testDeserialize() throws IOException { TaskState taskState = readObjectFromResource("/dataset/taskStateOK.json", TaskState.class); assertThat(taskState.getStatus(), is("OK")); assertThat(taskState.getMessage(), is("ok message")); } @Test public void testToStringFormat() throws Exception { TaskState taskState = readObjectFromResource("/dataset/taskStateOK.json", TaskState.class); assertThat(taskState.toString(), matchesPattern(TaskState.class.getSimpleName() + "\\[.*\\]")); } }
bsd-3-clause
nddrylliog/ooc-legacy
legacy-src/org/ooc/parsers/VariableAccessParser.java
1235
package org.ooc.parsers; import java.io.IOException; import org.ooc.errors.SourceContext; import org.ooc.nodes.clazz.ClassDef; import org.ooc.nodes.control.Scope; import org.ooc.nodes.others.Name; import org.ooc.structures.Variable; import org.ubi.FileLocation; import org.ubi.SourceReader; /** * Represents access to a variable. The variable must have been * declared before, e.g. * * @author Amos Wenger */ public class VariableAccessParser implements Parser { public boolean parse(SourceContext context) throws IOException { SourceReader reader = context.reader; boolean result = false; FileLocation location = reader.getLocation(); String name = reader.readName(); ClassDef classDef = context.getNearest(ClassDef.class); reader.skipWhitespace(); if(classDef != null) { Variable member = classDef.getMember(context, name); if(member != null) { context.add(new Name(location, name)); result = true; } } if(!result) { Scope scope = context.getNearest(Scope.class); if(scope != null) { Variable variable = scope.getVariable(name); if(variable != null) { context.add(new Name(location, name)); result = true; } } } return result; } }
bsd-3-clause
anildahiya/sdl_android
base/src/main/java/com/smartdevicelink/proxy/rpc/SendLocation.java
8038
/* * Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the SmartDeviceLink Consortium, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.smartdevicelink.proxy.rpc; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.proxy.RPCRequest; import com.smartdevicelink.proxy.rpc.enums.DeliveryMode; import com.smartdevicelink.util.SdlDataTypeConverter; import java.util.Hashtable; import java.util.List; /** * Sends a location to the head-unit to display on a map or list. * * @since SmartDeviceLink 3.0 * */ public class SendLocation extends RPCRequest{ public static final String KEY_LAT_DEGREES = "latitudeDegrees"; public static final String KEY_LON_DEGREES = "longitudeDegrees"; public static final String KEY_LOCATION_NAME = "locationName"; public static final String KEY_LOCATION_DESCRIPTION = "locationDescription"; public static final String KEY_PHONE_NUMBER = "phoneNumber"; public static final String KEY_ADDRESS_LINES = "addressLines"; public static final String KEY_LOCATION_IMAGE = "locationImage"; public static final String KEY_DELIVERY_MODE = "deliveryMode"; public static final String KEY_TIME_STAMP = "timeStamp"; public static final String KEY_ADDRESS = "address"; /** * Constructs a new SendLocation object */ public SendLocation(){ super(FunctionID.SEND_LOCATION.toString()); } /** * <p> * Constructs a new SendLocation object indicated by the Hashtable parameter * </p> * * @param hash * The Hashtable to use */ public SendLocation(Hashtable<String, Object> hash){ super(hash); } /** * Getter for longitude of the location to send. * * <p><b>IMPORTANT NOTE:</b> </p><p>A previous version of this method call returned a Float * value, however, it has been changed to return a Double.</p> This will compile, * but cause a ClassCastException if your value is not also a Double type. * @since SmartDeviceLink v4.0 * * @return The longitude of the location */ public Double getLongitudeDegrees(){ Object value = getParameters(KEY_LON_DEGREES); return SdlDataTypeConverter.objectToDouble(value); } /** * Setter for longitude of the location to send. * @param longitudeDegrees degrees of the longitudinal position */ public void setLongitudeDegrees(Double longitudeDegrees){ setParameters(KEY_LON_DEGREES, longitudeDegrees); } /** * Getter for latitude of the location to send. * * <p><b>IMPORTANT NOTE:</b> </p><p>A previous version of this method call returned a Float * value, however, it has been changed to return a Double.</p> This will compile, * but cause a ClassCastException if your value is not also a Double type. * @since SmartDeviceLink v4.0 * * @return The latitude of the location */ public Double getLatitudeDegrees(){ Object value = getParameters(KEY_LAT_DEGREES); return SdlDataTypeConverter.objectToDouble(value); } /** * Setter for latitude of the location to send. * @param latitudeDegrees degrees of the latitudinal position */ public void setLatitudeDegrees(Double latitudeDegrees){ setParameters(KEY_LAT_DEGREES, latitudeDegrees); } /** * Getter for name of the location to send. * @return The name of the location */ public String getLocationName(){ return getString(KEY_LOCATION_NAME); } /** * Setter for name of the location to send. * @param locationName The name of the location */ public void setLocationName(String locationName){ setParameters(KEY_LOCATION_NAME, locationName); } /** * Getter for description of the location to send. * @return The description of the location to send */ public String getLocationDescription(){ return getString(KEY_LOCATION_DESCRIPTION); } /** * Setter for description of the location to send. * @param locationDescription The description of the location */ public void setLocationDescription(String locationDescription){ setParameters(KEY_LOCATION_DESCRIPTION, locationDescription); } /** * Getter for phone number of the location to send. * @return */ public String getPhoneNumber(){ return getString(KEY_PHONE_NUMBER); } /** * Setter for phone number of the location to send. * @param phoneNumber The phone number of the location */ public void setPhoneNumber(String phoneNumber){ setParameters(KEY_PHONE_NUMBER, phoneNumber); } /** * Getter for address lines of the location to send. * @return The address lines of the location */ @SuppressWarnings("unchecked") public List<String> getAddressLines(){ return (List<String>) getObject(String.class, KEY_ADDRESS_LINES); } /** * Setter for address lines of the location to send. * @param addressLines The address lines of the location */ public void setAddressLines(List<String> addressLines){ setParameters(KEY_ADDRESS_LINES, addressLines); } /** * Getter for image of the location to send. * @return The image of the location to send */ @SuppressWarnings("unchecked") public Image getLocationImage(){ return (Image) getObject(Image.class, KEY_LOCATION_IMAGE); } /** * Setter for image of the location to send. * @param locationImage The image of the location to send */ public void setLocationImage(Image locationImage){ setParameters(KEY_LOCATION_IMAGE, locationImage); } public DeliveryMode getDeliveryMode() { return (DeliveryMode) getObject(DeliveryMode.class, KEY_DELIVERY_MODE); } public void setDeliveryMode(DeliveryMode deliveryMode) { setParameters(KEY_DELIVERY_MODE, deliveryMode); } @SuppressWarnings("unchecked") public DateTime getTimeStamp() { return (DateTime) getObject(DateTime.class, KEY_TIME_STAMP); } public void setTimeStamp(DateTime timeStamp) { setParameters(KEY_TIME_STAMP, timeStamp); } @SuppressWarnings("unchecked") public OasisAddress getAddress() { return (OasisAddress) getObject(OasisAddress.class, KEY_ADDRESS); } public void setAddress(OasisAddress address) { setParameters(KEY_ADDRESS, address); } }
bsd-3-clause
ZenHarbinger/RSTALanguageSupport
src/main/java/org/fife/rsta/ac/js/ecma/api/e4x/E4XXMLList.java
1306
package org.fife.rsta.ac.js.ecma.api.e4x; import org.fife.rsta.ac.js.ecma.api.e4x.functions.E4XXMLListFunctions; import org.fife.rsta.ac.js.ecma.api.ecma3.JSFunction; import org.fife.rsta.ac.js.ecma.api.ecma3.JSObject; /** * Object XMLList * * @since Standard ECMA-357 2nd. Edition */ public abstract class E4XXMLList implements E4XXMLListFunctions { /** * Object E4XXMLList(xml) * * @constructor * @param xml The XML definition * @extends Object * @since Standard ECMA-357 2nd. Edition * @since Level 3 Document Object Model Core Definition. */ public E4XXMLList ( JSObject xml ){} /** * <b>property prototype</b> * * @type XMLList * @memberOf XMLList * @see org.fife.rsta.ac.js.ecma.api.e4x.E4XXMLList XMLList * @since Standard ECMA-357 2nd. Edition * @since Level 3 Document Object Model Core Definition. */ public E4XXMLList protype; /** * <b>property constructor</b> * * @type Function * @memberOf XMLList * @see org.fife.rsta.ac.js.ecma.api.e4x.E4XXMLList XML * @since Standard ECMA-357 2nd. Edition * @since Level 3 Document Object Model Core Definition. */ protected JSFunction constructor; }
bsd-3-clause
patrickianwilson/vijava-contrib
src/main/java/com/vmware/vim25/ArrayOfHostFeatureCapability.java
2218
/*================================================================================ Copyright (c) 2013 Steve Jin. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ public class ArrayOfHostFeatureCapability { public HostFeatureCapability[] HostFeatureCapability; public HostFeatureCapability[] getHostFeatureCapability() { return this.HostFeatureCapability; } public HostFeatureCapability getHostFeatureCapability(int i) { return this.HostFeatureCapability[i]; } public void setHostFeatureCapability(HostFeatureCapability[] HostFeatureCapability) { this.HostFeatureCapability=HostFeatureCapability; } }
bsd-3-clause
standevgd/gooddata-java
src/test/java/com/gooddata/gdc/UriResponseTest.java
1121
/* * Copyright (C) 2004-2017, GoodData(R) Corporation. All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE.txt file in the root directory of this source tree. */ package com.gooddata.gdc; import org.testng.annotations.Test; import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; import static net.javacrumbs.jsonunit.core.util.ResourceUtils.resource; import static com.gooddata.util.ResourceUtils.readObjectFromResource; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; public class UriResponseTest { @Test public void testDeserialization() throws Exception { final UriResponse uriResponse = readObjectFromResource("/gdc/uriResponse.json", UriResponse.class); assertThat(uriResponse, is(notNullValue())); assertThat(uriResponse.getUri(), is("URI")); } @Test public void testSerialization() throws Exception { assertThat(new UriResponse("URI"), jsonEquals(resource("gdc/uriResponse.json"))); } }
bsd-3-clause
tobiasstamann/contextlogger
agent/agent/src/main/java/io/tracee/contextlogger/agent/ContextloggerInterceptor.java
1421
package io.tracee.contextlogger.agent; import io.tracee.contextlogger.MessagePrefixProvider; import io.tracee.contextlogger.TraceeContextLogger; import io.tracee.contextlogger.connector.LogLevel; import io.tracee.contextlogger.contextprovider.agent.AgentDataWrapper; import io.tracee.contextlogger.contextprovider.core.CoreImplicitContextProviders; import lombok.extern.slf4j.Slf4j; import net.bytebuddy.implementation.bind.annotation.AllArguments; import net.bytebuddy.implementation.bind.annotation.Origin; import net.bytebuddy.implementation.bind.annotation.RuntimeType; import net.bytebuddy.implementation.bind.annotation.SuperCall; import java.lang.reflect.Method; import java.util.concurrent.Callable; @Slf4j public class ContextloggerInterceptor { @RuntimeType public static Object intercept(@Origin Class calledClass, @Origin Method calledMethod, @SuperCall Callable<?> interceptedCall, @AllArguments Object... args) throws Exception { try { TraceeContextLogger .create() .enforceOrder() .apply() .logWithPrefixedMessage(LogLevel.INFO, MessagePrefixProvider.provideLogMessagePrefix(LogLevel.INFO, ContextloggerInterceptor.class), CoreImplicitContextProviders.COMMON, CoreImplicitContextProviders.TRACEE, AgentDataWrapper.wrap(calledClass, calledMethod, args)); return interceptedCall.call(); } catch (Exception e) { // rethrow exception throw e; } } }
bsd-3-clause
luminousfennell/jgs
DynamicAnalyzer/testing_external/src/main/java/testclasses/NSUPolicy2.java
773
package testclasses; import util.analyzer.HelperClass; import util.test.C; /** * Working example from readme. Since two exceptions are to be thrown, also see NSUPolicy3 * @author Nicolas Müller * */ public class NSUPolicy2 { public static void main(String[] args) { C o1 = new C(); C o2 = new C(); o1.f = true; o2.f = false; // o1, o2, o1.f and o2.f are all LOW boolean secret = HelperClass.makeHigh(true); C o; if (secret) { o = o1; } else { o = o2; } // o is high. // o1, o2, o1.f and o2.f are still LOW System.out.println(o1.f); // Okay System.out.println(o.f); // Not okay! Leaks information! o1.f = false; // Okay // o.f = true; // Not okay! NSU IFCError -> Test online in NSUPolicy3 } }
bsd-3-clause
kjniemi/nginx-clojure
example-projects/spring-core-example/src/main/java/nginx/clojure/spring/core/example/SpringApplicationContextAware.java
999
package nginx.clojure.spring.core.example; import java.util.concurrent.CountDownLatch; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringApplicationContextAware implements ApplicationContextAware { private static ApplicationContext applicationContext; private static CountDownLatch countDownLatch = new CountDownLatch(1); public static ApplicationContext getApplicationContext() { try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException("SpringApplicationContextAware countDownLatch interrupted error", e); } return applicationContext; } public SpringApplicationContextAware() { } @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { applicationContext = ctx; countDownLatch.countDown(); } }
bsd-3-clause
abayer/github-pullrequest-plugin
src/main/java/org/jenkinsci/plugins/github/pullrequest/events/impl/GitHubPRNonMergeableEvent.java
2244
package org.jenkinsci.plugins.github.pullrequest.events.impl; import hudson.Extension; import hudson.model.TaskListener; import org.jenkinsci.plugins.github.pullrequest.GitHubPRCause; import org.jenkinsci.plugins.github.pullrequest.GitHubPRPullRequest; import org.jenkinsci.plugins.github.pullrequest.GitHubPRTrigger; import org.jenkinsci.plugins.github.pullrequest.events.GitHubPREvent; import org.jenkinsci.plugins.github.pullrequest.events.GitHubPREventDescriptor; import org.kohsuke.github.GHPullRequest; import org.kohsuke.stapler.DataBoundConstructor; import javax.annotation.CheckForNull; import java.io.IOException; import java.io.PrintStream; import java.util.logging.Level; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Event to skip PRs that can't be merged. * * @author Alina Karpovich */ public class GitHubPRNonMergeableEvent extends GitHubPREvent { private static final String DISPLAY_NAME = "Not mergeable"; private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRNonMergeableEvent.class); private boolean skip = true; @DataBoundConstructor public GitHubPRNonMergeableEvent(boolean skip) { this.skip = skip; } @Override public GitHubPRCause check(GitHubPRTrigger gitHubPRTrigger, GHPullRequest remotePR, @CheckForNull GitHubPRPullRequest localPR, TaskListener listener) throws IOException { final PrintStream logger = listener.getLogger(); Boolean mergeable; try { mergeable = remotePR.getMergeable(); } catch (IOException e) { logger.println(DISPLAY_NAME + ": can't get mergeable status"); LOGGER.warn("Can't get mergeable status: {}", e.getMessage()); mergeable = false; } mergeable = mergeable != null ? mergeable : false; if (!mergeable) { return new GitHubPRCause(remotePR, DISPLAY_NAME, isSkip()); } return null; } public boolean isSkip() { return skip; } @Extension public static class DescriptorImpl extends GitHubPREventDescriptor { @Override public String getDisplayName() { return DISPLAY_NAME; } } }
mit
iface06/journeyOptimizer
src/test/java/de/as/roadRunners/app/journeyCommands/CalculateJourneyCommandTest.java
1446
package de.as.roadRunners.app.journeyCommands; import de.as.roadRunners.app.entities.Journey; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; public class CalculateJourneyCommandTest { private JourneyOptimizationContext context; @Test public void successfulCalculation() { CalculateJourneyCommand interactor = new CalculateJourneyCommand(context); interactor.setPlaner(new JourneyOptimizer(context.getOriginalJourney()) { @Override public Journey apply() { return new Journey(); } }); interactor.execute(); } @Test(expected = RuntimeException.class) public void notSuccessfulCalculation() { CalculateJourneyCommand interactor = new CalculateJourneyCommand(context); interactor.setPlaner(new JourneyOptimizer(context.getOriginalJourney()) { @Override public Journey apply() { throw new RuntimeException("Something goes wrong!"); } }); interactor.execute(); } @Before public void before() { context = createContext(); } private JourneyOptimizationContext createContext() { final Journey journeyForOptimiziation = new Journey(); JourneyOptimizationContext ctx = new JourneyOptimizationContext(journeyForOptimiziation); return ctx; } }
mit
jvillard/infer
infer/tests/codetoanalyze/java/starvation-whole-program/ConstructedAttributes.java
1518
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import android.os.Binder; import android.os.Handler; import android.os.Looper; import android.os.RemoteException; import java.util.concurrent.Executor; class ConstructedAttributes { static Binder binder; private static void doTransact() { try { binder.transact(0, null, null, 0); } catch (RemoteException e) { } } @ForUiThread private final Executor mUiThreadExecutor = null; Executor mUiExecutor; Executor mNonUiExecutor; Handler mUiHandler; Runnable mBadRunnable; Runnable mOkRunnable; ConstructedAttributes() { mUiExecutor = mUiThreadExecutor; mNonUiExecutor = Executors.getBackgroundExecutor(); mUiHandler = new Handler(Looper.getMainLooper()); mBadRunnable = new Runnable() { @Override public void run() { doTransact(); } }; mOkRunnable = new Runnable() { @Override public void run() {} }; } public void postBlockingCallToUIExecutorBad() { mUiExecutor.execute(mBadRunnable); } public void postNoopCallToUIExecutorOk() { mUiExecutor.execute(mOkRunnable); } public void postBlockingCallToNonUIExecutorOk() { mNonUiExecutor.execute(mBadRunnable); } public void postBlockingCallToUIHandlerBad() { mUiHandler.post(mBadRunnable); } }
mit
0x90sled/droidtowers
tools/proguard/src/proguard/classfile/attribute/annotation/visitor/AnnotatedClassVisitor.java
1923
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2011 Eric Lafortune (eric@graphics.cornell.edu) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile.attribute.annotation.visitor; import proguard.classfile.Clazz; import proguard.classfile.attribute.annotation.Annotation; import proguard.classfile.util.SimplifiedVisitor; import proguard.classfile.visitor.ClassVisitor; /** * This AnnotationVisitor delegates all visits to a given ClassVisitor. * The latter visits the class of each visited annotation, although * never twice in a row. * * @author Eric Lafortune */ public class AnnotatedClassVisitor extends SimplifiedVisitor implements AnnotationVisitor { private final ClassVisitor classVisitor; private Clazz lastVisitedClass; public AnnotatedClassVisitor(ClassVisitor classVisitor) { this.classVisitor = classVisitor; } // Implementations for AnnotationVisitor. public void visitAnnotation(Clazz clazz, Annotation annotation) { if (!clazz.equals(lastVisitedClass)) { clazz.accept(classVisitor); lastVisitedClass = clazz; } } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/FunctionAppBasicImpl.java
1239
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.appservice.implementation; import com.azure.resourcemanager.appservice.AppServiceManager; import com.azure.resourcemanager.appservice.fluent.models.SiteInner; import com.azure.resourcemanager.appservice.models.FunctionApp; import com.azure.resourcemanager.appservice.models.FunctionAppBasic; import com.azure.resourcemanager.resources.fluentcore.arm.models.HasManager; import reactor.core.publisher.Mono; class FunctionAppBasicImpl extends WebSiteBaseImpl implements FunctionAppBasic, HasManager<AppServiceManager> { private final AppServiceManager myManager; FunctionAppBasicImpl(SiteInner innerObject, AppServiceManager myManager) { super(innerObject); this.myManager = myManager; } @Override public FunctionApp refresh() { return this.refreshAsync().block(); } @Override public Mono<FunctionApp> refreshAsync() { return this.manager().functionApps().getByIdAsync(this.id()) .doOnNext(site -> this.setInner(site.innerModel())); } @Override public AppServiceManager manager() { return myManager; } }
mit
Kiskae/SpongeAPI
src/main/java/org/spongepowered/api/data/type/CookedFish.java
1674
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.type; import org.spongepowered.api.CatalogType; import org.spongepowered.api.util.annotation.CatalogedBy; /** * Represents a type of cooked fish. */ @CatalogedBy(CookedFishes.class) public interface CookedFish extends CatalogType { /** * Gets this cooked fish type's corresponding {@link Fish} type. * * @return The raw fish type. */ Fish getRawFish(); }
mit
Weisses/Ebonheart-Mods
Viesis' Gemstones/1.12.2 - 2555/src/main/java/com/viesis/gemstones/common/utils/damagesources/EntityDamageSourceElectric.java
1907
package com.viesis.gemstones.common.utils.damagesources; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.EntityDamageSourceIndirect; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.util.text.translation.I18n; public class EntityDamageSourceElectric extends EntityDamageSourceIndirect { private final Entity indirectEntity; public EntityDamageSourceElectric(String damageTypeIn, Entity source, Entity indirectEntityIn) { super(damageTypeIn, source, indirectEntityIn); this.setDamageBypassesArmor(); this.indirectEntity = indirectEntityIn; } public Entity getSourceOfDamage() { return this.damageSourceEntity; } public Entity getEntity() { return this.indirectEntity; } public ITextComponent getDeathMessage(EntityLivingBase entityLivingBaseIn) { ITextComponent itextcomponent = this.indirectEntity == null ? this.damageSourceEntity.getDisplayName() : this.indirectEntity.getDisplayName(); ItemStack itemstack = this.indirectEntity instanceof EntityLivingBase ? ((EntityLivingBase)this.indirectEntity).getHeldItemMainhand() : null; String s = "death.attack." + this.damageType; String s1 = s + ".item"; return itemstack != null && itemstack.hasDisplayName() && I18n.canTranslate(s1) ? new TextComponentTranslation(s1, new Object[] {entityLivingBaseIn.getDisplayName(), itextcomponent, itemstack.getTextComponent()}): new TextComponentTranslation(s, new Object[] {entityLivingBaseIn.getDisplayName(), itextcomponent}); } public static EntityDamageSourceElectric causeElectricDamage(Entity source, Entity transmitter) { return new EntityDamageSourceElectric("electric.entity", transmitter, source); } }
mit
Safewhere/kombit-web-java
kombit-opensaml-2.5.1/src/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0001.java
4655
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID 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.opensaml.saml1.binding.artifact; import java.util.Arrays; /** * SAML 1.X Type 0x0001 Artifact. SAML 1, type 1, artifacts contains a 2 byte type code with a value of 1 followed by a * 20 byte source ID followed by a 20 byte assertion handle. */ public class SAML1ArtifactType0001 extends AbstractSAML1Artifact { /** Artifact type code (0x0001). */ public static final byte[] TYPE_CODE = { 0, 1 }; /** 20 byte artifact source ID. */ private byte[] sourceID; /** 20 byte assertion handle. */ private byte[] assertionHandle; /** Constructor. */ public SAML1ArtifactType0001() { super(TYPE_CODE); } /** * Constructor. * * @param source 20 byte source ID of the artifact * @param handle 20 byte assertion handle of the artifact * * @throws IllegalArgumentException thrown if the given source ID or message handle are not of the current length * (20 bytes) */ public SAML1ArtifactType0001(byte[] source, byte[] handle) { super(TYPE_CODE); setSourceID(source); setAssertionHandle(handle); } /** * Constructs a SAML 1 artifact from its byte array representation. * * @param artifact the byte array representing the artifact * * @return the artifact created from the byte array * * @throws IllegalArgumentException thrown if the artifact is not the right type or lenght (42 bytes) or is not of * the correct type (0x0001) */ public static SAML1ArtifactType0001 parseArtifact(byte[] artifact) { if (artifact.length != 42) { throw new IllegalArgumentException("Artifact length must be 42 bytes it was " + artifact.length + "bytes"); } byte[] typeCode = { artifact[0], artifact[1] }; if (!Arrays.equals(typeCode, TYPE_CODE)) { throw new IllegalArgumentException("Artifact is not of appropriate type."); } byte[] sourceID = new byte[20]; System.arraycopy(artifact, 2, sourceID, 0, 20); byte[] assertionHandle = new byte[20]; System.arraycopy(artifact, 22, assertionHandle, 0, 20); return new SAML1ArtifactType0001(sourceID, assertionHandle); } /** * Gets the 20 byte source ID of the artifact. * * @return the source ID of the artifact */ public byte[] getSourceID() { return sourceID; } /** * Sets the 20 byte source ID of the artifact. * * @param newSourceID 20 byte source ID of the artifact * * @throws IllegalArgumentException thrown if the given source ID is not 20 bytes */ protected void setSourceID(byte[] newSourceID) { if (newSourceID.length != 20) { throw new IllegalArgumentException("Artifact source ID must be 20 bytes long"); } sourceID = newSourceID; } /** * Gets the artifiact's 20 byte assertion handle. * * @return artifiact's 20 byte assertion handle */ public byte[] getAssertionHandle() { return assertionHandle; } /** * Sets the artifiact's 20 byte assertion handle. * * @param handle artifiact's 20 byte assertion handle */ public void setAssertionHandle(byte[] handle) { if (handle.length != 20) { throw new IllegalArgumentException("Artifact assertion handle must be 20 bytes long"); } assertionHandle = handle; } /** {@inheritDoc} */ public byte[] getRemainingArtifact() { byte[] remainingArtifact = new byte[40]; System.arraycopy(getSourceID(), 0, remainingArtifact, 0, 20); System.arraycopy(getAssertionHandle(), 0, remainingArtifact, 20, 20); return remainingArtifact; } }
mit
selvasingh/azure-sdk-for-java
sdk/servicebus/microsoft-azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientSettings.java
3417
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.servicebus; import java.time.Duration; import com.microsoft.azure.servicebus.primitives.ClientConstants; import com.microsoft.azure.servicebus.primitives.RetryPolicy; import com.microsoft.azure.servicebus.primitives.TransportType; import com.microsoft.azure.servicebus.security.TokenProvider; /** * Class encapsulating common client level settings like TokenProvider, RetryPolicy, OperationTimeout. * @since 1.2.0 * */ public class ClientSettings { private TokenProvider tokenProvider; private RetryPolicy retryPolicy; private Duration operationTimeout; private TransportType transportType; /** * Creates a new instance with the given token provider, default retry policy and default operation timeout. * @param tokenProvider {@link TokenProvider} instance * * @see RetryPolicy#getDefault() */ public ClientSettings(TokenProvider tokenProvider) { this(tokenProvider, RetryPolicy.getDefault(), Duration.ofSeconds(ClientConstants.DEFAULT_OPERATION_TIMEOUT_IN_SECONDS), TransportType.AMQP); } /** * Creates a new instance with the given token provider, retry policy and operation timeout. * @param tokenProvider {@link TokenProvider} instance * @param retryPolicy {@link RetryPolicy} instance * @param operationTimeout default operation timeout to be used for all client operations. Client can override this value by explicitly specifying a timeout in the operation. */ public ClientSettings(TokenProvider tokenProvider, RetryPolicy retryPolicy, Duration operationTimeout) { this(tokenProvider, retryPolicy, operationTimeout, TransportType.AMQP); } /** * Creates a new instance with the given token provider, retry policy and operation timeout. * @param tokenProvider {@link TokenProvider} instance * @param retryPolicy {@link RetryPolicy} instance * @param operationTimeout default operation timeout to be used for all client operations. Client can override this value by explicitly specifying a timeout in the operation. * @param transportType {@link TransportType} instance */ public ClientSettings(TokenProvider tokenProvider, RetryPolicy retryPolicy, Duration operationTimeout, TransportType transportType) { this.tokenProvider = tokenProvider; this.retryPolicy = retryPolicy; this.operationTimeout = operationTimeout; this.transportType = transportType; } /** * Gets the token provider contained in this instance. * @return TokenProvider contained in this instance */ public TokenProvider getTokenProvider() { return tokenProvider; } /** * Gets the retry policy contained in this instance. * @return RetryPolicy contained in this instance */ public RetryPolicy getRetryPolicy() { return retryPolicy; } /** * Gets the operation timeout contained in this instance. * @return operation timeout contained in this instance */ public Duration getOperationTimeout() { return operationTimeout; } /** * Gets the transport type for this instance * @return transport type for the instance */ public TransportType getTransportType() { return transportType; } }
mit
Skywalker-11/spongycastle
pkix/src/test/jdk1.3/org/spongycastle/cert/test/BcCertTest.java
65802
package org.spongycastle.cert.test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.SecureRandom; import java.security.cert.CRL; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import junit.framework.TestCase; import org.spongycastle.asn1.ASN1EncodableVector; import org.spongycastle.asn1.ASN1Enumerated; import org.spongycastle.asn1.ASN1Object; import org.spongycastle.asn1.ASN1ObjectIdentifier; import org.spongycastle.asn1.DERBitString; import org.spongycastle.asn1.DERSequence; import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.spongycastle.asn1.x500.X500Name; import org.spongycastle.asn1.x500.X500NameBuilder; import org.spongycastle.asn1.x500.style.RFC4519Style; import org.spongycastle.asn1.x509.AlgorithmIdentifier; import org.spongycastle.asn1.x509.AuthorityKeyIdentifier; import org.spongycastle.asn1.x509.CRLReason; import org.spongycastle.asn1.x509.Certificate; import org.spongycastle.asn1.x509.Extension; import org.spongycastle.asn1.x509.Extensions; import org.spongycastle.asn1.x509.ExtensionsGenerator; import org.spongycastle.asn1.x509.GeneralName; import org.spongycastle.asn1.x509.GeneralNames; import org.spongycastle.asn1.x509.KeyPurposeId; import org.spongycastle.asn1.x509.KeyUsage; import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; import org.spongycastle.cert.CertException; import org.spongycastle.cert.X509CRLEntryHolder; import org.spongycastle.cert.X509CRLHolder; import org.spongycastle.cert.X509CertificateHolder; import org.spongycastle.cert.X509v1CertificateBuilder; import org.spongycastle.cert.X509v2CRLBuilder; import org.spongycastle.cert.X509v3CertificateBuilder; import org.spongycastle.cert.bc.BcX509ExtensionUtils; import org.spongycastle.cert.bc.BcX509v1CertificateBuilder; import org.spongycastle.cert.bc.BcX509v3CertificateBuilder; import org.spongycastle.cert.jcajce.JcaX509CertificateConverter; import org.spongycastle.crypto.AsymmetricCipherKeyPair; import org.spongycastle.crypto.AsymmetricCipherKeyPairGenerator; import org.spongycastle.crypto.generators.DSAKeyPairGenerator; import org.spongycastle.crypto.generators.DSAParametersGenerator; import org.spongycastle.crypto.generators.RSAKeyPairGenerator; import org.spongycastle.crypto.params.AsymmetricKeyParameter; import org.spongycastle.crypto.params.DSAKeyGenerationParameters; import org.spongycastle.crypto.params.DSAParameters; import org.spongycastle.crypto.params.RSAKeyGenerationParameters; import org.spongycastle.crypto.params.RSAKeyParameters; import org.spongycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.spongycastle.crypto.util.PublicKeyFactory; import org.spongycastle.crypto.util.SubjectPublicKeyInfoFactory; import org.spongycastle.cert.test.PEMData; import org.spongycastle.operator.ContentSigner; import org.spongycastle.operator.ContentVerifierProvider; import org.spongycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.spongycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; import org.spongycastle.operator.OperatorCreationException; import org.spongycastle.operator.bc.BcDSAContentSignerBuilder; import org.spongycastle.operator.bc.BcDSAContentVerifierProviderBuilder; import org.spongycastle.operator.bc.BcRSAContentSignerBuilder; import org.spongycastle.operator.bc.BcRSAContentVerifierProviderBuilder; import org.spongycastle.util.Strings; import org.spongycastle.util.encoders.Base64; public class BcCertTest extends TestCase { DefaultSignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder(); DefaultDigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); // // server.crt // byte[] cert1 = Base64.decode( "MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU2MjFaFw0wMTA2" + "MDIwNzU2MjFaMIG4MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxFzAVBgNVBAsTDldlYnNlcnZlciBUZWFtMR0wGwYDVQQDExR3d3cyLmNvbm5l" + "Y3Q0LmNvbS5hdTEoMCYGCSqGSIb3DQEJARYZd2VibWFzdGVyQGNvbm5lY3Q0LmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArvDxclKAhyv7Q/Wmr2re" + "Gw4XL9Cnh9e+6VgWy2AWNy/MVeXdlxzd7QAuc1eOWQkGQEiLPy5XQtTY+sBUJ3AO" + "Rvd2fEVJIcjf29ey7bYua9J/vz5MG2KYo9/WCHIwqD9mmG9g0xLcfwq/s8ZJBswE" + "7sb85VU+h94PTvsWOsWuKaECAwEAAaN3MHUwJAYDVR0RBB0wG4EZd2VibWFzdGVy" + "QGNvbm5lY3Q0LmNvbS5hdTA6BglghkgBhvhCAQ0ELRYrbW9kX3NzbCBnZW5lcmF0" + "ZWQgY3VzdG9tIHNlcnZlciBjZXJ0aWZpY2F0ZTARBglghkgBhvhCAQEEBAMCBkAw" + "DQYJKoZIhvcNAQEEBQADgYEAotccfKpwSsIxM1Hae8DR7M/Rw8dg/RqOWx45HNVL" + "iBS4/3N/TO195yeQKbfmzbAA2jbPVvIvGgTxPgO1MP4ZgvgRhasaa0qCJCkWvpM4" + "yQf33vOiYQbpv4rTwzU8AmRlBG45WdjyNIigGV+oRc61aKCTnLq7zB8N3z1TF/bF" + "5/8="); // // ca.crt // byte[] cert2 = Base64.decode( "MIIDbDCCAtWgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU1MzNaFw0wMTA2" + "MDIwNzU1MzNaMIG3MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEVMBMGA1UEAxMMQ29u" + "bmVjdCA0IENBMSgwJgYJKoZIhvcNAQkBFhl3ZWJtYXN0ZXJAY29ubmVjdDQuY29t" + "LmF1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgs5ptNG6Qv1ZpCDuUNGmv" + "rhjqMDPd3ri8JzZNRiiFlBA4e6/ReaO1U8ASewDeQMH6i9R6degFdQRLngbuJP0s" + "xcEE+SksEWNvygfzLwV9J/q+TQDyJYK52utb++lS0b48A1KPLwEsyL6kOAgelbur" + "ukwxowprKUIV7Knf1ajetQIDAQABo4GFMIGCMCQGA1UdEQQdMBuBGXdlYm1hc3Rl" + "ckBjb25uZWN0NC5jb20uYXUwDwYDVR0TBAgwBgEB/wIBADA2BglghkgBhvhCAQ0E" + "KRYnbW9kX3NzbCBnZW5lcmF0ZWQgY3VzdG9tIENBIGNlcnRpZmljYXRlMBEGCWCG" + "SAGG+EIBAQQEAwICBDANBgkqhkiG9w0BAQQFAAOBgQCsGvfdghH8pPhlwm1r3pQk" + "msnLAVIBb01EhbXm2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz" + "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ" + "DhkaJ8VqOMajkQFma2r9iA=="); // // testx509.pem // byte[] cert3 = Base64.decode( "MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV" + "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz" + "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM" + "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF" + "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO" + "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE" + "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ" + "zl9HYIMxATFyqSiD9jsx"); // // v3-cert1.pem // byte[] cert4 = Base64.decode( "MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx" + "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz" + "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw" + "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu" + "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2" + "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp" + "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C" + "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK" + "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x" + "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR" + "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB" + "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21" + "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3" + "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO"); // // v3-cert2.pem // byte[] cert5 = Base64.decode( "MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD" + "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0" + "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu" + "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1" + "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV" + "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx" + "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA" + "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT" + "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ" + "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm" + "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc" + "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz" + "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap" + "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU="); // // pem encoded pkcs7 // byte[] cert6 = Base64.decode( "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIJbzCCAj0w" + "ggGmAhEAzbp/VvDf5LxU/iKss3KqVTANBgkqhkiG9w0BAQIFADBfMQswCQYDVQQGEwJVUzEXMBUG" + "A1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGljIFByaW1hcnkgQ2Vy" + "dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTYwMTI5MDAwMDAwWhcNMjgwODAxMjM1OTU5WjBfMQsw" + "CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVi" + "bGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0A" + "MIGJAoGBAOUZv22jVmEtmUhx9mfeuY3rt56GgAqRDvo4Ja9GiILlc6igmyRdDR/MZW4MsNBWhBiH" + "mgabEKFz37RYOWtuwfYV1aioP6oSBo0xrH+wNNePNGeICc0UEeJORVZpH3gCgNrcR5EpuzbJY1zF" + "4Ncth3uhtzKwezC6Ki8xqu6jZ9rbAgMBAAEwDQYJKoZIhvcNAQECBQADgYEATD+4i8Zo3+5DMw5d" + "6abLB4RNejP/khv0Nq3YlSI2aBFsfELM85wuxAc/FLAPT/+Qknb54rxK6Y/NoIAK98Up8YIiXbix" + "3YEjo3slFUYweRb46gVLlH8dwhzI47f0EEA8E8NfH1PoSOSGtHuhNbB7Jbq4046rPzidADQAmPPR" + "cZQwggMuMIICl6ADAgECAhEA0nYujRQMPX2yqCVdr+4NdTANBgkqhkiG9w0BAQIFADBfMQswCQYD" + "VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGlj" + "IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTgwNTEyMDAwMDAwWhcNMDgwNTEy" + "MjM1OTU5WjCBzDEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy" + "dXN0IE5ldHdvcmsxRjBEBgNVBAsTPXd3dy52ZXJpc2lnbi5jb20vcmVwb3NpdG9yeS9SUEEgSW5j" + "b3JwLiBCeSBSZWYuLExJQUIuTFREKGMpOTgxSDBGBgNVBAMTP1ZlcmlTaWduIENsYXNzIDEgQ0Eg" + "SW5kaXZpZHVhbCBTdWJzY3JpYmVyLVBlcnNvbmEgTm90IFZhbGlkYXRlZDCBnzANBgkqhkiG9w0B" + "AQEFAAOBjQAwgYkCgYEAu1pEigQWu1X9A3qKLZRPFXg2uA1Ksm+cVL+86HcqnbnwaLuV2TFBcHqB" + "S7lIE1YtxwjhhEKrwKKSq0RcqkLwgg4C6S/7wju7vsknCl22sDZCM7VuVIhPh0q/Gdr5FegPh7Yc" + "48zGmo5/aiSS4/zgZbqnsX7vyds3ashKyAkG5JkCAwEAAaN8MHowEQYJYIZIAYb4QgEBBAQDAgEG" + "MEcGA1UdIARAMD4wPAYLYIZIAYb4RQEHAQEwLTArBggrBgEFBQcCARYfd3d3LnZlcmlzaWduLmNv" + "bS9yZXBvc2l0b3J5L1JQQTAPBgNVHRMECDAGAQH/AgEAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0B" + "AQIFAAOBgQCIuDc73dqUNwCtqp/hgQFxHpJqbS/28Z3TymQ43BuYDAeGW4UVag+5SYWklfEXfWe0" + "fy0s3ZpCnsM+tI6q5QsG3vJWKvozx74Z11NMw73I4xe1pElCY+zCphcPXVgaSTyQXFWjZSAA/Rgg" + "5V+CprGoksVYasGNAzzrw80FopCubjCCA/gwggNhoAMCAQICEBbbn/1G1zppD6KsP01bwywwDQYJ" + "KoZIhvcNAQEEBQAwgcwxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln" + "biBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3JlcG9zaXRvcnkvUlBB" + "IEluY29ycC4gQnkgUmVmLixMSUFCLkxURChjKTk4MUgwRgYDVQQDEz9WZXJpU2lnbiBDbGFzcyAx" + "IENBIEluZGl2aWR1YWwgU3Vic2NyaWJlci1QZXJzb25hIE5vdCBWYWxpZGF0ZWQwHhcNMDAxMDAy" + "MDAwMDAwWhcNMDAxMjAxMjM1OTU5WjCCAQcxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYD" + "VQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3Jl" + "cG9zaXRvcnkvUlBBIEluY29ycC4gYnkgUmVmLixMSUFCLkxURChjKTk4MR4wHAYDVQQLExVQZXJz" + "b25hIE5vdCBWYWxpZGF0ZWQxJzAlBgNVBAsTHkRpZ2l0YWwgSUQgQ2xhc3MgMSAtIE1pY3Jvc29m" + "dDETMBEGA1UEAxQKRGF2aWQgUnlhbjElMCMGCSqGSIb3DQEJARYWZGF2aWRAbGl2ZW1lZGlhLmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqxBsdeNmSvFqhMNwhQgNzM8mdjX9eSXb" + "DawpHtQHjmh0AKJSa3IwUY0VIsyZHuXWktO/CgaMBVPt6OVf/n0R2sQigMP6Y+PhEiS0vCJBL9aK" + "0+pOo2qXrjVBmq+XuCyPTnc+BOSrU26tJsX0P9BYorwySiEGxGanBNATdVL4NdUCAwEAAaOBnDCB" + "mTAJBgNVHRMEAjAAMEQGA1UdIAQ9MDswOQYLYIZIAYb4RQEHAQgwKjAoBggrBgEFBQcCARYcaHR0" + "cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTARBglghkgBhvhCAQEEBAMCB4AwMwYDVR0fBCwwKjAo" + "oCagJIYiaHR0cDovL2NybC52ZXJpc2lnbi5jb20vY2xhc3MxLmNybDANBgkqhkiG9w0BAQQFAAOB" + "gQBC8yIIdVGpFTf8/YiL14cMzcmL0nIRm4kGR3U59z7UtcXlfNXXJ8MyaeI/BnXwG/gD5OKYqW6R" + "yca9vZOxf1uoTBl82gInk865ED3Tej6msCqFzZffnSUQvOIeqLxxDlqYRQ6PmW2nAnZeyjcnbI5Y" + "syQSM2fmo7n6qJFP+GbFezGCAkUwggJBAgEBMIHhMIHMMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j" + "LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazFGMEQGA1UECxM9d3d3LnZlcmlzaWdu" + "LmNvbS9yZXBvc2l0b3J5L1JQQSBJbmNvcnAuIEJ5IFJlZi4sTElBQi5MVEQoYyk5ODFIMEYGA1UE" + "AxM/VmVyaVNpZ24gQ2xhc3MgMSBDQSBJbmRpdmlkdWFsIFN1YnNjcmliZXItUGVyc29uYSBOb3Qg" + "VmFsaWRhdGVkAhAW25/9Rtc6aQ+irD9NW8MsMAkGBSsOAwIaBQCggbowGAYJKoZIhvcNAQkDMQsG" + "CSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDAxMDAyMTczNTE4WjAjBgkqhkiG9w0BCQQxFgQU" + "gZjSaBEY2oxGvlQUIMnxSXhivK8wWwYJKoZIhvcNAQkPMU4wTDAKBggqhkiG9w0DBzAOBggqhkiG" + "9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwBwYFKw4DAh0w" + "DQYJKoZIhvcNAQEBBQAEgYAzk+PU91/ZFfoiuKOECjxEh9fDYE2jfDCheBIgh5gdcCo+sS1WQs8O" + "HreQ9Nop/JdJv1DQMBK6weNBBDoP0EEkRm1XCC144XhXZC82jBZohYmi2WvDbbC//YN58kRMYMyy" + "srrfn4Z9I+6kTriGXkrpGk9Q0LSGjmG2BIsqiF0dvwAAAAAAAA=="); // // dsaWithSHA1 cert // byte[] cert7 = Base64.decode( "MIIEXAYJKoZIhvcNAQcCoIIETTCCBEkCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCAsMwggK/MIIB4AIBADCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7" + "d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULjw3GobwaJX13kquPh" + "fVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABj" + "TUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/z" + "m8Q12PFp/PjOhh+nMA4xDDAKBgNVBAMTA0lEMzAeFw05NzEwMDEwMDAwMDBa" + "Fw0zODAxMDEwMDAwMDBaMA4xDDAKBgNVBAMTA0lEMzCB8DCBpwYFKw4DAhsw" + "gZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULj" + "w3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FE" + "WA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3" + "SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nA0QAAkEAkYkXLYMtGVGWj9OnzjPn" + "sB9sefSRPrVegZJCZbpW+Iv0/1RP1u04pHG9vtRpIQLjzUiWvLMU9EKQTThc" + "eNMmWDCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxg" + "Y61TX5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/Q" + "F4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jH" + "SqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nAy8AMCwC" + "FBY3dBSdeprGcqpr6wr3xbG+6WW+AhRMm/facKJNxkT3iKgJbp7R8Xd3QTGC" + "AWEwggFdAgEBMBMwDjEMMAoGA1UEAxMDSUQzAgEAMAkGBSsOAwIaBQCgXTAY" + "BgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMjA1" + "MjQyMzEzMDdaMCMGCSqGSIb3DQEJBDEWBBS4WMsoJhf7CVbZYCFcjoTRzPkJ" + "xjCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61T" + "X5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BU" + "j+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqji" + "jUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nBC8wLQIVALID" + "dt+MHwawrDrwsO1Z6sXBaaJsAhRaKssrpevmLkbygKPV07XiAKBG02Zvb2Jh" + "cg=="); // // testcrl.pem // byte[] crl1 = Base64.decode( "MIICjTCCAfowDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMxIDAeBgNVBAoT" + "F1JTQSBEYXRhIFNlY3VyaXR5LCBJbmMuMS4wLAYDVQQLEyVTZWN1cmUgU2VydmVy" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5Fw05NTA1MDIwMjEyMjZaFw05NTA2MDEw" + "MDAxNDlaMIIBaDAWAgUCQQAABBcNOTUwMjAxMTcyNDI2WjAWAgUCQQAACRcNOTUw" + "MjEwMDIxNjM5WjAWAgUCQQAADxcNOTUwMjI0MDAxMjQ5WjAWAgUCQQAADBcNOTUw" + "MjI1MDA0NjQ0WjAWAgUCQQAAGxcNOTUwMzEzMTg0MDQ5WjAWAgUCQQAAFhcNOTUw" + "MzE1MTkxNjU0WjAWAgUCQQAAGhcNOTUwMzE1MTk0MDQxWjAWAgUCQQAAHxcNOTUw" + "MzI0MTk0NDMzWjAWAgUCcgAABRcNOTUwMzI5MjAwNzExWjAWAgUCcgAAERcNOTUw" + "MzMwMDIzNDI2WjAWAgUCQQAAIBcNOTUwNDA3MDExMzIxWjAWAgUCcgAAHhcNOTUw" + "NDA4MDAwMjU5WjAWAgUCcgAAQRcNOTUwNDI4MTcxNzI0WjAWAgUCcgAAOBcNOTUw" + "NDI4MTcyNzIxWjAWAgUCcgAATBcNOTUwNTAyMDIxMjI2WjANBgkqhkiG9w0BAQIF" + "AAN+AHqOEJXSDejYy0UwxxrH/9+N2z5xu/if0J6qQmK92W0hW158wpJg+ovV3+wQ" + "wvIEPRL2rocL0tKfAsVq1IawSJzSNgxG0lrcla3MrJBnZ4GaZDu4FutZh72MR3Gt" + "JaAL3iTJHJD55kK2D/VoyY1djlsPuNh6AEgdVwFAyp0v"); // // ecdsa cert with extra octet string. // byte[] oldEcdsa = Base64.decode( "MIICljCCAkCgAwIBAgIBATALBgcqhkjOPQQBBQAwgY8xCzAJBgNVBAYTAkFVMSgwJ" + "gYDVQQKEx9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIwEAYDVQQHEw" + "lNZWxib3VybmUxETAPBgNVBAgTCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWV" + "kYmFjay1jcnlwdG9AYm91bmN5Y2FzdGxlLm9yZzAeFw0wMTEyMDcwMTAwMDRaFw0w" + "MTEyMDcwMTAxNDRaMIGPMQswCQYDVQQGEwJBVTEoMCYGA1UEChMfVGhlIExlZ2lvb" + "iBvZiB0aGUgQm91bmN5IENhc3RsZTESMBAGA1UEBxMJTWVsYm91cm5lMREwDwYDVQ" + "QIEwhWaWN0b3JpYTEvMC0GCSqGSIb3DQEJARYgZmVlZGJhY2stY3J5cHRvQGJvdW5" + "jeWNhc3RsZS5vcmcwgeQwgb0GByqGSM49AgEwgbECAQEwKQYHKoZIzj0BAQIef///" + "////////////f///////gAAAAAAAf///////MEAEHn///////////////3///////" + "4AAAAAAAH///////AQeawFsO9zxiUHQ1lSSFHXKcanbL7J9HTd5YYXClCwKBB8CD/" + "qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqvAh5///////////////9///+eXpq" + "fXZBx+9FSJoiQnQsDIgAEHwJbbcU7xholSP+w9nFHLebJUhqdLSU05lq/y9X+DHAw" + "CwYHKoZIzj0EAQUAA0MAMEACHnz6t4UNoVROp74ma4XNDjjGcjaqiIWPZLK8Bdw3G" + "QIeLZ4j3a6ividZl344UH+UPUE7xJxlYGuy7ejTsqRR"); byte[] keyUsage = Base64.decode( "MIIE7TCCBFagAwIBAgIEOAOR7jANBgkqhkiG9w0BAQQFADCByTELMAkGA1UE" + "BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgYDVQQLFD93d3cuZW50" + "cnVzdC5uZXQvQ2xpZW50X0NBX0luZm8vQ1BTIGluY29ycC4gYnkgcmVmLiBs" + "aW1pdHMgbGlhYi4xJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExp" + "bWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENsaWVudCBDZXJ0aWZpY2F0" + "aW9uIEF1dGhvcml0eTAeFw05OTEwMTIxOTI0MzBaFw0xOTEwMTIxOTU0MzBa" + "MIHJMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxSDBGBgNV" + "BAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0FfSW5mby9DUFMgaW5jb3Jw" + "LiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UECxMcKGMpIDE5OTkgRW50" + "cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5uZXQgQ2xpZW50" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GL" + "ADCBhwKBgQDIOpleMRffrCdvkHvkGf9FozTC28GoT/Bo6oT9n3V5z8GKUZSv" + "x1cDR2SerYIbWtp/N3hHuzeYEpbOxhN979IMMFGpOZ5V+Pux5zDeg7K6PvHV" + "iTs7hbqqdCz+PzFur5GVbgbUB01LLFZHGARS2g4Qk79jkJvh34zmAqTmT173" + "iwIBA6OCAeAwggHcMBEGCWCGSAGG+EIBAQQEAwIABzCCASIGA1UdHwSCARkw" + "ggEVMIHkoIHhoIHepIHbMIHYMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50" + "cnVzdC5uZXQxSDBGBgNVBAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0Ff" + "SW5mby9DUFMgaW5jb3JwLiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UE" + "CxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50" + "cnVzdC5uZXQgQ2xpZW50IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYD" + "VQQDEwRDUkwxMCygKqAohiZodHRwOi8vd3d3LmVudHJ1c3QubmV0L0NSTC9D" + "bGllbnQxLmNybDArBgNVHRAEJDAigA8xOTk5MTAxMjE5MjQzMFqBDzIwMTkx" + "MDEyMTkyNDMwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUxPucKXuXzUyW" + "/O5bs8qZdIuV6kwwHQYDVR0OBBYEFMT7nCl7l81MlvzuW7PKmXSLlepMMAwG" + "A1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI" + "hvcNAQEEBQADgYEAP66K8ddmAwWePvrqHEa7pFuPeJoSSJn59DXeDDYHAmsQ" + "OokUgZwxpnyyQbJq5wcBoUv5nyU7lsqZwz6hURzzwy5E97BnRqqS5TvaHBkU" + "ODDV4qIxJS7x7EU47fgGWANzYrAQMY9Av2TgXD7FTx/aEkP/TOYGJqibGapE" + "PHayXOw="); byte[] nameCert = Base64.decode( "MIIEFjCCA3+gAwIBAgIEdS8BozANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJE"+ "RTERMA8GA1UEChQIREFURVYgZUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRQ0Eg"+ "REFURVYgRDAzIDE6UE4wIhgPMjAwMTA1MTAxMDIyNDhaGA8yMDA0MDUwOTEwMjI0"+ "OFowgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIFAZCYXllcm4xEjAQBgNVBAcUCU7I"+ "dXJuYmVyZzERMA8GA1UEChQIREFURVYgZUcxHTAbBgNVBAUTFDAwMDAwMDAwMDA4"+ "OTU3NDM2MDAxMR4wHAYDVQQDFBVEaWV0bWFyIFNlbmdlbmxlaXRuZXIwgaEwDQYJ"+ "KoZIhvcNAQEBBQADgY8AMIGLAoGBAJLI/LJLKaHoMk8fBECW/od8u5erZi6jI8Ug"+ "C0a/LZyQUO/R20vWJs6GrClQtXB+AtfiBSnyZOSYzOdfDI8yEKPEv8qSuUPpOHps"+ "uNCFdLZF1vavVYGEEWs2+y+uuPmg8q1oPRyRmUZ+x9HrDvCXJraaDfTEd9olmB/Z"+ "AuC/PqpjAgUAwAAAAaOCAcYwggHCMAwGA1UdEwEB/wQCMAAwDwYDVR0PAQH/BAUD"+ "AwdAADAxBgNVHSAEKjAoMCYGBSskCAEBMB0wGwYIKwYBBQUHAgEWD3d3dy56cy5k"+ "YXRldi5kZTApBgNVHREEIjAggR5kaWV0bWFyLnNlbmdlbmxlaXRuZXJAZGF0ZXYu"+ "ZGUwgYQGA1UdIwR9MHuhc6RxMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1"+ "bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0"+ "MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE6CBACm8LkwDgYHAoIG"+ "AQoMAAQDAQEAMEcGA1UdHwRAMD4wPKAUoBKGEHd3dy5jcmwuZGF0ZXYuZGWiJKQi"+ "MCAxCzAJBgNVBAYTAkRFMREwDwYDVQQKFAhEQVRFViBlRzAWBgUrJAgDBAQNMAsT"+ "A0VVUgIBBQIBATAdBgNVHQ4EFgQUfv6xFP0xk7027folhy+ziZvBJiwwLAYIKwYB"+ "BQUHAQEEIDAeMBwGCCsGAQUFBzABhhB3d3cuZGlyLmRhdGV2LmRlMA0GCSqGSIb3"+ "DQEBBQUAA4GBAEOVX6uQxbgtKzdgbTi6YLffMftFr2mmNwch7qzpM5gxcynzgVkg"+ "pnQcDNlm5AIbS6pO8jTCLfCd5TZ5biQksBErqmesIl3QD+VqtB+RNghxectZ3VEs"+ "nCUtcE7tJ8O14qwCb3TxS9dvIUFiVi4DjbxX46TdcTbTaK8/qr6AIf+l"); byte[] probSelfSignedCert = Base64.decode( "MIICxTCCAi6gAwIBAgIQAQAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQUFADBF" + "MScwJQYDVQQKEx4gRElSRUNUSU9OIEdFTkVSQUxFIERFUyBJTVBPVFMxGjAYBgNV" + "BAMTESBBQyBNSU5FRkkgQiBURVNUMB4XDTA0MDUwNzEyMDAwMFoXDTE0MDUwNzEy" + "MDAwMFowRTEnMCUGA1UEChMeIERJUkVDVElPTiBHRU5FUkFMRSBERVMgSU1QT1RT" + "MRowGAYDVQQDExEgQUMgTUlORUZJIEIgVEVTVDCBnzANBgkqhkiG9w0BAQEFAAOB" + "jQAwgYkCgYEAveoCUOAukZdcFCs2qJk76vSqEX0ZFzHqQ6faBPZWjwkgUNwZ6m6m" + "qWvvyq1cuxhoDvpfC6NXILETawYc6MNwwxsOtVVIjuXlcF17NMejljJafbPximEt" + "DQ4LcQeSp4K7FyFlIAMLyt3BQ77emGzU5fjFTvHSUNb3jblx0sV28c0CAwEAAaOB" + "tTCBsjAfBgNVHSMEGDAWgBSEJ4bLbvEQY8cYMAFKPFD1/fFXlzAdBgNVHQ4EFgQU" + "hCeGy27xEGPHGDABSjxQ9f3xV5cwDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIB" + "AQQEAwIBBjA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vYWRvbmlzLnBrNy5jZXJ0" + "cGx1cy5uZXQvZGdpLXRlc3QuY3JsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN" + "AQEFBQADgYEAmToHJWjd3+4zknfsP09H6uMbolHNGG0zTS2lrLKpzcmkQfjhQpT9" + "LUTBvfs1jdjo9fGmQLvOG+Sm51Rbjglb8bcikVI5gLbclOlvqLkm77otjl4U4Z2/" + "Y0vP14Aov3Sn3k+17EfReYUZI4liuB95ncobC4e8ZM++LjQcIM0s+Vs="); byte[] gost34102001base = Base64.decode( "MIIB1DCCAYECEEjpVKXP6Wn1yVz3VeeDQa8wCgYGKoUDAgIDBQAwbTEfMB0G" + "A1UEAwwWR29zdFIzNDEwLTIwMDEgZXhhbXBsZTESMBAGA1UECgwJQ3J5cHRv" + "UHJvMQswCQYDVQQGEwJSVTEpMCcGCSqGSIb3DQEJARYaR29zdFIzNDEwLTIw" + "MDFAZXhhbXBsZS5jb20wHhcNMDUwMjAzMTUxNjQ2WhcNMTUwMjAzMTUxNjQ2" + "WjBtMR8wHQYDVQQDDBZHb3N0UjM0MTAtMjAwMSBleGFtcGxlMRIwEAYDVQQK" + "DAlDcnlwdG9Qcm8xCzAJBgNVBAYTAlJVMSkwJwYJKoZIhvcNAQkBFhpHb3N0" + "UjM0MTAtMjAwMUBleGFtcGxlLmNvbTBjMBwGBiqFAwICEzASBgcqhQMCAiQA" + "BgcqhQMCAh4BA0MABECElWh1YAIaQHUIzROMMYks/eUFA3pDXPRtKw/nTzJ+" + "V4/rzBa5lYgD0Jp8ha4P5I3qprt+VsfLsN8PZrzK6hpgMAoGBiqFAwICAwUA" + "A0EAHw5dw/aw/OiNvHyOE65kvyo4Hp0sfz3csM6UUkp10VO247ofNJK3tsLb" + "HOLjUaqzefrlGb11WpHYrvWFg+FcLA=="); private final byte[] emptyDNCert = Base64.decode( "MIICfTCCAeagAwIBAgIBajANBgkqhkiG9w0BAQQFADB8MQswCQYDVQQGEwJVUzEMMAoGA1UEChMD" + "Q0RXMQkwBwYDVQQLEwAxCTAHBgNVBAcTADEJMAcGA1UECBMAMRowGAYDVQQDExFUZW1wbGFyIFRl" + "c3QgMTAyNDEiMCAGCSqGSIb3DQEJARYTdGVtcGxhcnRlc3RAY2R3LmNvbTAeFw0wNjA1MjIwNTAw" + "MDBaFw0xMDA1MjIwNTAwMDBaMHwxCzAJBgNVBAYTAlVTMQwwCgYDVQQKEwNDRFcxCTAHBgNVBAsT" + "ADEJMAcGA1UEBxMAMQkwBwYDVQQIEwAxGjAYBgNVBAMTEVRlbXBsYXIgVGVzdCAxMDI0MSIwIAYJ" + "KoZIhvcNAQkBFhN0ZW1wbGFydGVzdEBjZHcuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB" + "gQDH3aJpJBfM+A3d84j5YcU6zEQaQ76u5xO9NSBmHjZykKS2kCcUqPpvVOPDA5WgV22dtKPh+lYV" + "iUp7wyCVwAKibq8HIbihHceFqMKzjwC639rMoDJ7bi/yzQWz1Zg+075a4FGPlUKn7Yfu89wKkjdW" + "wDpRPXc/agqBnrx5pJTXzQIDAQABow8wDTALBgNVHQ8EBAMCALEwDQYJKoZIhvcNAQEEBQADgYEA" + "RRsRsjse3i2/KClFVd6YLZ+7K1BE0WxFyY2bbytkwQJSxvv3vLSuweFUbhNxutb68wl/yW4GLy4b" + "1QdyswNxrNDXTuu5ILKhRDDuWeocz83aG2KGtr3JlFyr3biWGEyn5WUOE6tbONoQDJ0oPYgI6CAc" + "EHdUp0lioOCt6UOw7Cs="); private AsymmetricKeyParameter dudPublicKey = new AsymmetricKeyParameter(true) { public String getAlgorithm() { return null; } public String getFormat() { return null; } public byte[] getEncoded() { return null; } }; public String getName() { return "CertTest"; } public void checkCertificate( int id, byte[] bytes) { try { X509CertificateHolder certHldr = new X509CertificateHolder(bytes); SubjectPublicKeyInfo k = certHldr.getSubjectPublicKeyInfo(); // System.out.println(cert); } catch (Exception e) { fail(e.toString()); } } /* public void checkNameCertificate( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "LKBX-BC"); X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn); AsymmetricKeyParameter k = cert.getAsymmetricKeyParameter(); if (!cert.getIssuerDN().toString().equals("C=DE,O=DATEV eG,0.2.262.1.10.7.20=1+CN=CA DATEV D03 1:PN")) { fail(id + " failed - name test."); } // System.out.println(cert); } catch (Exception e) { fail(dump + Strings.lineSeparator() + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } */ public void checkKeyUsage( int id, byte[] bytes) throws IOException { X509CertificateHolder certHld = new X509CertificateHolder(bytes); if ((DERBitString.getInstance(certHld.getExtension(Extension.keyUsage).getParsedValue()).getBytes()[0] & 0x01) != 0) { fail("error generating cert - key usage wrong."); } } public void checkSelfSignedCertificate( int id, byte[] bytes) throws OperatorCreationException, IOException, CertException { X509CertificateHolder certHolder = new X509CertificateHolder(bytes); assertTrue(certHolder.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(certHolder))); } /** * we generate a self signed certificate for the sake of testing - RSA */ public void checkCreation1() throws Exception { // // a sample key pair. // AsymmetricKeyParameter pubKey = new RSAKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); AsymmetricKeyParameter privKey = new RSAPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // distinguished name table. // X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE); builder.addRDN(RFC4519Style.c, "AU"); builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); builder.addRDN(RFC4519Style.l, "Melbourne"); builder.addRDN(RFC4519Style.st, "Victoria"); builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); // // extensions // // // create the certificate - version 3 - without extensions // AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256WithRSAEncryption"); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlg, digAlgFinder.find(sigAlg)).build(privKey); X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000),builder.build(), pubKey); X509CertificateHolder certH = certGen.build(sigGen); assertTrue(certH.isValidOn(new Date())); ContentVerifierProvider contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(pubKey); assertTrue(certH.isSignatureValid(contentVerifierProvider)); X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certH); Set dummySet = cert.getNonCriticalExtensionOIDs(); if (dummySet != null) { fail("non-critical oid set should be null"); } dummySet = cert.getCriticalExtensionOIDs(); if (dummySet != null) { fail("critical oid set should be null"); } // // create the certificate - version 3 - with extensions // sigGen = new BcRSAContentSignerBuilder(sigAlgFinder.find("MD5WithRSA"), digAlgFinder.find(sigAlgFinder.find("MD5withRSA"))).build(privKey); certGen = new BcX509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1) , new Date(System.currentTimeMillis() - 50000) , new Date(System.currentTimeMillis() + 50000) , builder.build() , pubKey) .addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, new KeyUsage(KeyUsage.encipherOnly)) .addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)) .addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509CertificateHolder certHolder = certGen.build(sigGen); assertTrue(certHolder.isValidOn(new Date())); contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey); if (!certHolder.isSignatureValid(contentVerifierProvider)) { fail("signature test failed"); } ByteArrayInputStream bIn = new ByteArrayInputStream(certHolder.getEncoded()); CertificateFactory certFact = CertificateFactory.getInstance("X.509"); cert = (X509Certificate)certFact.generateCertificate(bIn); if (!cert.getKeyUsage()[7]) { fail("error generating cert - key usage wrong."); } // System.out.println(cert); // // create the certificate - version 1 // sigGen = new BcRSAContentSignerBuilder(sigAlgFinder.find("MD5WithRSA"), digAlgFinder.find(sigAlgFinder.find("MD5withRSA"))).build(privKey); X509v1CertificateBuilder certGen1 = new BcX509v1CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); cert = new JcaX509CertificateConverter().getCertificate(certGen1.build(sigGen)); assertTrue(certHolder.isValidOn(new Date())); contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(pubKey); assertTrue(certHolder.isSignatureValid(contentVerifierProvider)); bIn = new ByteArrayInputStream(cert.getEncoded()); certFact = CertificateFactory.getInstance("X.509"); cert = (X509Certificate)certFact.generateCertificate(bIn); // System.out.println(cert); if (!cert.getIssuerDN().equals(cert.getSubjectDN())) { fail("name comparison fails"); } // // a lightweight key pair. // RSAKeyParameters lwPubKey = new RSAKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RSAPrivateCrtKeyParameters lwPrivKey = new RSAPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // distinguished name table. // builder = new X500NameBuilder(RFC4519Style.INSTANCE); builder.addRDN(RFC4519Style.c, "AU"); builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); builder.addRDN(RFC4519Style.l, "Melbourne"); builder.addRDN(RFC4519Style.st, "Victoria"); builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); // // extensions // // // create the certificate - version 3 - without extensions // AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(lwPrivKey); SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(lwPubKey); certGen = new X509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), builder.build(), pubInfo); certHolder = certGen.build(sigGen); assertTrue(certHolder.isValidOn(new Date())); contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(lwPubKey); assertTrue(certHolder.isSignatureValid(contentVerifierProvider)); if (!certHolder.isSignatureValid(contentVerifierProvider)) { fail("lw sig verification failed"); } } /** * we generate a self signed certificate for the sake of testing - DSA */ public void checkCreation2() throws Exception { // // set up the keys // AsymmetricKeyParameter privKey; AsymmetricKeyParameter pubKey; AsymmetricCipherKeyPairGenerator kpg = new DSAKeyPairGenerator(); BigInteger r = new BigInteger("68076202252361894315274692543577577550894681403"); BigInteger s = new BigInteger("1089214853334067536215539335472893651470583479365"); DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(512, 80, new SecureRandom()); DSAParameters params = pGen.generateParameters(); DSAKeyGenerationParameters genParam = new DSAKeyGenerationParameters(new SecureRandom(), params); kpg.init(genParam); AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); privKey = (AsymmetricKeyParameter)pair.getPrivate(); pubKey = (AsymmetricKeyParameter)pair.getPublic(); // // distinguished name table. // X500NameBuilder builder = createStdBuilder(); // // extensions // // // create the certificate - version 3 // AlgorithmIdentifier sigAlgId = sigAlgFinder.find("SHA1withDSA"); AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); ContentSigner sigGen = new BcDSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); X509CertificateHolder cert = certGen.build(sigGen); assertTrue(cert.isValidOn(new Date())); assertTrue(cert.isSignatureValid(new BcDSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); // // create the certificate - version 1 // sigAlgId = sigAlgFinder.find("SHA1withDSA"); digAlgId = digAlgFinder.find(sigAlgId); sigGen = new BcDSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); X509v1CertificateBuilder certGen1 = new BcX509v1CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); cert = certGen1.build(sigGen); assertTrue(cert.isValidOn(new Date())); assertTrue(cert.isSignatureValid(new BcDSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); AsymmetricKeyParameter certPubKey = PublicKeyFactory.createKey(cert.getSubjectPublicKeyInfo()); assertTrue(cert.isSignatureValid(new BcDSAContentVerifierProviderBuilder(digAlgFinder).build(certPubKey))); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509"); X509Certificate x509cert = (X509Certificate)fact.generateCertificate(bIn); //System.out.println(cert); } private X500NameBuilder createStdBuilder() { X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE); builder.addRDN(RFC4519Style.c, "AU"); builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); builder.addRDN(RFC4519Style.l, "Melbourne"); builder.addRDN(RFC4519Style.st, "Victoria"); builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); return builder; } private void checkCRL( int id, byte[] bytes) { String dump = ""; try { X509CRLHolder crlHolder = new X509CRLHolder(bytes); } catch (Exception e) { fail(dump + Strings.lineSeparator() + getName() + ": "+ id + " failed - exception " + e.toString()); } } public void checkCRLCreation1() throws Exception { AsymmetricCipherKeyPairGenerator kpg = new RSAKeyPairGenerator(); RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( BigInteger.valueOf(0x1001), new SecureRandom(), 1024, 25); kpg.init(genParam); AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); Date now = new Date(); X509v2CRLBuilder crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); crlGen.addCRLEntry(BigInteger.ONE, now, CRLReason.privilegeWithdrawn); crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier(pair.getPublic())); AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256withRSAEncryption"); AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); X509CRLHolder crl = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build(pair.getPrivate())); if (!crl.getIssuer().equals(new X500Name("CN=Test CA"))) { fail("failed CRL issuer test"); } Extension authExt = crl.getExtension(Extension.authorityKeyIdentifier); if (authExt == null) { fail("failed to find CRL extension"); } AuthorityKeyIdentifier authId = AuthorityKeyIdentifier.getInstance(authExt.getParsedValue()); X509CRLEntryHolder entry = crl.getRevokedCertificate(BigInteger.ONE); if (entry == null) { fail("failed to find CRL entry"); } if (!entry.getSerialNumber().equals(BigInteger.ONE)) { fail("CRL cert serial number does not match"); } if (!entry.hasExtensions()) { fail("CRL entry extension not found"); } Extension ext = entry.getExtension(Extension.reasonCode); if (ext != null) { ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(ext.getParsedValue()); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong"); } } else { fail("CRL entry reasonCode not found"); } } public void checkCRLCreation2() throws Exception { AsymmetricCipherKeyPairGenerator kpg = new RSAKeyPairGenerator(); RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( BigInteger.valueOf(0x1001), new SecureRandom(), 1024, 25); kpg.init(genParam); AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); Date now = new Date(); X509v2CRLBuilder crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); ExtensionsGenerator extGen = new ExtensionsGenerator(); CRLReason crlReason = CRLReason.lookup(CRLReason.privilegeWithdrawn); extGen.addExtension(Extension.reasonCode, false, crlReason); BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); crlGen.addCRLEntry(BigInteger.ONE, now, extGen.generate()); crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier((AsymmetricKeyParameter)pair.getPublic())); AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256withRSAEncryption"); AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); X509CRLHolder crlHolder = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter)pair.getPrivate())); if (!crlHolder.getIssuer().equals(new X500Name("CN=Test CA"))) { fail("failed CRL issuer test"); } Extension authExt = crlHolder.getExtension(Extension.authorityKeyIdentifier); if (authExt == null) { fail("failed to find CRL extension"); } AuthorityKeyIdentifier authId = AuthorityKeyIdentifier.getInstance(authExt.getParsedValue()); X509CRLEntryHolder entry = crlHolder.getRevokedCertificate(BigInteger.ONE); if (entry == null) { fail("failed to find CRL entry"); } if (!entry.getSerialNumber().equals(BigInteger.ONE)) { fail("CRL cert serial number does not match"); } if (!entry.hasExtensions()) { fail("CRL entry extension not found"); } Extension ext = entry.getExtension(Extension.reasonCode); if (ext != null) { ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(ext.getParsedValue()); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong"); } } else { fail("CRL entry reasonCode not found"); } } public void checkCRLCreation3() throws Exception { AsymmetricCipherKeyPairGenerator kpg = new RSAKeyPairGenerator(); RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( BigInteger.valueOf(0x1001), new SecureRandom(), 1024, 25); kpg.init(genParam); AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); Date now = new Date(); X509v2CRLBuilder crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); ExtensionsGenerator extGen = new ExtensionsGenerator(); CRLReason crlReason = CRLReason.lookup(CRLReason.privilegeWithdrawn); extGen.addExtension(Extension.reasonCode, false, crlReason); BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); Extensions entryExtensions = extGen.generate(); crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions); crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier((AsymmetricKeyParameter)pair.getPublic())); AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256withRSAEncryption"); AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); X509CRLHolder crlHolder = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter)pair.getPrivate())); if (!crlHolder.getIssuer().equals(new X500Name("CN=Test CA"))) { fail("failed CRL issuer test"); } Extension authExt = crlHolder.getExtension(Extension.authorityKeyIdentifier); if (authExt == null) { fail("failed to find CRL extension"); } AuthorityKeyIdentifier authId = AuthorityKeyIdentifier.getInstance(authExt.getParsedValue()); X509CRLEntryHolder entry = crlHolder.getRevokedCertificate(BigInteger.ONE); if (entry == null) { fail("failed to find CRL entry"); } if (!entry.getSerialNumber().equals(BigInteger.ONE)) { fail("CRL cert serial number does not match"); } if (!entry.hasExtensions()) { fail("CRL entry extension not found"); } Extension ext = entry.getExtension(Extension.reasonCode); if (ext != null) { ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(ext.getParsedValue()); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong"); } } else { fail("CRL entry reasonCode not found"); } // // check loading of existing CRL // now = new Date(); crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); crlGen.addCRL(crlHolder); crlGen.addCRLEntry(BigInteger.valueOf(2), now, entryExtensions); crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier(pair.getPublic())); crlHolder = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build(pair.getPrivate())); int count = 0; boolean oneFound = false; boolean twoFound = false; Iterator it = crlHolder.getRevokedCertificates().iterator(); while (it.hasNext()) { X509CRLEntryHolder crlEnt = (X509CRLEntryHolder)it.next(); if (crlEnt.getSerialNumber().intValue() == 1) { oneFound = true; Extension extn = crlEnt.getExtension(Extension.reasonCode); if (extn != null) { ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(extn.getParsedValue()); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong on recheck"); } } else { fail("CRL entry reasonCode not found on recheck"); } } else if (crlEnt.getSerialNumber().intValue() == 2) { twoFound = true; } count++; } if (count != 2) { fail("wrong number of CRLs found, got: " + count); } if (!oneFound || !twoFound) { fail("wrong CRLs found in copied list"); } // // check factory read back // CertificateFactory cFact = CertificateFactory.getInstance("X.509"); X509CRL readCrl = (X509CRL)cFact.generateCRL(new ByteArrayInputStream(crlHolder.getEncoded())); if (readCrl == null) { fail("crl not returned!"); } Collection col = cFact.generateCRLs(new ByteArrayInputStream(crlHolder.getEncoded())); if (col.size() != 1) { fail("wrong number of CRLs found in collection"); } } public void checkCreation5() throws Exception { // // a sample key pair. // AsymmetricKeyParameter pubKey = new RSAKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); AsymmetricKeyParameter privKey = new RSAPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // set up the keys // SecureRandom rand = new SecureRandom(); // // distinguished name table. // X500NameBuilder builder = createStdBuilder(); // // create base certificate - version 3 // AlgorithmIdentifier sigAlg = sigAlgFinder.find("MD5WithRSA"); AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(privKey); ASN1ObjectIdentifier extOid = new ASN1ObjectIdentifier("2.5.29.37"); X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey) .addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, new KeyUsage(KeyUsage.encipherOnly)) .addExtension(extOid, true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)) .addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509CertificateHolder baseCert = certGen.build(sigGen); // // copy certificate // certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey) .copyAndAddExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, baseCert) .copyAndAddExtension(extOid, false, baseCert); X509CertificateHolder cert = certGen.build(sigGen); assertTrue(cert.isValidOn(new Date())); assertTrue(cert.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); if (!baseCert.getExtension(new ASN1ObjectIdentifier("2.5.29.15")).equals(cert.getExtension(new ASN1ObjectIdentifier("2.5.29.15")))) { fail("2.5.29.15 differs"); } assertTrue(baseCert.getExtension(extOid).getExtnId().equals(cert.getExtension(extOid).getExtnId())); assertFalse(baseCert.getExtension(extOid).isCritical() == cert.getExtension(extOid).isCritical()); if (!baseCert.getExtension(extOid).getParsedValue().equals(cert.getExtension(extOid).getParsedValue())) { fail("2.5.29.37 differs"); } // // exception test // try { certGen.copyAndAddExtension(new ASN1ObjectIdentifier("2.5.99.99"), true, baseCert); fail("exception not thrown on dud extension copy"); } catch (NullPointerException e) { // expected } // try // { // certGen.setPublicKey(dudPublicKey); // // certGen.generate(privKey, BC); // // fail("key without encoding not detected in v3"); // } // catch (IllegalArgumentException e) // { // // expected // } } public void testForgedSignature() throws Exception { String cert = "MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV" + "BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD" + "VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU4NTVa" + "Fw0wNjEwMTEyMzU4NTVaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs" + "YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy" + "IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD" + "hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u" + "12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAbynCRIlUQgaqyNgU" + "DF6P14yRKUtX8akOP2TwStaSiVf/akYqfLFm3UGka5XbPj4rifrZ0/sOoZEEBvHQ" + "e20sRA=="; X509CertificateHolder hldr = new X509CertificateHolder(Base64.decode(cert)); assertFalse(hldr.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(hldr))); } private void pemTest() throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509", "SC"); X509Certificate cert = readPEMCert(cf, PEMData.CERTIFICATE_1); if (cert == null) { fail("PEM cert not read"); } cert = readPEMCert(cf, "-----BEGIN CERTIFICATE-----" + PEMData.CERTIFICATE_2); if (cert == null) { fail("PEM cert with extraneous header not read"); } CRL crl = cf.generateCRL(new ByteArrayInputStream(PEMData.CRL_1.getBytes("US-ASCII"))); if (crl == null) { fail("PEM crl not read"); } Collection col = cf.generateCertificates(new ByteArrayInputStream(PEMData.CERTIFICATE_2.getBytes("US-ASCII"))); if (col.size() != 1 || !col.contains(cert)) { fail("PEM cert collection not right"); } col = cf.generateCRLs(new ByteArrayInputStream(PEMData.CRL_2.getBytes("US-ASCII"))); if (col.size() != 1 || !col.contains(crl)) { fail("PEM crl collection not right"); } } private static X509Certificate readPEMCert(CertificateFactory cf, String pemData) throws CertificateException, UnsupportedEncodingException { return (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(pemData.getBytes("US-ASCII"))); } private void createPSSCert(String algorithm) throws Exception { AsymmetricCipherKeyPair pair = generateLongFixedKeys(); AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)pair.getPrivate(); AsymmetricKeyParameter pubKey = (AsymmetricKeyParameter)pair.getPublic(); // // distinguished name table. // X500NameBuilder builder = createStdBuilder(); // // create base certificate - version 3 // BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); AlgorithmIdentifier sigAlgId = sigAlgFinder.find(algorithm); AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); BcX509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, new KeyUsage(KeyUsage.encipherOnly)); certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); certGen.addExtension(Extension.authorityKeyIdentifier, true, extFact.createAuthorityKeyIdentifier(pubKey)); X509CertificateHolder baseCert = certGen.build(sigGen); assertTrue(baseCert.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); } private AsymmetricCipherKeyPair generateLongFixedKeys() { RSAKeyParameters pubKeySpec = new RSAKeyParameters( false, new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); RSAKeyParameters privKeySpec = new RSAPrivateCrtKeyParameters( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16), new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); return new AsymmetricCipherKeyPair(pubKeySpec, privKeySpec); } public void testNullDerNullCert() throws Exception { AsymmetricCipherKeyPair pair = generateLongFixedKeys(); AsymmetricKeyParameter pubKey = (AsymmetricKeyParameter)pair.getPublic(); AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)pair.getPrivate(); DefaultSignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder(); DefaultDigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); AlgorithmIdentifier sigAlgId = sigAlgFinder.find("MD5withRSA"); AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); BcX509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey); X509CertificateHolder cert = certGen.build(sigGen); Certificate struct = Certificate.getInstance(cert.getEncoded()); ASN1Object tbsCertificate = struct.getTBSCertificate(); AlgorithmIdentifier sig = struct.getSignatureAlgorithm(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCertificate); v.add(new AlgorithmIdentifier(sig.getAlgorithm())); v.add(struct.getSignature()); // verify ByteArrayInputStream bIn; String dump = ""; bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded()); cert = new X509CertificateHolder(new DERSequence(v).getEncoded()); assertTrue(cert.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); } public void testCertificates() throws Exception { checkCertificate(1, cert1); checkCertificate(2, cert2); checkCertificate(3, cert3); checkCertificate(4, cert4); checkCertificate(5, cert5); //checkCertificate(7, cert7); checkKeyUsage(8, keyUsage); checkSelfSignedCertificate(11, probSelfSignedCert); checkCRL(1, crl1); checkCreation1(); checkCreation2(); checkCreation5(); createPSSCert("SHA1withRSAandMGF1"); createPSSCert("SHA224withRSAandMGF1"); createPSSCert("SHA256withRSAandMGF1"); createPSSCert("SHA384withRSAandMGF1"); checkCRLCreation1(); checkCRLCreation2(); checkCRLCreation3(); pemTest(); checkCertificate(18, emptyDNCert); } }
mit
fvasquezjatar/fermat-unused
DMP/plugin/transaction/fermat-dmp-plugin-transaction-incoming-extra-user-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/transaction/incoming_extra_user/developer/bitdubai/version_1/structure/IncomingExtraUserMonitorAgent/MockErrorManager.java
3138
package unit.com.bitdubai.fermat_dmp_plugin.layer.transaction.incoming_extra_user.developer.bitdubai.version_1.structure.IncomingExtraUserMonitorAgent; import com.bitdubai.fermat_api.layer.all_definition.enums.Addons; import com.bitdubai.fermat_api.layer.all_definition.enums.PlatformComponents; import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins; import com.bitdubai.fermat_api.layer.all_definition.enums.UISource; import com.bitdubai.fermat_api.layer.all_definition.events.interfaces.FermatEvent; import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.enums.Wallets; import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.enums.SubApps; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedAddonsExceptionSeverity; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedPlatformExceptionSeverity; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedPluginExceptionSeverity; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedSubAppExceptionSeverity; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedUIExceptionSeverity; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedWalletExceptionSeverity; /** * Created by jorgegonzalez on 2015.07.02.. */ public class MockErrorManager implements ErrorManager { private String reportedException; public String getReportedException(){ return reportedException; } @Override public void reportUnexpectedPlatformException(PlatformComponents exceptionSource, UnexpectedPlatformExceptionSeverity unexpectedPlatformExceptionSeverity, Exception exception) { this.reportedException = exception.toString(); } @Override public void reportUnexpectedPluginException(Plugins exceptionSource, UnexpectedPluginExceptionSeverity unexpectedPluginExceptionSeverity, Exception exception) { this.reportedException = exception.toString(); } @Override public void reportUnexpectedWalletException(Wallets exceptionSource, UnexpectedWalletExceptionSeverity unexpectedWalletExceptionSeverity, Exception exception) { this.reportedException = exception.toString(); } @Override public void reportUnexpectedAddonsException(Addons exceptionSource, UnexpectedAddonsExceptionSeverity unexpectedAddonsExceptionSeverity, Exception exception) { this.reportedException = exception.toString(); } @Override public void reportUnexpectedSubAppException(SubApps exceptionSource, UnexpectedSubAppExceptionSeverity unexpectedAddonsExceptionSeverity, Exception exception) { } @Override public void reportUnexpectedUIException(UISource exceptionSource, UnexpectedUIExceptionSeverity unexpectedAddonsExceptionSeverity, Exception exception) { } @Override public void reportUnexpectedEventException(FermatEvent exceptionSource, Exception exception) { } }
mit
Skywalker-11/spongycastle
pg/src/main/java/org/spongycastle/openpgp/operator/bc/BcPGPKeyConverter.java
11245
package org.spongycastle.openpgp.operator.bc; import java.io.IOException; import java.util.Date; import org.spongycastle.asn1.ASN1ObjectIdentifier; import org.spongycastle.asn1.ASN1OctetString; import org.spongycastle.asn1.DEROctetString; import org.spongycastle.asn1.nist.NISTNamedCurves; import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; import org.spongycastle.asn1.x9.X9ECParameters; import org.spongycastle.asn1.x9.X9ECPoint; import org.spongycastle.bcpg.BCPGKey; import org.spongycastle.bcpg.DSAPublicBCPGKey; import org.spongycastle.bcpg.DSASecretBCPGKey; import org.spongycastle.bcpg.ECDHPublicBCPGKey; import org.spongycastle.bcpg.ECDSAPublicBCPGKey; import org.spongycastle.bcpg.ECPublicBCPGKey; import org.spongycastle.bcpg.ECSecretBCPGKey; import org.spongycastle.bcpg.ElGamalPublicBCPGKey; import org.spongycastle.bcpg.ElGamalSecretBCPGKey; import org.spongycastle.bcpg.HashAlgorithmTags; import org.spongycastle.bcpg.PublicKeyAlgorithmTags; import org.spongycastle.bcpg.PublicKeyPacket; import org.spongycastle.bcpg.RSAPublicBCPGKey; import org.spongycastle.bcpg.RSASecretBCPGKey; import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags; import org.spongycastle.crypto.params.AsymmetricKeyParameter; import org.spongycastle.crypto.params.DSAParameters; import org.spongycastle.crypto.params.DSAPrivateKeyParameters; import org.spongycastle.crypto.params.DSAPublicKeyParameters; import org.spongycastle.crypto.params.ECNamedDomainParameters; import org.spongycastle.crypto.params.ECPrivateKeyParameters; import org.spongycastle.crypto.params.ECPublicKeyParameters; import org.spongycastle.crypto.params.ElGamalParameters; import org.spongycastle.crypto.params.ElGamalPrivateKeyParameters; import org.spongycastle.crypto.params.ElGamalPublicKeyParameters; import org.spongycastle.crypto.params.RSAKeyParameters; import org.spongycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.spongycastle.crypto.util.SubjectPublicKeyInfoFactory; import org.spongycastle.openpgp.PGPAlgorithmParameters; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPKdfParameters; import org.spongycastle.openpgp.PGPPrivateKey; import org.spongycastle.openpgp.PGPPublicKey; public class BcPGPKeyConverter { /** * Create a PGPPublicKey from the passed in JCA one. * <p> * Note: the time passed in affects the value of the key's keyID, so you probably only want * to do this once for a JCA key, or make sure you keep track of the time you used. * </p> * @param algorithm asymmetric algorithm type representing the public key. * @param pubKey actual public key to associate. * @param time date of creation. * @throws PGPException on key creation problem. */ public PGPPublicKey getPGPPublicKey(int algorithm, PGPAlgorithmParameters algorithmParameters, AsymmetricKeyParameter pubKey, Date time) throws PGPException { BCPGKey bcpgKey; if (pubKey instanceof RSAKeyParameters) { RSAKeyParameters rK = (RSAKeyParameters)pubKey; bcpgKey = new RSAPublicBCPGKey(rK.getModulus(), rK.getExponent()); } else if (pubKey instanceof DSAPublicKeyParameters) { DSAPublicKeyParameters dK = (DSAPublicKeyParameters)pubKey; DSAParameters dP = dK.getParameters(); bcpgKey = new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY()); } else if (pubKey instanceof ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters eK = (ElGamalPublicKeyParameters)pubKey; ElGamalParameters eS = eK.getParameters(); bcpgKey = new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()); } else if (pubKey instanceof ECPublicKeyParameters) { SubjectPublicKeyInfo keyInfo; try { keyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubKey); } catch (IOException e) { throw new PGPException("Unable to encode key: " + e.getMessage(), e); } // TODO: should probably match curve by comparison as well ASN1ObjectIdentifier curveOid = ASN1ObjectIdentifier.getInstance(keyInfo.getAlgorithm().getParameters()); X9ECParameters params = NISTNamedCurves.getByOID(curveOid); ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes()); X9ECPoint derQ = new X9ECPoint(params.getCurve(), key); if (algorithm == PGPPublicKey.ECDH) { PGPKdfParameters kdfParams = (PGPKdfParameters)algorithmParameters; if (kdfParams == null) { // We default to these as they are specified as mandatory in RFC 6631. kdfParams = new PGPKdfParameters(HashAlgorithmTags.SHA256, SymmetricKeyAlgorithmTags.AES_128); } bcpgKey = new ECDHPublicBCPGKey(curveOid, derQ.getPoint(), kdfParams.getHashAlgorithm(), kdfParams.getSymmetricWrapAlgorithm()); } else if (algorithm == PGPPublicKey.ECDSA) { bcpgKey = new ECDSAPublicBCPGKey(curveOid, derQ.getPoint()); } else { throw new PGPException("unknown EC algorithm"); } } else { throw new PGPException("unknown key class"); } return new PGPPublicKey(new PublicKeyPacket(algorithm, time, bcpgKey), new BcKeyFingerprintCalculator()); } public PGPPrivateKey getPGPPrivateKey(PGPPublicKey pubKey, AsymmetricKeyParameter privKey) throws PGPException { BCPGKey privPk; switch (pubKey.getAlgorithm()) { case PGPPublicKey.RSA_ENCRYPT: case PGPPublicKey.RSA_SIGN: case PGPPublicKey.RSA_GENERAL: RSAPrivateCrtKeyParameters rsK = (RSAPrivateCrtKeyParameters)privKey; privPk = new RSASecretBCPGKey(rsK.getExponent(), rsK.getP(), rsK.getQ()); break; case PGPPublicKey.DSA: DSAPrivateKeyParameters dsK = (DSAPrivateKeyParameters)privKey; privPk = new DSASecretBCPGKey(dsK.getX()); break; case PGPPublicKey.ELGAMAL_ENCRYPT: case PGPPublicKey.ELGAMAL_GENERAL: ElGamalPrivateKeyParameters esK = (ElGamalPrivateKeyParameters)privKey; privPk = new ElGamalSecretBCPGKey(esK.getX()); break; case PGPPublicKey.ECDH: case PGPPublicKey.ECDSA: ECPrivateKeyParameters ecK = (ECPrivateKeyParameters)privKey; privPk = new ECSecretBCPGKey(ecK.getD()); break; default: throw new PGPException("unknown key class"); } return new PGPPrivateKey(pubKey.getKeyID(), pubKey.getPublicKeyPacket(), privPk); } public AsymmetricKeyParameter getPublicKey(PGPPublicKey publicKey) throws PGPException { PublicKeyPacket publicPk = publicKey.getPublicKeyPacket(); try { switch (publicPk.getAlgorithm()) { case PublicKeyAlgorithmTags.RSA_ENCRYPT: case PublicKeyAlgorithmTags.RSA_GENERAL: case PublicKeyAlgorithmTags.RSA_SIGN: RSAPublicBCPGKey rsaK = (RSAPublicBCPGKey)publicPk.getKey(); return new RSAKeyParameters(false, rsaK.getModulus(), rsaK.getPublicExponent()); case PublicKeyAlgorithmTags.DSA: DSAPublicBCPGKey dsaK = (DSAPublicBCPGKey)publicPk.getKey(); return new DSAPublicKeyParameters(dsaK.getY(), new DSAParameters(dsaK.getP(), dsaK.getQ(), dsaK.getG())); case PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT: case PublicKeyAlgorithmTags.ELGAMAL_GENERAL: ElGamalPublicBCPGKey elK = (ElGamalPublicBCPGKey)publicPk.getKey(); return new ElGamalPublicKeyParameters(elK.getY(), new ElGamalParameters(elK.getP(), elK.getG())); case PGPPublicKey.ECDH: case PGPPublicKey.ECDSA: ECPublicBCPGKey ecPub = (ECPublicBCPGKey)publicPk.getKey(); X9ECParameters x9 = BcUtil.getX9Parameters(ecPub.getCurveOID()); return new ECPublicKeyParameters(BcUtil.decodePoint(ecPub.getEncodedPoint(), x9.getCurve()), new ECNamedDomainParameters(ecPub.getCurveOID(), x9.getCurve(), x9.getG(), x9.getN(), x9.getH())); default: throw new PGPException("unknown public key algorithm encountered"); } } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("exception constructing public key", e); } } public AsymmetricKeyParameter getPrivateKey(PGPPrivateKey privKey) throws PGPException { PublicKeyPacket pubPk = privKey.getPublicKeyPacket(); BCPGKey privPk = privKey.getPrivateKeyDataPacket(); try { switch (pubPk.getAlgorithm()) { case PGPPublicKey.RSA_ENCRYPT: case PGPPublicKey.RSA_GENERAL: case PGPPublicKey.RSA_SIGN: RSAPublicBCPGKey rsaPub = (RSAPublicBCPGKey)pubPk.getKey(); RSASecretBCPGKey rsaPriv = (RSASecretBCPGKey)privPk; return new RSAPrivateCrtKeyParameters(rsaPriv.getModulus(), rsaPub.getPublicExponent(), rsaPriv.getPrivateExponent(), rsaPriv.getPrimeP(), rsaPriv.getPrimeQ(), rsaPriv.getPrimeExponentP(), rsaPriv.getPrimeExponentQ(), rsaPriv.getCrtCoefficient()); case PGPPublicKey.DSA: DSAPublicBCPGKey dsaPub = (DSAPublicBCPGKey)pubPk.getKey(); DSASecretBCPGKey dsaPriv = (DSASecretBCPGKey)privPk; return new DSAPrivateKeyParameters(dsaPriv.getX(), new DSAParameters(dsaPub.getP(), dsaPub.getQ(), dsaPub.getG())); case PGPPublicKey.ELGAMAL_ENCRYPT: case PGPPublicKey.ELGAMAL_GENERAL: ElGamalPublicBCPGKey elPub = (ElGamalPublicBCPGKey)pubPk.getKey(); ElGamalSecretBCPGKey elPriv = (ElGamalSecretBCPGKey)privPk; return new ElGamalPrivateKeyParameters(elPriv.getX(), new ElGamalParameters(elPub.getP(), elPub.getG())); case PGPPublicKey.ECDH: case PGPPublicKey.ECDSA: ECPublicBCPGKey ecPub = (ECPublicBCPGKey)pubPk.getKey(); ECSecretBCPGKey ecPriv = (ECSecretBCPGKey)privPk; X9ECParameters x9 = BcUtil.getX9Parameters(ecPub.getCurveOID()); return new ECPrivateKeyParameters(ecPriv.getX(), new ECNamedDomainParameters(ecPub.getCurveOID(), x9.getCurve(), x9.getG(), x9.getN(), x9.getH())); default: throw new PGPException("unknown public key algorithm encountered"); } } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Exception constructing key", e); } } }
mit
wavinsun/mUtils
MUtilsDemo/src/main/java/cn/mutils/app/demo/net/WeatherTask.java
5097
package cn.mutils.app.demo.net; import android.content.Context; import proguard.annotation.Keep; import proguard.annotation.KeepClassMembers; import cn.mutils.app.demo.net.WeatherTask.WeatherReq; import cn.mutils.app.demo.net.WeatherTask.WeatherRes; import cn.mutils.core.annotation.Format; import cn.mutils.core.annotation.Name; import cn.mutils.core.annotation.Primitive; import cn.mutils.core.annotation.PrimitiveType; import cn.mutils.core.time.DateTime; @SuppressWarnings("serial") public class WeatherTask extends BasicTask<WeatherReq, WeatherRes> { @Keep @KeepClassMembers public static class WeatherReq extends BasicRequest { protected String mCitypinyin; public String getCitypinyin() { return mCitypinyin; } public void setCitypinyin(String citypinyin) { mCitypinyin = citypinyin; } } @Keep @KeepClassMembers public static class WeatherRes extends BasicResponse { protected WeatherRet mRetData; public WeatherRet getRetData() { return mRetData; } public void setRetData(WeatherRet retData) { mRetData = retData; } } @Keep @KeepClassMembers public static class WeatherRet { protected String mCity; protected String mPinyin; protected String mCitycode; protected DateTime mDate; protected DateTime mTime; protected String mPostCode; protected double mLongitude; protected double mLatitude; protected String mAltitude; protected String mWeather; protected String mTemp; protected String mL_tmp; protected String mH_tmp; protected String mWD; protected String mWS; protected String mSunrise; protected String mSunset; public String getCity() { return mCity; } public void setCity(String city) { mCity = city; } public String getPinyin() { return mPinyin; } public void setPinyin(String pinyin) { mPinyin = pinyin; } public String getCitycode() { return mCitycode; } public void setCitycode(String citycode) { mCitycode = citycode; } @Primitive(PrimitiveType.STRING) @Format("yy-MM-dd") public DateTime getDate() { return mDate; } public void setDate(DateTime date) { mDate = date; } @Primitive(PrimitiveType.STRING) @Format("HH:mm") public DateTime getTime() { return mTime; } public void setTime(DateTime time) { mTime = time; } public String getPostCode() { return mPostCode; } public void setPostCode(String postCode) { mPostCode = postCode; } public double getLongitude() { return mLongitude; } public void setLongitude(double longitude) { mLongitude = longitude; } public double getLatitude() { return mLatitude; } public void setLatitude(double latitude) { mLatitude = latitude; } public String getAltitude() { return mAltitude; } public void setAltitude(String altitude) { mAltitude = altitude; } public String getWeather() { return mWeather; } public void setWeather(String weather) { mWeather = weather; } public String getTemp() { return mTemp; } public void setTemp(String temp) { mTemp = temp; } public String getL_tmp() { return mL_tmp; } public void setL_tmp(String l_tmp) { mL_tmp = l_tmp; } public String getH_tmp() { return mH_tmp; } public void setH_tmp(String h_tmp) { mH_tmp = h_tmp; } @Name("WD") public String getWD() { return mWD; } public void setWD(String WD) { mWD = WD; } @Name("WD") public String getWS() { return mWS; } public void setWS(String WS) { mWS = WS; } public String getSunrise() { return mSunrise; } public void setSunrise(String sunrise) { mSunrise = sunrise; } public String getSunset() { return mSunset; } public void setSunset(String sunset) { mSunset = sunset; } } @Override public void setContext(Context context) { super.setContext(context); setUrl("http://apis.baidu.com/apistore/weatherservice/weather"); } @Override protected void debugging(String event, String message) { super.debugging(event, message); } }
mit
joshgarde/SpongeAPI
src/test/java/org/spongepowered/api/util/event/factory/ClassGeneratorProviderTest.java
19628
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.util.event.factory; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.closeTo; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertThat; import com.google.common.base.Optional; import com.google.common.collect.Maps; import org.hamcrest.Matchers; import org.junit.Test; import org.spongepowered.api.util.annotation.TransformResult; import org.spongepowered.api.util.annotation.TransformWith; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.Nullable; public class ClassGeneratorProviderTest { private static final double ERROR = 0.03; private ClassGeneratorProvider createProvider() { return new ClassGeneratorProvider("org.spongepowered.test"); } @Test public void testCreate_ModifierMethodInterface() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<ModifiedMethodInterface> factory = provider.create(ModifiedMethodInterface.class, Object.class); Map<String, Object> values = Maps.newHashMap(); ModifiedMethodInterface result = factory.apply(values); assertNotSame(result.getNewModifierClass(), result); assertNotSame(result.getOtherModifierClass(), result); } @Test public void testCreate_Primitives() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<PrimitiveContainer> factory = provider.create(PrimitiveContainer.class, Object.class); Map<String, Object> values = Maps.newHashMap(); values.put("byte", (byte) 10); values.put("short", (short) 11); values.put("int", 12); values.put("long", 13L); values.put("float", (float) 14.5); values.put("double", 15.5); values.put("boolean", true); values.put("char", (char) 17); PrimitiveContainer result = factory.apply(values); assertThat(result.getByte(), is((byte) 10)); assertThat(result.getShort(), is((short) 11)); assertThat(result.getInt(), is(12)); assertThat(result.getLong(), is(13L)); assertThat((double) result.getFloat(), is(closeTo(14.5, ERROR))); assertThat(result.getDouble(), is(closeTo(15.5, ERROR))); assertThat(result.getBoolean(), is(true)); assertThat(result.getChar(), is((char) 17)); result.setByte((byte) 20); result.setShort((short) 21); result.setInt(22); result.setLong(23L); result.setFloat((float) 24.5); result.setDouble(25.5); result.setBoolean(false); result.setChar((char) 27); assertThat(result.getByte(), is((byte) 20)); assertThat(result.getShort(), is((short) 21)); assertThat(result.getInt(), is(22)); assertThat(result.getLong(), is(23L)); assertThat((double) result.getFloat(), is(closeTo(24.5, ERROR))); assertThat(result.getDouble(), is(closeTo(25.5, ERROR))); assertThat(result.getBoolean(), is(false)); assertThat(result.getChar(), is((char) 27)); } @Test public void testCreate_UnsetPrimitives() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<PrimitiveContainer> factory = provider.create(PrimitiveContainer.class, Object.class); PrimitiveContainer result = factory.apply(Collections.<String, Object>emptyMap()); assertThat(result.getByte(), is((byte) 0)); assertThat(result.getShort(), is((short) 0)); assertThat(result.getInt(), is(0)); assertThat(result.getLong(), is(0L)); assertThat((double) result.getFloat(), is(closeTo(0, ERROR))); assertThat(result.getDouble(), is(closeTo(0, ERROR))); assertThat(result.getBoolean(), is(false)); assertThat(result.getChar(), is((char) 0)); } @Test(expected = NullPointerException.class) public void testCreate_UnsetPrimitivesWithNonNull() throws Exception { ClassGeneratorProvider provider = createProvider(); provider.setNullPolicy(NullPolicy.NON_NULL_BY_DEFAULT); EventFactory<PrimitiveContainer> factory = provider.create(PrimitiveContainer.class, Object.class); factory.apply(Collections.<String, Object>emptyMap()); } @Test public void testCreate_BoxedPrimitives() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<BoxedPrimitiveContainer> factory = provider.create(BoxedPrimitiveContainer.class, Object.class); Map<String, Object> values = Maps.newHashMap(); values.put("byte", (byte) 10); values.put("short", (short) 11); values.put("int", 12); values.put("long", 13L); values.put("float", (float) 14.5); values.put("double", 15.5); values.put("boolean", true); values.put("char", (char) 17); BoxedPrimitiveContainer result = factory.apply(values); assertThat(result.getByte(), is((byte) 10)); assertThat(result.getShort(), is((short) 11)); assertThat(result.getInt(), is(12)); assertThat(result.getLong(), is(13L)); assertThat((double) result.getFloat(), is(closeTo(14.5, ERROR))); assertThat(result.getDouble(), is(closeTo(15.5, ERROR))); assertThat(result.getBoolean(), is(true)); assertThat(result.getChar(), is((char) 17)); result.setByte((byte) 20); result.setShort((short) 21); result.setInt(22); result.setLong(23L); result.setFloat((float) 24.5); result.setDouble(25.5); result.setBoolean(false); result.setChar((char) 27); assertThat(result.getByte(), is((byte) 20)); assertThat(result.getShort(), is((short) 21)); assertThat(result.getInt(), is(22)); assertThat(result.getLong(), is(23L)); assertThat((double) result.getFloat(), is(closeTo(24.5, ERROR))); assertThat(result.getDouble(), is(closeTo(25.5, ERROR))); assertThat(result.getBoolean(), is(false)); assertThat(result.getChar(), is((char) 27)); result.setByte(null); result.setShort(null); result.setInt(null); result.setLong(null); result.setFloat(null); result.setDouble(null); result.setBoolean(null); result.setChar(null); assertThat(result.getByte(), is(nullValue())); assertThat(result.getShort(), is(nullValue())); assertThat(result.getInt(), is(nullValue())); assertThat(result.getLong(), is(nullValue())); assertThat(result.getFloat(), is(nullValue())); assertThat(result.getDouble(), is(nullValue())); assertThat(result.getBoolean(), is(nullValue())); assertThat(result.getChar(), is(nullValue())); } @Test public void testCreate_Arrays() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<ArrayContainer> factory = provider.create(ArrayContainer.class, Object.class); Object object = new Object(); Map<String, Object> values = Maps.newHashMap(); values.put("bytes", new byte[]{1}); values.put("shorts", new short[]{2}); values.put("ints", new int[]{3}); values.put("longs", new long[]{4}); values.put("floats", new float[0]); values.put("doubles", new double[0]); values.put("booleans", new boolean[]{true}); values.put("chars", new char[]{'a'}); values.put("objects", new Object[]{object}); ArrayContainer result = factory.apply(values); assertThat(result.getBytes(), is(new byte[]{1})); assertThat(result.getShorts(), is(new short[]{2})); assertThat(result.getInts(), is(new int[]{3})); assertThat(result.getLongs(), is(new long[]{4})); assertThat(result.getFloats(), is(new float[0])); assertThat(result.getDoubles(), is(new double[0])); assertThat(result.getBooleans(), is(new boolean[]{true})); assertThat(result.getChars(), is(new char[]{'a'})); assertThat(result.getObjects(), is(new Object[]{object})); } @Test(expected = IllegalArgumentException.class) public void testCreate_ExcessParameters() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<ExcessParametersContainer> factory = provider.create(ExcessParametersContainer.class, Object.class); Map<String, Object> values = Maps.newHashMap(); values.put("name", "Jon"); values.put("age", 8); factory.apply(values); } @Test public void testCreate_Inheritance() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<ChildContainer> factory = provider.create(ChildContainer.class, Object.class); Map<String, Object> values = Maps.newHashMap(); values.put("name", "Eduardo"); values.put("age", 25); values.put("heatCapacity", 20); values.put("height", 6); values.put("temperature", 99); ChildContainer result = factory.apply(values); assertThat(result.getName(), is(equalTo("Eduardo"))); assertThat(result.getAge(), is(25)); assertThat(result.getHeatCapacity(), is(20)); assertThat(result.getHeight(), is(6)); assertThat(result.getTemperature(), is(99)); result.setName("Brandon"); result.setAge(30); assertThat(result.getName(), is(equalTo("Brandon"))); assertThat(result.getAge(), is(30)); assertThat(result.getHeatCapacity(), is(20)); assertThat(result.getHeight(), is(6)); assertThat(result.getTemperature(), is(99)); } @Test(expected = AbstractMethodError.class) public void testCreate_NonConformingAccessor() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<NonConformingAccessorContainer> factory = provider.create(NonConformingAccessorContainer.class, Object.class); NonConformingAccessorContainer result = factory.apply(Collections.<String, Object>emptyMap()); result.setName("Joey"); assertThat(result.getName(0), is(Matchers.nullValue())); // Nonconforming method } @Test(expected = AbstractMethodError.class) public void testCreate_NonConformingMutator() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<NonConformingMutatorContainer> factory = provider.create(NonConformingMutatorContainer.class, Object.class); NonConformingMutatorContainer result = factory.apply(Collections.<String, Object>emptyMap()); assertThat(result.getName(), is(Matchers.nullValue())); result.setName("Joey"); // Nonconforming method } @Test(expected = AbstractMethodError.class) public void testCreate_IncorrectMutator() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<IncorrectMutatorContainer> factory = provider.create(IncorrectMutatorContainer.class, Object.class); IncorrectMutatorContainer result = factory.apply(Collections.<String, Object>emptyMap()); assertThat(result.getAddress(), is(Matchers.nullValue())); result.setAddress(new ArrayList<Object>()); // Nonconforming method } @Test public void testCreate_AbstractImpl() throws Exception { ClassGeneratorProvider provider = createProvider(); EventFactory<AbstractImplContainer> factory = provider.create(AbstractImplContainer.class, AbstractImpl.class); Map<String, Object> values = Maps.newHashMap(); values.put("age", 56); AbstractImplContainer result = factory.apply(values); assertThat(result.getName(), is(equalTo("Bobby"))); assertThat(result.getAge(), is(56)); assertThat(((AbstractImpl) result).isCool(), is(true)); result.setName("Nathaniel"); assertThat(result.getName(), is(equalTo("Nathaniel Iceman"))); assertThat(result.getAge(), is(56)); assertThat(((AbstractImpl) result).isCool(), is(true)); } @Test(expected = IllegalArgumentException.class) public void testCreate_AbstractImplAndExcessParams() throws Exception { Map<String, Object> values = Maps.newHashMap(); values.put("name", "Vincent"); values.put("age", 56); values.put("cool", false); ClassGeneratorProvider provider = createProvider(); EventFactory<AbstractImplContainer> factory = provider.create(AbstractImplContainer.class, AbstractImpl.class); factory.apply(values); } @Test public void testCreate_OptionalGetter() { Map<String, Object> values = Maps.newHashMap(); values.put("name", Optional.fromNullable("MyName")); ClassGeneratorProvider provider = createProvider(); EventFactory<OptionalGetter> factory = provider.create(OptionalGetter.class, Object.class); OptionalGetter getter = factory.apply(values); assertThat(getter.getName().isPresent(), is(true)); assertThat(getter.getName().get(), is(Matchers.equalTo("MyName"))); getter.setName(null); assertThat(getter.getName().isPresent(), is(false)); getter.setName("Aaron"); assertThat(getter.getName().isPresent(), is(true)); assertThat(getter.getName().get(), is(Matchers.equalTo("Aaron"))); } @Test(expected = RuntimeException.class) public void testCreate_OverloadedSetter() { Map<String, Object> values = Maps.newHashMap(); values.put("object", ""); ClassGeneratorProvider provider = createProvider(); EventFactory<CovariantMethodOverrideInterface> factory = provider.create(CovariantMethodOverrideInterface.class, Object.class); CovariantMethodOverrideInterface overriden = factory.apply(values); overriden.setObject(new Object()); } public interface OptionalGetter { Optional<String> getName(); void setName(@Nullable String name); } public interface PrimitiveContainer { byte getByte(); void setByte(byte v); short getShort(); void setShort(short v); int getInt(); void setInt(int v); long getLong(); void setLong(long v); float getFloat(); void setFloat(float v); double getDouble(); void setDouble(double v); boolean getBoolean(); void setBoolean(boolean v); char getChar(); void setChar(char v); } public interface BoxedPrimitiveContainer { Byte getByte(); void setByte(Byte v); Short getShort(); void setShort(Short v); Integer getInt(); void setInt(Integer v); Long getLong(); void setLong(Long v); Float getFloat(); void setFloat(Float v); Double getDouble(); void setDouble(Double v); Boolean getBoolean(); void setBoolean(Boolean v); Character getChar(); void setChar(Character v); } public interface ArrayContainer { byte[] getBytes(); void setBytes(byte[] v); short[] getShorts(); void setShorts(short[] v); int[] getInts(); void setInts(int[] v); long[] getLongs(); void setLongs(long[] v); float[] getFloats(); void setFloats(float[] v); double[] getDoubles(); void setDoubles(double[] v); boolean[] getBooleans(); void setBooleans(boolean[] v); char[] getChars(); void setChars(char[] v); Object[] getObjects(); void setObjects(Object[] v); } public interface ExcessParametersContainer { String getName(); String setName(String name); } public interface Parent1AContainer { String getName(); void setName(String name); } public interface Parent1BContainer { int getAge(); int getHeatCapacity(); } public interface Parent2AContainer extends Parent1AContainer { int getAge(); int getHeight(); } public interface Parent2BContainer extends Parent1AContainer { void setAge(int age); } public interface ChildContainer extends Parent2AContainer, Parent2BContainer, Parent1BContainer { int getTemperature(); } public interface NonConformingAccessorContainer { String getName(int index); void setName(String name); } public interface NonConformingMutatorContainer { String getName(); String setName(String name); } public interface IncorrectMutatorContainer { List<?> getAddress(); void setAddress(ArrayList<?> address); } public interface AbstractImplContainer { String getName(); void setName(String name); int getAge(); void setAge(int age); } public static class AbstractImpl { private String name = "Bobby"; public String getName() { return this.name; } public void setName(String name) { this.name = name + " Iceman"; } public boolean isCool() { return true; } } public interface ModifiedMethodInterface { @TransformResult ModifierClass getNewModifierClass(); @TransformResult("foo") ModifierClass getOtherModifierClass(); } public class ModifierClass { @TransformWith public ModifierClass copy() { return new ModifierClass(); } @TransformWith("foo") public ModifierClass copy2() { return new ModifierClass(); } } public interface CovariantMethodInterface { Object getObject(); void setObject(Object object); } public interface CovariantMethodOverrideInterface extends CovariantMethodInterface { @Override String getObject(); void setObject(String object); } }
mit
kjorg50/Anypic-Android
src/com/parse/anypic/LoginActivity.java
4088
package com.parse.anypic; import java.util.Arrays; import java.util.List; import com.parse.ParseAnalytics; import com.parse.ParseFacebookUtils; import com.parse.ParseUser; import com.parse.ParseException; import com.parse.LogInCallback; import android.app.Activity; import android.app.ActionBar; import android.app.Dialog; import android.app.Fragment; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.os.Build; public class LoginActivity extends Activity { private Button loginButton; private Dialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); loginButton = (Button) findViewById(R.id.loginButton); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(AnypicApplication.TAG, "Login button clicked"); onLoginButtonClicked(); } }); // Check if there is a currently logged in user // and they are linked to a Facebook account. ParseUser currentUser = ParseUser.getCurrentUser(); if ((currentUser != null) && ParseFacebookUtils.isLinked(currentUser)) { // Go to the main photo list view activity showHomeListActivity(); } // For push notifications ParseAnalytics.trackAppOpened(getIntent()); } private void onLoginButtonClicked() { LoginActivity.this.progressDialog = ProgressDialog.show( LoginActivity.this, "", "Logging in...", true); List<String> permissions = Arrays.asList("public_profile","user_about_me","user_friends"); ParseFacebookUtils.logIn(permissions, this, new LogInCallback() { @Override public void done(ParseUser user, ParseException err) { LoginActivity.this.progressDialog.dismiss(); if (user == null) { Log.i(AnypicApplication.TAG, "Uh oh. The user cancelled the Facebook login."); } else if (user.isNew()) { Log.i(AnypicApplication.TAG, "User signed up and logged in through Facebook!"); showHomeListActivity(); } else { Log.i(AnypicApplication.TAG, "User logged in through Facebook!"); showHomeListActivity(); } } }); } /** * Used to provide "single sign-on" for users who don't have the Facebook app installed */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data); } private void showHomeListActivity() { //Log.i(AnypicApplication.TAG, "entered showHomeListActivity"); Intent intent = new Intent(this, HomeListActivity.class); startActivity(intent); finish(); // This closes the login screen so it's not on the back stack } /***************************************************************************/ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.login, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_login, container, false); return rootView; } } }
cc0-1.0
openhab/openhab2
bundles/org.openhab.binding.denonmarantz/src/main/java/org/openhab/binding/denonmarantz/internal/xml/entities/commands/AppCommandResponse.java
1244
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.denonmarantz.internal.xml.entities.commands; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Response to an {@link AppCommandRequest}, wraps a list of {@link CommandRx} * * @author Jeroen Idserda - Initial contribution */ @XmlRootElement(name = "rx") @XmlAccessorType(XmlAccessType.FIELD) public class AppCommandResponse { @XmlElement(name = "cmd") private List<CommandRx> commands = new ArrayList<>(); public AppCommandResponse() { } public List<CommandRx> getCommands() { return commands; } public void setCommands(List<CommandRx> commands) { this.commands = commands; } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.core/src/org/eclipse/jdt/internal/core/BinaryLambdaMethod.java
1192
/******************************************************************************* * Copyright (c) 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.core; import org.eclipse.jdt.core.IJavaElement; public class BinaryLambdaMethod extends LambdaMethod { BinaryLambdaMethod(JavaElement parent, String name, String key, int sourceStart, String [] parameterTypes, String [] parameterNames, String returnType, SourceMethodElementInfo elementInfo) { super(parent, name, key, sourceStart, parameterTypes, parameterNames, returnType, elementInfo); } /* * @see JavaElement#getPrimaryElement(boolean) */ public IJavaElement getPrimaryElement(boolean checkOwner) { return this; } /* * @see IMember#isBinary() */ public boolean isBinary() { return true; } }
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test963.java
260
package duplicates_out; public class A_test963 { void test() { new Object() { public void yes() { extracted(); } protected void extracted() { /*[*/System.out.println("hello world");/*]*/ } }; System.out.println("hello world"); } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.dwdpollenflug/src/main/java/org/openhab/binding/dwdpollenflug/internal/dto/DWDRegion.java
2600
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.dwdpollenflug.internal.dto; import static org.openhab.binding.dwdpollenflug.internal.DWDPollenflugBindingConstants.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.core.library.types.StringType; import org.openhab.core.types.State; import com.google.gson.annotations.SerializedName; /** * The {@link DWDRegion} class holds the internal data representation of each Region * * @author Johannes Ott - Initial contribution */ @NonNullByDefault public class DWDRegion { @SerializedName("region_id") public int regionID = 0; @SerializedName("region_name") public String regionName = ""; @SerializedName("partregion_id") public int partRegionID = 0; @SerializedName("partregion_name") public String partRegionName = ""; @SerializedName("Pollen") private @Nullable Map<String, DWDPollentypeJSON> pollen; public Map<String, String> getProperties() { Map<String, String> map = new HashMap<>(); map.put(PROPERTY_REGION_NAME, regionName); map.put(PROPERTY_PARTREGION_NAME, partRegionName); return Collections.unmodifiableMap(map); } public int getRegionID() { if (partRegionID > 0) { return partRegionID; } return regionID; } public Map<String, State> getChannelsStateMap() { final Map<String, DWDPollentypeJSON> localPollen = pollen; if (localPollen != null) { Map<String, State> map = new HashMap<>(); localPollen.forEach((k, jsonType) -> { final String pollenType = DWDPollenflugPollen.valueOf(k.toUpperCase()).getChannelName(); map.put(pollenType + "#" + CHANNEL_TODAY, new StringType(jsonType.today)); map.put(pollenType + "#" + CHANNEL_TOMORROW, new StringType(jsonType.tomorrow)); map.put(pollenType + "#" + CHANNEL_DAYAFTER_TO, new StringType(jsonType.dayAfterTomorrow)); }); return Collections.unmodifiableMap(map); } return Collections.emptyMap(); } }
epl-1.0
akervern/che
ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/command/toolbar/commands/button/AbstractMenuItem.java
826
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.command.toolbar.commands.button; import org.eclipse.che.ide.api.command.CommandImpl; import org.eclipse.che.ide.ui.menubutton.MenuItem; /** An abstract {@link MenuItem} for {@link ExecuteCommandButton}s. */ public abstract class AbstractMenuItem implements MenuItem { private final CommandImpl command; protected AbstractMenuItem(CommandImpl command) { this.command = command; } public CommandImpl getCommand() { return command; } }
epl-1.0
Maarc/windup-rulesets
rules-reviewed/technology-usage/tests/data/database/AnnotationSingleDs.java
380
import javax.annotation.sql.DataSourceDefinition; /** * @author <a href="mailto:dklingenberg@gmail.com">David Klingenberg</a> */ @DataSourceDefinition( name = "jdbc/single-DS", className="com.example.MyDataSource", portNumber=6689, serverName="example.com", user="lance", password="secret" ), public class AnnotationSingleDs { }
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_in/TestCStyleArrayRead.java
224
package object_in; public class TestCStyleArrayRead { public Object field[] = new Object[0]; public TestCStyleArrayRead() { field = new Object[0]; } public void basicRun() { System.err.println(field.length); } }
epl-1.0
ModelWriter/Source
plugins/eu.modelwriter.semantic.parser/src/synalp/generation/jeni/semantics/rules/Rules.java
505
package synalp.generation.jeni.semantics.rules; import java.util.ArrayList; import synalp.commons.semantics.Semantics; /** * A list of rules. The order matters. * @author Alexandre Denis */ @SuppressWarnings("serial") public class Rules extends ArrayList<Rule> { /** * Applies these rules to the given semantic input, one after the other. This method alters the * given Semantics. * @param input */ public void apply(Semantics input) { for(Rule rule : this) rule.apply(input); } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxAudioSink.java
5346
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.squeezebox.internal; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.openhab.binding.squeezebox.internal.handler.SqueezeBoxPlayerHandler; import org.openhab.core.audio.AudioFormat; import org.openhab.core.audio.AudioHTTPServer; import org.openhab.core.audio.AudioSink; import org.openhab.core.audio.AudioStream; import org.openhab.core.audio.FileAudioStream; import org.openhab.core.audio.FixedLengthAudioStream; import org.openhab.core.audio.URLAudioStream; import org.openhab.core.audio.UnsupportedAudioFormatException; import org.openhab.core.audio.UnsupportedAudioStreamException; import org.openhab.core.audio.utils.AudioStreamUtils; import org.openhab.core.library.types.PercentType; import org.openhab.core.library.types.StringType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This makes a SqueezeBox Player serve as an {@link AudioSink}- * * @author Mark Hilbush - Initial contribution * @author Mark Hilbush - Add callbackUrl */ public class SqueezeBoxAudioSink implements AudioSink { private final Logger logger = LoggerFactory.getLogger(SqueezeBoxAudioSink.class); private static final HashSet<AudioFormat> SUPPORTED_FORMATS = new HashSet<>(); private static final HashSet<Class<? extends AudioStream>> SUPPORTED_STREAMS = new HashSet<>(); // Needed because Squeezebox does multiple requests for the stream private static final int STREAM_TIMEOUT = 15; private String callbackUrl; static { SUPPORTED_FORMATS.add(AudioFormat.WAV); SUPPORTED_FORMATS.add(AudioFormat.MP3); SUPPORTED_STREAMS.add(FixedLengthAudioStream.class); SUPPORTED_STREAMS.add(URLAudioStream.class); } private AudioHTTPServer audioHTTPServer; private SqueezeBoxPlayerHandler playerHandler; public SqueezeBoxAudioSink(SqueezeBoxPlayerHandler playerHandler, AudioHTTPServer audioHTTPServer, String callbackUrl) { this.playerHandler = playerHandler; this.audioHTTPServer = audioHTTPServer; this.callbackUrl = callbackUrl; if (StringUtils.isNotEmpty(callbackUrl)) { logger.debug("SqueezeBox AudioSink created with callback URL {}", callbackUrl); } } @Override public String getId() { return playerHandler.getThing().getUID().toString(); } @Override public String getLabel(Locale locale) { return playerHandler.getThing().getLabel(); } @Override public void process(AudioStream audioStream) throws UnsupportedAudioFormatException, UnsupportedAudioStreamException { AudioFormat format = audioStream.getFormat(); if (!AudioFormat.WAV.isCompatible(format) && !AudioFormat.MP3.isCompatible(format)) { throw new UnsupportedAudioFormatException("Currently only MP3 and WAV formats are supported: ", format); } String url; if (audioStream instanceof URLAudioStream) { url = ((URLAudioStream) audioStream).getURL(); } else if (audioStream instanceof FixedLengthAudioStream) { // Since Squeezebox will make multiple requests for the stream, set a timeout on the stream url = audioHTTPServer.serve((FixedLengthAudioStream) audioStream, STREAM_TIMEOUT).toString(); if (AudioFormat.WAV.isCompatible(format)) { url += AudioStreamUtils.EXTENSION_SEPARATOR + FileAudioStream.WAV_EXTENSION; } else if (AudioFormat.MP3.isCompatible(format)) { url += AudioStreamUtils.EXTENSION_SEPARATOR + FileAudioStream.MP3_EXTENSION; } // Form the URL for streaming the notification from the OH2 web server // Use the callback URL if it is set in the binding configuration String host = StringUtils.isEmpty(callbackUrl) ? playerHandler.getHostAndPort() : callbackUrl; if (host == null) { logger.warn("Unable to get host/port from which to stream notification"); return; } url = host + url; } else { throw new UnsupportedAudioStreamException( "SqueezeBox can only handle URLAudioStream or FixedLengthAudioStreams.", null); } logger.debug("Processing audioStream {} of format {}", url, format); playerHandler.playNotificationSoundURI(new StringType(url)); } @Override public Set<AudioFormat> getSupportedFormats() { return SUPPORTED_FORMATS; } @Override public Set<Class<? extends AudioStream>> getSupportedStreams() { return SUPPORTED_STREAMS; } @Override public PercentType getVolume() { return playerHandler.getNotificationSoundVolume(); } @Override public void setVolume(PercentType volume) { playerHandler.setNotificationSoundVolume(volume); } }
epl-1.0
bmaggi/Papyrus-SysML11
plugins/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/DimensionEditHelperAdvice.java
2500
/***************************************************************************** * Copyright (c) 2010 CEA LIST. * * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *****************************************************************************/ package org.eclipse.papyrus.sysml.service.types.helper; import java.awt.Dimension; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.commands.ConfigureElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.papyrus.sysml.blocks.BlocksPackage; import org.eclipse.papyrus.uml.service.types.helper.advice.AbstractStereotypedElementEditHelperAdvice; import org.eclipse.papyrus.uml.service.types.utils.NamedElementHelper; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.uml2.uml.util.UMLUtil.StereotypeApplicationHelper; /** SysML {@link Dimension} edit helper advice */ public class DimensionEditHelperAdvice extends AbstractStereotypedElementEditHelperAdvice { /** Default constructor */ public DimensionEditHelperAdvice() { requiredProfiles.add(BlocksPackage.eINSTANCE); } /** Complete creation process by applying the expected stereotype */ @Override protected ICommand getBeforeConfigureCommand(final ConfigureRequest request) { return new ConfigureElementCommand(request) { @Override protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { NamedElement element = (NamedElement) request.getElementToConfigure(); if (element != null) { StereotypeApplicationHelper.INSTANCE.applyStereotype(element, BlocksPackage.eINSTANCE.getDimension()); // Set default name // Initialize the element name based on the created IElementType String initializedName = NamedElementHelper.getDefaultNameWithIncrementFromBase(BlocksPackage.eINSTANCE.getDimension().getName(), element.eContainer().eContents()); element.setName(initializedName); } return CommandResult.newOKCommandResult(element); } }; } }
epl-1.0
kumattau/JDTPatch
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java
8262
/******************************************************************************* * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.corext.refactoring.structure; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.WorkingCopyOwner; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.internal.corext.refactoring.CollectingSearchRequestor; import org.eclipse.jdt.internal.corext.util.SearchUtils; public class ReferenceFinderUtil { private ReferenceFinderUtil(){ //no instances } //----- referenced types - public static IType[] getTypesReferencedIn(IJavaElement[] elements, IProgressMonitor pm) throws JavaModelException { SearchMatch[] results= getTypeReferencesIn(elements, null, pm); Set<IJavaElement> referencedTypes= extractElements(results, IJavaElement.TYPE); return referencedTypes.toArray(new IType[referencedTypes.size()]); } public static IType[] getTypesReferencedIn(IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { SearchMatch[] results= getTypeReferencesIn(elements, owner, pm); Set<IJavaElement> referencedTypes= extractElements(results, IJavaElement.TYPE); return referencedTypes.toArray(new IType[referencedTypes.size()]); } private static SearchMatch[] getTypeReferencesIn(IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { List<SearchMatch> referencedTypes= new ArrayList<SearchMatch>(); pm.beginTask("", elements.length); //$NON-NLS-1$ for (int i = 0; i < elements.length; i++) { referencedTypes.addAll(getTypeReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1))); } pm.done(); return referencedTypes.toArray(new SearchMatch[referencedTypes.size()]); } private static List<SearchMatch> getTypeReferencesIn(IJavaElement element, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { CollectingSearchRequestor requestor= new CollectingSearchRequestor(); SearchEngine engine= owner != null ? new SearchEngine(owner) : new SearchEngine(); engine.searchDeclarationsOfReferencedTypes(element, requestor, pm); return requestor.getResults(); } //----- referenced fields ---- public static IField[] getFieldsReferencedIn(IJavaElement[] elements, IProgressMonitor pm) throws JavaModelException { SearchMatch[] results= getFieldReferencesIn(elements, null, pm); Set<IJavaElement> referencedFields= extractElements(results, IJavaElement.FIELD); return referencedFields.toArray(new IField[referencedFields.size()]); } public static IField[] getFieldsReferencedIn(IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { SearchMatch[] results= getFieldReferencesIn(elements, owner, pm); Set<IJavaElement> referencedFields= extractElements(results, IJavaElement.FIELD); return referencedFields.toArray(new IField[referencedFields.size()]); } private static SearchMatch[] getFieldReferencesIn(IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { List<SearchMatch> referencedFields= new ArrayList<SearchMatch>(); pm.beginTask("", elements.length); //$NON-NLS-1$ for (int i = 0; i < elements.length; i++) { referencedFields.addAll(getFieldReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1))); } pm.done(); return referencedFields.toArray(new SearchMatch[referencedFields.size()]); } private static List<SearchMatch> getFieldReferencesIn(IJavaElement element, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { CollectingSearchRequestor requestor= new CollectingSearchRequestor(); SearchEngine engine= owner != null ? new SearchEngine(owner) : new SearchEngine(); engine.searchDeclarationsOfAccessedFields(element, requestor, pm); return requestor.getResults(); } //----- referenced methods ---- public static IMethod[] getMethodsReferencedIn(IJavaElement[] elements, IProgressMonitor pm) throws JavaModelException { SearchMatch[] results= getMethodReferencesIn(elements, null, pm); Set<IJavaElement> referencedMethods= extractElements(results, IJavaElement.METHOD); return referencedMethods.toArray(new IMethod[referencedMethods.size()]); } public static IMethod[] getMethodsReferencedIn(IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { SearchMatch[] results= getMethodReferencesIn(elements, owner, pm); Set<IJavaElement> referencedMethods= extractElements(results, IJavaElement.METHOD); return referencedMethods.toArray(new IMethod[referencedMethods.size()]); } private static SearchMatch[] getMethodReferencesIn(IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { List<SearchMatch> referencedMethods= new ArrayList<SearchMatch>(); pm.beginTask("", elements.length); //$NON-NLS-1$ for (int i = 0; i < elements.length; i++) { referencedMethods.addAll(getMethodReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1))); } pm.done(); return referencedMethods.toArray(new SearchMatch[referencedMethods.size()]); } private static List<SearchMatch> getMethodReferencesIn(IJavaElement element, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException { CollectingSearchRequestor requestor= new CollectingSearchRequestor(); SearchEngine engine= owner != null ? new SearchEngine(owner) : new SearchEngine(); engine.searchDeclarationsOfSentMessages(element, requestor, pm); return requestor.getResults(); } public static ITypeBinding[] getTypesReferencedInDeclarations(MethodDeclaration[] methods) { Set<ITypeBinding> typesUsed= new HashSet<ITypeBinding>(); for (int i= 0; i < methods.length; i++) { typesUsed.addAll(getTypesUsedInDeclaration(methods[i])); } return typesUsed.toArray(new ITypeBinding[typesUsed.size()]); } //set of ITypeBindings public static Set<ITypeBinding> getTypesUsedInDeclaration(MethodDeclaration methodDeclaration) { if (methodDeclaration == null) return new HashSet<ITypeBinding>(0); Set<ITypeBinding> result= new HashSet<ITypeBinding>(); ITypeBinding binding= null; Type returnType= methodDeclaration.getReturnType2(); if (returnType != null) { binding = returnType.resolveBinding(); if (binding != null) result.add(binding); } for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) { binding = iter.next().getType().resolveBinding(); if (binding != null) result.add(binding); } for (Iterator<Type> iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) { binding= iter.next().resolveBinding(); if (binding != null) result.add(binding); } return result; } /// private helpers private static Set<IJavaElement> extractElements(SearchMatch[] searchResults, int elementType) { Set<IJavaElement> elements= new HashSet<IJavaElement>(); for (int i= 0; i < searchResults.length; i++) { IJavaElement el= SearchUtils.getEnclosingJavaElement(searchResults[i]); if (el.exists() && el.getElementType() == elementType) elements.add(el); } return elements; } }
epl-1.0
my76128/controller
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterActivator.java
10373
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.persist.impl.osgi; import com.google.common.annotations.VisibleForTesting; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.management.MBeanServer; import org.opendaylight.controller.config.persist.api.ConfigPusher; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory; import org.opendaylight.controller.netconf.persist.impl.ConfigPusherImpl; import org.opendaylight.controller.netconf.persist.impl.PersisterAggregator; import org.opendaylight.controller.netconf.util.CloseableUtil; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConfigPersisterActivator implements BundleActivator { private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterActivator.class); private static final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); public static final String MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY = "maxWaitForCapabilitiesMillis"; private static final long MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(2); public static final String CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY = "conflictingVersionTimeoutMillis"; private static final long CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(1); public static final String NETCONF_CONFIG_PERSISTER = "netconf.config.persister"; public static final String STORAGE_ADAPTER_CLASS_PROP_SUFFIX = "storageAdapterClass"; private List<AutoCloseable> autoCloseables; private volatile BundleContext context; ServiceRegistration<?> registration; @Override public void start(final BundleContext context) throws Exception { LOG.debug("ConfigPersister starting"); this.context = context; autoCloseables = new ArrayList<>(); PropertiesProviderBaseImpl propertiesProvider = new PropertiesProviderBaseImpl(context); final PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(propertiesProvider); autoCloseables.add(persisterAggregator); long maxWaitForCapabilitiesMillis = getMaxWaitForCapabilitiesMillis(propertiesProvider); List<ConfigSnapshotHolder> configs = persisterAggregator.loadLastConfigs(); long conflictingVersionTimeoutMillis = getConflictingVersionTimeoutMillis(propertiesProvider); LOG.debug("Following configs will be pushed: {}", configs); InnerCustomizer innerCustomizer = new InnerCustomizer(configs, maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis, persisterAggregator); OuterCustomizer outerCustomizer = new OuterCustomizer(context, innerCustomizer); new ServiceTracker<>(context, NetconfOperationServiceFactory.class, outerCustomizer).open(); } private long getConflictingVersionTimeoutMillis(PropertiesProviderBaseImpl propertiesProvider) { String timeoutProperty = propertiesProvider.getProperty(CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY); return timeoutProperty == null ? CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT : Long.valueOf(timeoutProperty); } private long getMaxWaitForCapabilitiesMillis(PropertiesProviderBaseImpl propertiesProvider) { String timeoutProperty = propertiesProvider.getProperty(MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY); return timeoutProperty == null ? MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT : Long.valueOf(timeoutProperty); } @Override public void stop(BundleContext context) throws Exception { synchronized(autoCloseables) { CloseableUtil.closeAll(autoCloseables); if (registration != null) { registration.unregister(); } this.context = null; } } @VisibleForTesting public static String getFilterString() { return "(&" + "(" + Constants.OBJECTCLASS + "=" + NetconfOperationServiceFactory.class.getName() + ")" + "(name" + "=" + "config-netconf-connector" + ")" + ")"; } class OuterCustomizer implements ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory> { private final BundleContext context; private final InnerCustomizer innerCustomizer; OuterCustomizer(BundleContext context, InnerCustomizer innerCustomizer) { this.context = context; this.innerCustomizer = innerCustomizer; } @Override public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) { LOG.trace("Got OuterCustomizer.addingService {}", reference); // JMX was registered, track config-netconf-connector Filter filter; try { filter = context.createFilter(getFilterString()); } catch (InvalidSyntaxException e) { throw new IllegalStateException(e); } new ServiceTracker<>(context, filter, innerCustomizer).open(); return null; } @Override public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) { } @Override public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) { } } class InnerCustomizer implements ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory> { private final List<ConfigSnapshotHolder> configs; private final PersisterAggregator persisterAggregator; private final long maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis; // This inner customizer has its filter to find the right operation service, but it gets triggered after any // operation service appears. This means that it could start pushing thread up to N times (N = number of operation services spawned in OSGi) private final AtomicBoolean alreadyStarted = new AtomicBoolean(false); InnerCustomizer(List<ConfigSnapshotHolder> configs, long maxWaitForCapabilitiesMillis, long conflictingVersionTimeoutMillis, PersisterAggregator persisterAggregator) { this.configs = configs; this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis; this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis; this.persisterAggregator = persisterAggregator; } @Override public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) { if(alreadyStarted.compareAndSet(false, true) == false) { //Prevents multiple calls to this method spawning multiple pushing threads return reference.getBundle().getBundleContext().getService(reference); } LOG.trace("Got InnerCustomizer.addingService {}", reference); NetconfOperationServiceFactory service = reference.getBundle().getBundleContext().getService(reference); LOG.debug("Creating new job queue"); final ConfigPusherImpl configPusher = new ConfigPusherImpl(service, maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis); LOG.debug("Configuration Persister got {}", service); LOG.debug("Context was {}", context); LOG.debug("Registration was {}", registration); final Thread pushingThread = new Thread(new Runnable() { @Override public void run() { try { if(configs != null && !configs.isEmpty()) { configPusher.pushConfigs(configs); } if(context != null) { registration = context.registerService(ConfigPusher.class.getName(), configPusher, null); configPusher.process(autoCloseables, platformMBeanServer, persisterAggregator); } else { LOG.warn("Unable to process configs as BundleContext is null"); } } catch (InterruptedException e) { LOG.info("ConfigPusher thread stopped",e); } LOG.info("Configuration Persister initialization completed."); } }, "config-pusher"); synchronized (autoCloseables) { autoCloseables.add(new AutoCloseable() { @Override public void close() { pushingThread.interrupt(); } }); } pushingThread.start(); return service; } @Override public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) { LOG.trace("Got InnerCustomizer.modifiedService {}", reference); } @Override public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) { LOG.trace("Got InnerCustomizer.removedService {}", reference); } } }
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test4/in/C.java
75
package p3; import p1.A; class C { C() { A a= new A(); a.mA1(); } }
epl-1.0
devjunix/libjt400-java
src/com/ibm/as400/vaccess/SQLQueryWherePane.java
51527
/////////////////////////////////////////////////////////////////////////////// // // JTOpen (IBM Toolbox for Java - OSS version) // // Filename: SQLQueryWherePane.java // // The source code contained herein is licensed under the IBM Public License // Version 1.0, which has been approved by the Open Source Initiative. // Copyright (C) 1997-2000 International Business Machines Corporation and // others. All rights reserved. // /////////////////////////////////////////////////////////////////////////////// package com.ibm.as400.vaccess; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Types; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; /** The SQLQueryWherePane class represents a panel which allows a user to dynamically build the SELECT portion of an SQL query. This panel is used for a page of the SQLQueryBuilderPane notebook. **/ class SQLQueryWherePane extends SQLQueryFieldsPane { private static final String copyright = "Copyright (C) 1997-2000 International Business Machines Corporation and others."; // The variables and methods which have private commented out // had to be made package scope since currently Internet Explorer // does not allow inner class to access private items in their // containing class. // GUI components /*private*/ DoubleClickList notList_; /*private*/ DoubleClickList functionList_; /*private*/ DoubleClickList testList_; /*private*/ DoubleClickList otherList_; /*private*/ SQLQueryClause clause_; // Constants for SQL syntax. Because these strings represent // SQL syntax, they are not translated. // Constants for functions. private static final String FCN_CAST_ = "CAST"; private static final String FCN_CHAR_ = "CHAR"; private static final String FCN_CURRENT_ = "CURRENT"; private static final String FCN_DATE_ = "DATE"; private static final String FCN_DAY_ = "DAY"; private static final String FCN_HOUR_ = "HOUR"; private static final String FCN_LENGTH_ = "LENGTH"; private static final String FCN_MINUTE_ = "MINUTE"; private static final String FCN_MONTH_ = "MONTH"; private static final String FCN_SECOND_ = "SECOND"; private static final String FCN_SUBSTR_ = "SUBSTRING"; private static final String FCN_TIME_ = "TIME"; private static final String FCN_TIMESTAMP_ = "TIMESTAMP"; private static final String FCN_UPPER_ = "UPPER"; private static final String FCN_YEAR_ = "YEAR"; // Constants for tests. private static final String TEST_BETWEEN_ = "BETWEEN"; private static final String TEST_IN_ = "IN"; private static final String TEST_NOT_NULL_ = "IS NOT NULL"; private static final String TEST_NULL_ = "IS NULL"; private static final String TEST_LIKE_ = "LIKE"; // Is NOT in affect for this expression. private boolean notInEffect_ = false; // Private variables used by internal methods. These are // instance variables because they are used in several places. /*private*/ JDialog dialog; /*private*/ boolean pane1Active; /*private*/ JComboBox list1, list2, list3; /*private*/ JTextField textField1, textField2; private static final String [] notChoices = {"NOT"}; private static final String [] functionChoices = {FCN_CAST_, FCN_CHAR_, FCN_CURRENT_, FCN_DATE_, FCN_DAY_, FCN_HOUR_, FCN_LENGTH_, FCN_MINUTE_, FCN_MONTH_, FCN_SECOND_, FCN_SUBSTR_, FCN_TIME_, FCN_TIMESTAMP_, FCN_UPPER_, FCN_YEAR_}; private static final String [] testChoices = {"=", "<>", "<", ">", "<=", ">=", TEST_BETWEEN_, TEST_IN_, TEST_NOT_NULL_, TEST_NULL_, TEST_LIKE_}; private static final String [] otherChoices = {"AND", "OR"}; /** Constructs a SQLQueryWherePane object. Note <i>init</i> must be called to build the GUI contents. @param parent The parent of this panel. **/ public SQLQueryWherePane (SQLQueryBuilderPane parent) { super(parent); } /** Enables the appropriate controls after a function is chosen. **/ void functionComplete() { // Make appropriate controls available. fields_.setEnabled(false); notList_.setEnabled(false); functionList_.setEnabled(false); testList_.setEnabled(true); } /** Called when an item in the function list is double-clicked on. The request is processed, requesting additional information from the user if needed, and the completed item is added to the clause. @param item The item that was chosen. **/ /*private*/ void functionPicked(String item) { // Variables used when putting up an additional dialog. String[] choices; // choices for the user Object choice; // what the user selected // ------------------------- // FCN_CURRENT_ // ------------------------- // Current requires a second value for date, time or timestamp. if (item.equals(FCN_CURRENT_)) { choices = new String[]{"DATE", "TIME", "TIMESTAMP"}; choice = JOptionPane.showInputDialog(this, // parent item, // message item, // title JOptionPane.QUESTION_MESSAGE, // message type null, // icon choices, // choices choices[0]); // initial choice if (choice == null) // null means they cancelled return; String text = "(CURRENT " + choice ; clause_.appendText(text); functionComplete(); } // ------------------------- // FCN_CAST_ // ------------------------- // On AS400, cast is only valid at V4R2 or later. // Cast requires a field name and an SQL type. else if (item.equals(FCN_CAST_)) { choices = getFieldNames(); if (choices.length ==0) { // put up error message and return noFields(item); return; } list1 = new JComboBox(); for (int i=0; i< choices.length; ++i) list1.addItem(choices[i]); JLabel asLabel = new JLabel("AS"); list2 = new JComboBox(); list2.setEditable(true); // allow users to change type - ie CHAR(10) list2.addItem("CHARACTER()"); list2.addItem("DATE"); list2.addItem("DECIMAL(,)"); list2.addItem("DOUBLE"); list2.addItem("FLOAT()"); list2.addItem("GRAPHIC()"); list2.addItem("INTEGER"); list2.addItem("NUMERIC(,)"); list2.addItem("REAL"); list2.addItem("SMALLINT"); list2.addItem("TIME"); list2.addItem("TIMESTAMP"); list2.addItem("VARCHAR()"); list2.addItem("VARGRAPHIC()"); JPanel choicePanel = new JPanel(); choicePanel.add(list1); choicePanel.add(asLabel); choicePanel.add(list2); // Create buttons JButton okButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_OK")); final String fitem = item; okButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ev) { String choice1 = (String)list1.getSelectedItem(); String choice2 = (String)list2.getSelectedItem(); if (choice2 == null || choice2.equals("")) { // put up error message and return (leave dialog up) JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_VALUE_MISSING") + " AS", // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type return; } if (choice2.endsWith("()")) { // Create dialog for getting one length String type = choice2.substring(0,choice2.length()-2); boolean required = type.startsWith("VAR"); String prompt2; if (required) prompt2 = ResourceLoader.getQueryText("DBQUERY_TEXT_LENGTH_REQ"); else prompt2 = ResourceLoader.getQueryText("DBQUERY_TEXT_LENGTH"); boolean error = true; while (error) { String result = JOptionPane.showInputDialog(parent_, // parent prompt2, // message type + " " + ResourceLoader.getQueryText("DBQUERY_TITLE_LENGTH"), // title JOptionPane.QUESTION_MESSAGE ); // message type if (result.equals("")) { if (required) { // put up error message JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_INVALID_INT_VALUE3"), // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type } else { choice2 = type; // use default length, remove parens error = false; } } else { // verify input is a number try { int i = Integer.parseInt(result); if (i > 0) error = false; } catch(NumberFormatException e) {} if (error) { // put up error message JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_INVALID_INT_VALUE3"), // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type } else choice2 = type + "(" + result + ")"; // add length } } } else if (choice2.endsWith("(,)")) { // Create dialog for getting the total length (precision). String type = choice2.substring(0,choice2.length()-3); boolean error = true; while (error) { String result = JOptionPane.showInputDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_TEXT_LENGTH_TOTAL"), // message type + " " + ResourceLoader.getQueryText("DBQUERY_TITLE_LENGTH"), // title JOptionPane.QUESTION_MESSAGE ); // message type if (result.equals("")) { choice2 = type; // use default length, remove parens error = false; } else { // verify input is a number try { int i = Integer.parseInt(result); if (i >= 0) error = false; } catch(NumberFormatException e) {} if (error) { // put up error message JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_INVALID_INT_VALUE3"), // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type } else { choice2 = type + "(" + result + ")"; // add length // Put up second dialog asking for scale (decimal positions) error = true; while (error) { String result2 = JOptionPane.showInputDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_TEXT_LENGTH_DECIMAL"), // message type + " " + ResourceLoader.getQueryText("DBQUERY_TITLE_LENGTH"), // title JOptionPane.QUESTION_MESSAGE ); // message type if (result2 == null) { choice2 = type + "(" + result + ")"; // add one length error = false; } else if (result2.equals("")) { choice2 = type + "(" + result + ")"; // add one length error = false; } else { // verify input is a number try { int i = Integer.parseInt(result2); if (i >= 0) error = false; } catch(NumberFormatException e) {} if (error) { // put up error message JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_INVALID_INT_VALUE3"), // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type } else choice2 = type + "(" + result + "," + result2 + ")"; // add two lengths } } } } } } String text; /*if (choice2.indexOf("GRAPHIC") == 0 || choice2.indexOf("VARGRAPHIC") == 0) // cast to graphic requires CCSID 13488 text = "(" + fitem + "(" + choice1 + " AS " + choice2 + " CCSID 13488)"; else*/ text = "(" + fitem + "(" + choice1 + " AS " + choice2 + ")"; clause_.appendText(text); dialog.dispose(); functionComplete(); } } // end of ActionListenerAdapter ); JButton cancelButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_CANCEL")); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { dialog.dispose(); } } ); JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); dialog = new JDialog(VUtilities.getFrame(this), item, true); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add("Center",new LabelledComponent(ResourceLoader.getQueryText("DBQUERY_TEXT_CHOOSE2") + " " + item + "()", choicePanel, false)); dialog.getContentPane().add("South", buttonPanel); dialog.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent ev) { dialog.dispose(); } } ); dialog.pack(); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } // ------------------------- // FCN_CHAR_ // ------------------------- // Char requires a date, time or timestamp field, and then an // optional SQL datetime format. else if (item.equals(FCN_CHAR_)) { choices = getDateTimeFieldNames(); if (choices.length ==0) { // put up error message and return noFields(item); return; } list1 = new JComboBox(); for (int i=0; i< choices.length; ++i) list1.addItem(choices[i]); list2 = new JComboBox(); list2.addItem(" "); // Blank for no choice list2.addItem("ISO"); list2.addItem("USA"); list2.addItem("EUR"); list2.addItem("JIS"); // Create buttons JButton okButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_OK")); final String fitem = item; okButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ev) { String choice1 = (String)list1.getSelectedItem(); String choice2 = (String)list2.getSelectedItem(); String text; if (choice2.equals(" ")) text = "(" + fitem + "(" + choice1 + ")"; else text = "(" + fitem + "(" + choice1 + ", " + choice2 + ")"; clause_.appendText(text); dialog.dispose(); functionComplete(); } } // end of ActionListenerAdapter ); JButton cancelButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_CANCEL")); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { dialog.dispose(); } } ); JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); dialog = new JDialog(VUtilities.getFrame(this), item, true); dialog.getContentPane().setLayout(new BorderLayout()); JPanel listPanel = new JPanel(); listPanel.add(list1); listPanel.add(list2); dialog.getContentPane().add("Center", new LabelledComponent(ResourceLoader.getQueryText("DBQUERY_TEXT_CHOOSE2") + " " + item + "()", listPanel, false)); dialog.getContentPane().add("South", buttonPanel); dialog.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent ev) {dialog.dispose();} } ); dialog.pack(); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } // ------------------------- // FCN_SUBSTR_ // ------------------------- // Substring requires a character field name, start index, and stop index. else if (item.equals(FCN_SUBSTR_)) { // Substring requires a character field name and then two numbers // for the start and end. We use the FROM/FOR syntax, so it // looks like this: "SUBSTRING(<field> FROM 2 FOR 6) // The FOR part is optional. choices = getCharacterFieldNames(); if (choices.length ==0) { // put up error message and return noFields(item); return; } list1 = new JComboBox(); for (int i=0; i< choices.length; ++i) list1.addItem(choices[i]); final String fieldFROM = "FROM"; final String fieldFOR = "FOR"; JLabel fromLabel = new JLabel(fieldFROM); JLabel forLabel = new JLabel(fieldFOR); textField1 = new JTextField("1", 3); textField2 = new JTextField(3); JPanel choicePanel = new JPanel(); choicePanel.add(list1); choicePanel.add(fromLabel); choicePanel.add(textField1); choicePanel.add(forLabel); choicePanel.add(textField2); // Create buttons JButton okButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_OK")); final String fitem = item; okButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ev) { String choice1 = (String)list1.getSelectedItem(); String choice2 = textField1.getText().trim(); String choice3 = textField2.getText().trim(); String text; if (choice2.equals("")) { // put up error message and return (leave dialog up) JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_VALUE_MISSING") + " " + fieldFROM, // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type return; } else { // verify input is a number boolean error = false; try { int i = Integer.parseInt(choice2); if (i<1) error = true; } catch(NumberFormatException e) {error = true;} if (error) { // put up error message and return (leave dialog up) JOptionPane.showMessageDialog(parent_, // parent fieldFROM + " " + ResourceLoader.getQueryText("DBQUERY_MESSAGE_INVALID_INT_VALUE2"), // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type return; } } if (choice3.equals("")) text = fitem + "(" + choice1 + " FROM " + choice2 + ")"; else { // verify input is a number boolean error = false; try { int i = Integer.parseInt(choice3); if (i<0) error = true; } catch(NumberFormatException e) {error = true;} if (error) { // put up error message and return (leave dialog up) JOptionPane.showMessageDialog(parent_, // parent fieldFOR + " " + ResourceLoader.getQueryText("DBQUERY_MESSAGE_INVALID_INT_VALUE"), // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type return; } text = fitem + "(" + choice1 + " FROM " + choice2 + " FOR " + choice3 + ")"; } clause_.appendText("(" + text); dialog.dispose(); functionComplete(); } } // end of ActionListenerAdapter ); JButton cancelButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_CANCEL")); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { dialog.dispose(); } } ); JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); dialog = new JDialog(VUtilities.getFrame(this), item, true); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add("Center",new LabelledComponent(ResourceLoader.getQueryText("DBQUERY_TEXT_CHOOSE2") + " " + item + "()", choicePanel, false)); dialog.getContentPane().add("South", buttonPanel); dialog.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent ev) {dialog.dispose();} } ); dialog.pack(); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } // ------------------------- // FCN_TIMESTAMP_ // ------------------------- // Timestamp requires either a timestamp field or a date field and // a time field. else if (item.equals(FCN_TIMESTAMP_)) { // Make two panels, one for choosing a 1 date and 1 time field, // the other for choosing a timestamp field. Have radio // buttons to switch between the panes. Disable the pane and // button if the appropriate fields do not exist. // Get fields for each list. String[] dateFields = getFieldNamesOfType(Types.DATE); String[] timeFields = getFieldNamesOfType(Types.TIME); String[] timestampFields = getFieldNamesOfType(Types.TIMESTAMP); // Verify there are fields appropriate for this function boolean pane1valid = !(dateFields.length == 0 || timeFields.length == 0); boolean pane2valid = !(timestampFields.length == 0); if (!pane1valid && !pane2valid) { // put up error message and return noFields(item); return; } dialog = new JDialog(VUtilities.getFrame(this), item, true); dialog.getContentPane().setLayout(new BorderLayout()); JPanel choicePane = new JPanel(new BorderLayout()); pane1Active = pane1valid; // switch for which pane active; JRadioButton pane1Button=null, pane2Button; // Make first panel for date and time fields if (pane1valid) { JPanel pane1 = new JPanel(new BorderLayout()); pane1.setBorder(new CompoundBorder( new EmptyBorder(10,10,10,10), new CompoundBorder(LineBorder.createBlackLineBorder(), new EmptyBorder(10,10,10,10)))); if (pane2valid) // need buttons only if both panes valid { pane1Button = new JRadioButton( ResourceLoader.getQueryText("DBQUERY_BUTTON_TIMESTAMP_2_FIELDS"), true); pane1Button.setBorder(new EmptyBorder(0,10,10,10)); pane1Button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { list1.setEnabled(true); list2.setEnabled(true); list3.setEnabled(false); pane1Active = true; } } ); pane1.add("North", pane1Button); } list1 = new JComboBox(); for (int i=0; i<dateFields.length; ++i) list1.addItem(dateFields[i]); list2 = new JComboBox(); for (int i=0; i<timeFields.length; ++i) list2.addItem(timeFields[i]); Box listpane = Box.createHorizontalBox(); listpane.add(list1); listpane.add(list2); pane1.add("Center", listpane); choicePane.add("West",pane1); } // Make second panel for timestamp fields if (pane2valid) { JPanel pane2 = new JPanel(new BorderLayout()); pane2.setBorder(new CompoundBorder( new EmptyBorder(10,10,10,10), new CompoundBorder(LineBorder.createBlackLineBorder(), new EmptyBorder(10,10,10,10)))); if (pane1valid) // need buttons only if both panes valid { pane2Button = new JRadioButton( ResourceLoader.getQueryText("DBQUERY_BUTTON_TIMESTAMP_1_FIELDS"), false); pane2Button.setBorder(new EmptyBorder(0,10,10,10)); ButtonGroup group = new ButtonGroup(); group.add(pane1Button); group.add(pane2Button); pane2Button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { list1.setEnabled(false); list2.setEnabled(false); list3.setEnabled(true); pane1Active = false; } } ); pane2.add("North", pane2Button); } list3 = new JComboBox(); for (int i=0; i<timestampFields.length; ++i) list3.addItem(timestampFields[i]); pane2.add("Center", list3); choicePane.add("East",pane2); } // diable list in pane 2 if have 2 panes if (pane1valid && pane2valid) list3.setEnabled(false); // Create buttons JButton okButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_OK")); final String fitem = item; okButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ev) { String text; if (pane1Active) { String choice1 = (String)list1.getSelectedItem(); String choice2 = (String)list2.getSelectedItem(); text = "(" + fitem + "(" + choice1 + ", " + choice2 + ")"; } else // pane2 active { String choice1 = (String)list3.getSelectedItem(); text = "(" + fitem + "(" + choice1 + ")"; } clause_.appendText(text); dialog.dispose(); functionComplete(); } } // end of ActionListenerAdapter ); JButton cancelButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_CANCEL")); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { dialog.dispose(); } } ); JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); dialog.getContentPane().add("South", buttonPanel); dialog.getContentPane().add("Center", choicePane); dialog.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent ev) {dialog.dispose();} } ); dialog.pack(); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } // ------------------------- // remaining functions // ------------------------- // Remaining functions all require a field name. // Which fields are valid depends on the function. else { // Show dialog to have user choose field. if (item.equals(FCN_DATE_) || item.equals(FCN_DAY_) || item.equals(FCN_MONTH_) || item.equals(FCN_YEAR_)) { // only date and timestamp fields are valid choices = getDateFieldNames(); } else if (item.equals(FCN_MINUTE_) || item.equals(FCN_SECOND_) || item.equals(FCN_HOUR_) || item.equals(FCN_TIME_)) { // all time and timestamp fields are valid choices = getTimeFieldNames(); } else if (item.equals(FCN_UPPER_)) { // all character fields are valid choices = getCharacterFieldNames(); } else // must be FCN_LENGTH // all fields are valid choices = getFieldNames(); if (choices.length ==0) { // put up error message and return noFields(item); return; } choice = JOptionPane.showInputDialog(this, // parent ResourceLoader.getQueryText("DBQUERY_TEXT_CHOOSE") + " " + item + "()", // message item, // title JOptionPane.QUESTION_MESSAGE, // message type null, // icon choices, // choices choices[0]); // initial choice if (choice == null) // null means they cancelled return; clause_.appendText("(" + item + "(" + choice + ")"); functionComplete(); } } /** Returns the sql clause for this panel. @return The sql clause for this panel. **/ public String getClause() { if (clause_ == null) return null; return clause_.getText(); } /** Puts up an error message which tells the user there are no fields that are suitable for the chosen function. @param function Name of the function attempting to be used. **/ private void noFields(String function) { JOptionPane.showMessageDialog(this, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_NO_FIELDS") + " " + function + "()", // message function + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type } /** Called when an item in the not list is double-clicked on. The request is processed, the completed item is added to the clause. @param item The item that was chosen. **/ /*private*/ void notPicked(String item) { notInEffect_ = true; // Add text to clause clause_.appendText("(" + item); // Make appropriate controls available. notList_.setEnabled(false); } /** Called when an item in the other list is double-clicked on. The request is processed, the completed item is added to the clause. @param item The item that was chosen. **/ /*private*/ void otherPicked(String item) { // Add text to clause clause_.appendText(item); // Make appropriate controls available. fields_.setEnabled(true); notList_.setEnabled(true); functionList_.setEnabled(true); otherList_.setEnabled(false); notInEffect_ = false; } /** Adds the field to the clause. @param index Index of the row in the table that was clicked upon. **/ protected void rowPicked(int index) { // Add the field to the clause with a leading left paren clause_.appendText("(" + fieldName(index)); // Make appropriate controls available. fields_.setEnabled(false); notList_.setEnabled(false); functionList_.setEnabled(false); testList_.setEnabled(true); } /** Builds the panel GUI components and sets up connections between the components by using listeners. **/ protected void setupPane() { super.setupPane(); // List box for not. notList_ = new DoubleClickList(notChoices); notList_.setVisibleRowCount(1); //@B0A notList_.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent event) { notPicked((String)event.getItem()); } }); // Functions list. functionList_ = new DoubleClickList(functionChoices); functionList_.setVisibleRowCount(5); //@B0A - have more than 5 elements, but do this for consistency with other panes. functionList_.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent event) { functionPicked((String)event.getItem()); } }); // Test list. testList_ = new DoubleClickList(testChoices); testList_.setEnabled(false); testList_.setVisibleRowCount(5); //@B0A - have more than 5 elements, but do this for consistency with other panes. testList_.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent event) { testPicked((String)event.getItem()); } }); // Other list. otherList_ = new DoubleClickList(otherChoices); otherList_.setEnabled(false); otherList_.setVisibleRowCount(2); //@B0A otherList_.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent event) { otherPicked((String)event.getItem()); } }); // Layout middle row. Box middleRow = Box.createHorizontalBox(); middleRow.add(new LabelledComponent("DBQUERY_LABEL_NOT", notList_)); middleRow.add(new LabelledComponent("DBQUERY_LABEL_FUNCTIONS", functionList_)); middleRow.add(new LabelledComponent("DBQUERY_LABEL_TEST", testList_)); middleRow.add(new LabelledComponent("DBQUERY_LABEL_OTHER", otherList_)); // Clause. clause_ = new SQLQueryClause(5); // Layout overall. Box overallBox = Box.createVerticalBox(); overallBox.add(fields_); overallBox.add(middleRow); overallBox.add(new LabelledComponent("DBQUERY_LABEL_CLAUSE_WHERE", new ScrollingTextPane(clause_))); setLayout(new BorderLayout()); add("Center", overallBox); } /** Called when an item in the test list is double-clicked on. The request is processed, the completed item is added to the clause. @param item The item that was chosen. **/ /*private*/ void testPicked(String item) { String text = null; // ------------------------- // TEST_BETWEEN_ // ------------------------- // BETWEEN requires 2 inputs, either field names or a // constant. if (item.equals(TEST_BETWEEN_)) { String[] choices = getFieldNames(); list1 = new JComboBox(); list2 = new JComboBox(); list1.addItem(""); // Add empty items so user may type in constant. list2.addItem(""); for (int i=0; i< choices.length; ++i) { list1.addItem(choices[i]); list2.addItem(choices[i]); } list1.setEditable(true); list2.setEditable(true); JLabel andLabel = new JLabel("AND"); andLabel.setBorder(new EmptyBorder(10,10,10,10)); JPanel choicePane = new JPanel(); choicePane.add(list1); choicePane.add(andLabel); choicePane.add(list2); // Create buttons JButton okButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_OK")); final String fitem = item; okButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ev) { String choice1 = ((String)list1.getSelectedItem()); String choice2 = ((String)list2.getSelectedItem()); if (choice1 != null) choice1 = choice1.trim(); if (choice2 != null) choice2 = choice2.trim(); if (choice1 == null || choice2 == null || choice1.equals("") || choice2.equals("")) { // put up error message and return (leave dialog up) JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_VALUE_MISSING") + " " + fitem, // message fitem + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type return; } // Add to clause if (notInEffect_) clause_.appendText(fitem + " " + choice1 + " AND " + choice2 + "))"); else clause_.appendText(fitem + " " + choice1 + " AND " + choice2 + ")"); // Make appropriate controls available. otherList_.setEnabled(true); testList_.setEnabled(false); // End dialog dialog.dispose(); } } // end of ActionListenerAdapter ); JButton cancelButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_CANCEL")); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { dialog.dispose(); } } ); JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); dialog = new JDialog(VUtilities.getFrame(this), item, true); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add("Center",new LabelledComponent(ResourceLoader.getQueryText("DBQUERY_TEXT_CHOOSE3") + " " + item, choicePane, false)); dialog.getContentPane().add("South", buttonPanel); dialog.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent ev) {dialog.dispose();} } ); dialog.pack(); dialog.setLocationRelativeTo(this); // @A1 - Set default focus in JPanel-JComboBox-JTextField dialog.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent event) { JComponent comp, subcomp; for (int x=0; x<dialog.getContentPane().getComponentCount(); x++) { comp = (JComponent) dialog.getContentPane().getComponent(x); if (comp instanceof JPanel) { // choicePane for (int y=0; y<comp.getComponentCount(); y++) { subcomp = (JComponent) comp.getComponent(y); if (subcomp instanceof JComboBox) // list1 { for (int z=0; z<subcomp.getComponentCount(); z++) { if (subcomp.getComponent(z) instanceof JTextField) { subcomp.getComponent(z).requestFocus(); return; } } return; } } return; } } } } ); dialog.setVisible(true); } // ------------------------- // TEST_IN_ TEST_LIKE_ // ------------------------- // IN and LIKE require a single constant input. else if (item.equals(TEST_IN_) || item.equals(TEST_LIKE_)) { boolean error = true; String result = ""; while (error) { result = JOptionPane.showInputDialog(this, // parent ResourceLoader.getQueryText("DBQUERY_TEXT_TEST_CONSTANT") + " " + item, // message ResourceLoader.getQueryText("DBQUERY_TITLE_CONSTANT"), // title JOptionPane.QUESTION_MESSAGE); // message type if (result == null) // null means they cancelled return; if (result.equals("")) { // put up error message JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_VALUE_MISSING") + " " + item, // message item + "() " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type } else error = false; } if (item.equals(TEST_IN_)) text = item + " (" + result + ")"; else // TEST_LIKE_ text = item + " '" + result + "'"; } // ------------------------- // TEST_NOT_NULL_ TEST_NULL_ // ------------------------- // IS (NOT) NULL needs no further input. else if (item.equals(TEST_NOT_NULL_) || item.equals(TEST_NULL_)) { text = item; } // ------------------------- // comparison operators // ------------------------- // Remaining functions (comparison operators) require // one input which can be a field name or a constant expression. else { String[] choices = getFieldNames(); list1 = new JComboBox(); list1.addItem(""); // blank line for constant for (int i=0; i< choices.length; ++i) list1.addItem(choices[i]); list1.setEditable(true); // Create buttons JButton okButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_OK")); final String fitem = item; okButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ev) { String choice1 = ((String)list1.getSelectedItem()); if (choice1 != null) choice1 = choice1.trim(); if (choice1 == null || choice1.equals("")) { // put up error message and return (leave dialog up) JOptionPane.showMessageDialog(parent_, // parent ResourceLoader.getQueryText("DBQUERY_MESSAGE_VALUE_MISSING") + " " + fitem, // message fitem + " " + ResourceLoader.getQueryText("DBQUERY_TITLE_ERROR"), // title JOptionPane.ERROR_MESSAGE ); // message type return; } // Add to clause if (notInEffect_) clause_.appendText(fitem + " " + choice1 + "))"); else clause_.appendText(fitem + " " + choice1 + ")"); // Make appropriate controls available. otherList_.setEnabled(true); testList_.setEnabled(false); // End dialog dialog.dispose(); } } // end of ActionListenerAdapter ); JButton cancelButton = new JButton(ResourceLoader.getQueryText("DBQUERY_BUTTON_CANCEL")); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { dialog.dispose(); } } ); JPanel buttonPanel = new JPanel(); buttonPanel.add(okButton); buttonPanel.add(cancelButton); dialog = new JDialog(VUtilities.getFrame(this), item, true); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add("Center",new LabelledComponent(ResourceLoader.getQueryText("DBQUERY_TEXT_CHOOSE3") + " " + item, list1, false)); dialog.getContentPane().add("South", buttonPanel); dialog.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent ev) {dialog.dispose();} } ); dialog.pack(); dialog.setLocationRelativeTo(this); // @A1 - Set default focus in JComboBox-JTextField dialog.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent event) { JComponent comp; for (int i=0; i<dialog.getContentPane().getComponentCount(); i++) { comp = (JComponent) dialog.getContentPane().getComponent(i); if (comp instanceof JComboBox) { // list1 for (int x=0; x<comp.getComponentCount(); x++) { if (comp.getComponent(x) instanceof JTextField) { comp.getComponent(x).requestFocus(); return; } } return; } } } } ); dialog.setVisible(true); } if (text != null) // user completed test { // Add text to clause with trailing right paren(s). if (notInEffect_) clause_.appendText(text + "))"); else clause_.appendText(text + ")"); // Make appropriate controls available. otherList_.setEnabled(true); testList_.setEnabled(false); } } }
epl-1.0
theanuradha/debrief
org.mwc.debrief.data_feed/src/org/mwc/debrief/data_feed/views/LiveFeedViewer.java
1105
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.mwc.debrief.data_feed.views; /** interface for class capable of providing UI control of a data-feed * * @author ian.mayo * */ public interface LiveFeedViewer { /** add a message to the viewer log * * @param msg */ public void showMessage(String msg); /** update the state shown for this data source * * @param newState */ public void showState(String newState); /** extract data from this line of text, insert into plot * * @param data */ public void insertData(String data); }
epl-1.0
ControlSystemStudio/cs-studio
applications/appunorganized/appunorganized-plugins/org.csstudio.swt.chart/src/org/csstudio/swt/chart/axes/TraceNameYAxis.java
5666
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.swt.chart.axes; import java.util.ArrayList; import org.csstudio.swt.chart.Trace; import org.csstudio.swt.util.GraphicsUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** A 'Y' or 'vertical' axis that uses the trace names as labels. * <p> * The chart maintains one or more Y axes. * Each trace to plot needs to be assigned to a Y axis. * * @see Trace * @author Kay Kasemir */ public class TraceNameYAxis extends YAxis { private boolean traces_changed = true; private int space_width; /** Number of traces in each label row. */ private int row_items[]; /** Pixel width (or height, since they're vertical) of each row. */ private int row_widths[]; /** @see YAxis#YAxis */ public TraceNameYAxis(String label, YAxisListener listener) { super(label, listener); } // In addition to inherited bahavior, trigger a new layout @Override public final void addTrace(Trace trace) { traces_changed = true; super.addTrace(trace); fireEvent(YAxisListener.Aspect.LABEL); } // In addition to inherited bahavior, trigger a new layout @Override public final void removeTrace(Trace trace) { traces_changed = true; super.removeTrace(trace); fireEvent(YAxisListener.Aspect.LABEL); } // In addition to inherited bahavior, trigger a new layout @Override public final void setRegion(int x, int y, int width, int height) { traces_changed = true; super.setRegion(x, y, width, height); } private void determineLayout(GC gc) { if (!traces_changed) return; ArrayList<Integer> items = new ArrayList<Integer>(); ArrayList<Integer> widths = new ArrayList<Integer>(); space_width = gc.stringExtent(", ").x; //$NON-NLS-1$ int wid = 0; int itms = 0; // See how much fits in each row. for (int i=0; i<getNumTraces(); ++i) { int name_width = gc.textExtent(getTrace(i).getName()).x; // Start new row when exceeding available space. // Except: If there's only one item // in this row.. tough. It'll be truncated. if (itms > 0 && wid + name_width + space_width > region.height) { // Start new row items.add(new Integer(itms)); widths.add(new Integer(wid)); itms = 0; wid = 0; } ++itms; // Won't need the space_width for the last entry... Oh, well. wid += name_width + space_width; } if (itms > 0) { items.add(new Integer(itms)); widths.add(new Integer(wid)); } assert items.size() == widths.size(); // Turn ArrayList<Integer> into int[] row_items = new int[items.size()]; for (int i=0; i<row_items.length; ++i) row_items[i] = items.get(i).intValue(); row_widths = new int[widths.size()]; for (int i=0; i<row_widths.length; ++i) row_widths[i] = widths.get(i).intValue(); traces_changed = false; } @Override public final int getPixelWidth(final GC gc) { if (!isVisible()) return 0; determineLayout(gc); final Point char_size = gc.textExtent("X"); //$NON-NLS-1$ // Room for (vertical) label rows + value text + tick markers. return (row_widths.length + 1)*char_size.y + TICK_LENGTH; } @Override protected void paintLabel(GC gc) { if (getNumTraces() < 1) { // Do not use setLabel, because that would cause a redraw, // and we are already in a redraw -> endless loop. label = "y"; //$NON-NLS-1$ super.paintLabel(gc); return; } determineLayout(gc); // Label: At left edge of region, vertically apx. centered int row = 0; int items = 0; int x = region.x + 1; // y+height = botton, then go up by half the 'extra' int y = region.y + (region.height + row_widths[row])/2; Color fg = gc.getForeground(); for (int i=0; i<getNumTraces(); ++i) { String name = getTrace(i).getName(); gc.setForeground(getTrace(i).getColor()); Point text_size = gc.textExtent(name); int name_width = text_size.x; if (items >= row_items[row]) { // Start another row ++row; y = region.y + (region.height + row_widths[row])/2; x += text_size.y; items = 0; } y -= name_width; GraphicsUtils.drawVerticalText(name, x, y, gc, SWT.UP); gc.setForeground(fg); // restore original fg if (i < getNumTraces()-1) { y -= space_width; GraphicsUtils.drawVerticalText(", ", x, y, gc, SWT.UP); //$NON-NLS-1$ } ++items; } } }
epl-1.0
ceefour/agriculous
src/main/java/com/hendyirawan/smartroad/core/RoadAnalysis.java
590
package com.hendyirawan.smartroad.core; import org.opencv.core.Mat; import javax.annotation.Nullable; /** * Created by ceefour on 5/13/15. */ public class RoadAnalysis { public Mat original; public Mat blurred; public Mat edges; public Mat augmented; public RoadDamageLevel damageLevel; public RoadDamageKind damageKind; public Integer potholeCount; @Nullable public Double totalPotholeWidth; @Nullable public Double totalPotholeLength; @Nullable public Double totalPotholeDepth; @Nullable public Double totalPotholeArea; }
epl-1.0
b-cuts/esper
esper/src/test/java/com/espertech/esper/support/bean/SupportBean_ST0_Container.java
3272
/* * ************************************************************************************* * Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.support.bean; import java.util.ArrayList; import java.util.List; public class SupportBean_ST0_Container { private static String[] samples; public static void setSamples(String[] samples) { SupportBean_ST0_Container.samples = samples; } private List<SupportBean_ST0> contained; private List<SupportBean_ST0> containedTwo; public SupportBean_ST0_Container(List<SupportBean_ST0> contained) { this.contained = contained; } public SupportBean_ST0_Container(List<SupportBean_ST0> contained, List<SupportBean_ST0> containedTwo) { this.contained = contained; this.containedTwo = containedTwo; } public static List<SupportBean_ST0> makeSampleList() { if (samples == null) { return null; } return make2Value(samples).getContained(); } public static SupportBean_ST0[] makeSampleArray() { if (samples == null) { return null; } List<SupportBean_ST0> items = make2Value(samples).getContained(); return items.toArray(new SupportBean_ST0[items.size()]); } public static SupportBean_ST0_Container make3Value(String ... values) { if (values == null) { return new SupportBean_ST0_Container(null); } List<SupportBean_ST0> contained = new ArrayList<SupportBean_ST0>(); for (int i = 0; i < values.length; i++) { String[] triplet = values[i].split(","); contained.add(new SupportBean_ST0(triplet[0], triplet[1], Integer.parseInt(triplet[2]))); } return new SupportBean_ST0_Container(contained); } public static List<SupportBean_ST0> make2ValueList(String ... values) { if (values == null) { return null; } List<SupportBean_ST0> result = new ArrayList<SupportBean_ST0>(); for (int i = 0; i < values.length; i++) { String[] pair = values[i].split(","); result.add(new SupportBean_ST0(pair[0], Integer.parseInt(pair[1]))); } return result; } public static SupportBean_ST0_Container make2Value(String ... values) { return new SupportBean_ST0_Container(make2ValueList(values)); } public List<SupportBean_ST0> getContained() { return contained; } public List<SupportBean_ST0> getContainedTwo() { return containedTwo; } public static SupportBean_ST0 makeTest(String value) { return make2Value(value).getContained().get(0); } }
gpl-2.0
majianxiong/vulcan
plugins/vulcan-mercurial/source/main/java/net/sourceforge/vulcan/mercurial/Invoker.java
1154
/* * Vulcan Build Manager * Copyright (C) 2005-2012 Chris Eldredge * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package net.sourceforge.vulcan.mercurial; import java.io.File; import java.io.IOException; import java.io.OutputStream; public interface Invoker { void setOutputStream(OutputStream stream); InvocationResult invoke(String command, File workDir, String... args) throws IOException; String getErrorText(); String getOutputText(); int getExitCode(); }
gpl-2.0
b-cuts/esper
esper/src/test/java/com/espertech/esper/epl/variable/TestVersionedValueList.java
5710
/* * ************************************************************************************* * Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.epl.variable; import junit.framework.TestCase; import java.util.concurrent.locks.ReentrantReadWriteLock; public class TestVersionedValueList extends TestCase { private VersionedValueList<String> list; public void setUp() { list = new VersionedValueList<String>("abc", 2, "a", 1000, 10000, new ReentrantReadWriteLock().readLock(), 10, true); } public void testFlowNoTime() { tryInvalid(0); tryInvalid(1); assertEquals("a", list.getVersion(2)); assertEquals("a", list.getVersion(3)); list.addValue(4, "b", 0); tryInvalid(1); assertEquals("a", list.getVersion(2)); assertEquals("a", list.getVersion(3)); assertEquals("b", list.getVersion(4)); assertEquals("b", list.getVersion(5)); list.addValue(6, "c", 0); tryInvalid(1); assertEquals("a", list.getVersion(2)); assertEquals("a", list.getVersion(3)); assertEquals("b", list.getVersion(4)); assertEquals("b", list.getVersion(5)); assertEquals("c", list.getVersion(6)); assertEquals("c", list.getVersion(7)); list.addValue(7, "d", 0); tryInvalid(1); assertEquals("a", list.getVersion(2)); assertEquals("a", list.getVersion(3)); assertEquals("b", list.getVersion(4)); assertEquals("b", list.getVersion(5)); assertEquals("c", list.getVersion(6)); assertEquals("d", list.getVersion(7)); assertEquals("d", list.getVersion(8)); list.addValue(9, "e", 0); tryInvalid(1); assertEquals("a", list.getVersion(2)); assertEquals("a", list.getVersion(3)); assertEquals("b", list.getVersion(4)); assertEquals("b", list.getVersion(5)); assertEquals("c", list.getVersion(6)); assertEquals("d", list.getVersion(7)); assertEquals("d", list.getVersion(8)); assertEquals("e", list.getVersion(9)); assertEquals("e", list.getVersion(10)); } public void testHighWatermark() { list.addValue(3, "b", 3000); list.addValue(4, "c", 4000); list.addValue(5, "d", 5000); list.addValue(6, "e", 6000); list.addValue(7, "f", 7000); list.addValue(8, "g", 8000); list.addValue(9, "h", 9000); list.addValue(10, "i", 10000); list.addValue(11, "j", 10500); list.addValue(12, "k", 10600); assertEquals(9, list.getOlderVersions().size()); tryInvalid(0); tryInvalid(1); assertEquals("a", list.getVersion(2)); assertEquals("b", list.getVersion(3)); assertEquals("c", list.getVersion(4)); assertEquals("d", list.getVersion(5)); assertEquals("e", list.getVersion(6)); assertEquals("f", list.getVersion(7)); assertEquals("g", list.getVersion(8)); assertEquals("k", list.getVersion(12)); assertEquals("k", list.getVersion(13)); list.addValue(15, "x", 11000); // 11th value added assertEquals(9, list.getOlderVersions().size()); tryInvalid(0); tryInvalid(1); tryInvalid(2); assertEquals("b", list.getVersion(3)); assertEquals("c", list.getVersion(4)); assertEquals("d", list.getVersion(5)); assertEquals("k", list.getVersion(13)); assertEquals("k", list.getVersion(14)); assertEquals("x", list.getVersion(15)); // expire all before 5.5 sec list.addValue(20, "y", 15500); // 11th value added assertEquals(7, list.getOlderVersions().size()); tryInvalid(0); tryInvalid(1); tryInvalid(2); tryInvalid(3); tryInvalid(4); tryInvalid(5); assertEquals("e", list.getVersion(6)); assertEquals("k", list.getVersion(13)); assertEquals("x", list.getVersion(15)); assertEquals("x", list.getVersion(16)); assertEquals("y", list.getVersion(20)); // expire all before 10.5 sec list.addValue(21, "z1", 20500); list.addValue(22, "z2", 20500); list.addValue(23, "z3", 20501); assertEquals(4, list.getOlderVersions().size()); tryInvalid(9); tryInvalid(10); tryInvalid(11); assertEquals("k", list.getVersion(12)); assertEquals("k", list.getVersion(13)); assertEquals("k", list.getVersion(14)); assertEquals("x", list.getVersion(15)); assertEquals("x", list.getVersion(16)); assertEquals("y", list.getVersion(20)); assertEquals("z1", list.getVersion(21)); assertEquals("z2", list.getVersion(22)); assertEquals("z3", list.getVersion(23)); assertEquals("z3", list.getVersion(24)); } private void tryInvalid(int version) { try { list.getVersion(version); fail(); } catch (IllegalStateException ex) { } } }
gpl-2.0
xiangyong/btrace
src/test/resources/OnMethodTest.java
4059
/* * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package resources; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * !!! Only append the new methods; line numbers need to be kept intact !!! * @author Jaroslav Bachorik */ public class OnMethodTest { private int field; public OnMethodTest() {} private OnMethodTest(String a) {} public void noargs() {}; static public void noargs$static() {}; public long args(String a, long b, String[] c, int[] d) {return 0L;} static public long args$static(String a, long b, String[] c, int[] d) {return 0L;} public static long callTopLevelStatic(String a, long b) { OnMethodTest instance = new OnMethodTest(); return callTargetStatic(a, b) + instance.callTarget(a, b); } public static long callTargetStatic(String a, long b) { return 3L; } public long callTopLevel(String a, long b) { return callTarget(a, b) + callTargetStatic(a, b); } private long callTarget(String a, long b) { return 4L; } public void exception() { try { throw new IOException("hello world"); } catch (IOException e) { e.printStackTrace(); } } public void uncaught() { throw new RuntimeException("ho-hey"); } public void array(int a) { int[] arr = new int[10]; int b = arr[a]; arr[a] = 15; } public void field() { this.field = this.field + 1; } public void newObject() { Map<String, String> m = new HashMap<String, String>(); } public void newArray() { int[] a = new int[1]; int[][] b = new int[1][1]; String[] c = new String[1]; String[][] d = new String[1][1]; } public void casts() { Map<String, String> c = new HashMap<String, String>(); HashMap<String, String> d = (HashMap<String, String>)c; if (c instanceof HashMap) { System.err.println("hey ho"); } } public void sync() { synchronized(this) { System.err.println("ho hey"); } } public long callTopLevel1(String a, long b) { long i = callTarget(a, b) + callTargetStatic(a, b); return i + calLTargetX(a, b); } private long calLTargetX(String a, long b) { return 5L; } public long argsMultiReturn(String a, long b, String[] c, int[] d) { if (System.currentTimeMillis() > 325723059) { return 0L; } if (System.currentTimeMillis() > 32525) { return 1L; } { System.out.println("fdsfg"); return -1L; } } public native long nativeWithReturn(int a, String b, long[] c, Object[] d); public native void nativeWithoutReturn(int a, String b, long[] c, Object[] d); }
gpl-2.0
consulo/consulo-vim
src/main/java/com/maddyhome/idea/vim/action/motion/object/MotionOuterBlockAngleAction.java
1674
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2016 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.action.motion.object; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.action.motion.TextObjectAction; import com.maddyhome.idea.vim.command.Argument; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.handler.TextObjectActionHandler; import org.jetbrains.annotations.NotNull; /** */ public class MotionOuterBlockAngleAction extends TextObjectAction { public MotionOuterBlockAngleAction() { super(new MotionOuterBlockAngleAction.Handler()); } private static class Handler extends TextObjectActionHandler { public TextRange getRange(@NotNull Editor editor, DataContext context, int count, int rawCount, Argument argument) { return VimPlugin.getMotion().getBlockRange(editor, count, true, '<'); } } }
gpl-2.0
ekummerfeld/tetrad
tetrad-gui/src/main/java/edu/cmu/tetradapp/util/SplashScreen.java
5642
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetradapp.util; import edu.cmu.tetrad.latest.LatestClient; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; /** * A class that displays a splashScreen with a progress bar. Everything is * static so there can only be one Splash Screen. The usage is show, * (increment)* and hide. * * @author Juan Casares */ public class SplashScreen { private static int MAX; private static int COUNTER; private static SplashWindow WINDOW; private boolean skipLatest; public static void show(Frame parent, String title, int max, boolean skipLatest) { hide(); SplashScreen.COUNTER = 0; SplashScreen.MAX = max; WINDOW = new SplashWindow(parent, null, title, skipLatest); } public static void hide() { if (WINDOW == null) { return; } // show a complete bar for a short while WINDOW.bar.setValue(MAX); WINDOW.bar.repaint(); try { Thread.sleep(2000); } catch (InterruptedException e) { // Ignore. } WINDOW.setVisible(false); WINDOW.dispose(); WINDOW = null; } public static void increment() { increment(1); } private static void increment(int by) { COUNTER += by; if (COUNTER > MAX) { COUNTER = MAX; } if (WINDOW != null) { WINDOW.bar.setValue(COUNTER); } } private static class SplashWindow extends Window { final Image splashIm; final JProgressBar bar; SplashWindow(Frame parent, Image image, String title, boolean skipLatest) { super(parent); this.splashIm = image; //setSize(200, 100); JPanel panel = new JPanel(); panel.setBackground(Color.white); panel.setBorder(BorderFactory.createLineBorder(Color.black)); panel.setLayout(new BorderLayout()); add(panel, BorderLayout.CENTER); Box b = Box.createVerticalBox(); panel.add(b, BorderLayout.CENTER); Box b1 = Box.createHorizontalBox(); JLabel label = new JLabel(title, JLabel.CENTER); label.setFont(label.getFont().deriveFont((float) 16)); b1.add(Box.createHorizontalGlue()); b1.add(label); b1.add(Box.createHorizontalGlue()); b.add(b1); String text = LicenseUtils.copyright(); // optionally check if we are running latest version String version = this.getClass().getPackage().getImplementationVersion(); if (! skipLatest) { LatestClient latestClient = LatestClient.getInstance(); // if no version it means we are not running a jar so probably development if (version == null) version = "DEVELOPMENT"; latestClient.checkLatest("tetrad", version); StringBuilder latestResult = new StringBuilder(latestClient.getLatestResult(60)); text = text + "\n" + latestResult.toString(); } JTextArea textArea = new JTextArea(text); textArea.setBorder(new EmptyBorder(5, 5, 5, 5)); b.add(textArea); bar = new JProgressBar(0, MAX); bar.setBackground(Color.white); bar.setBorderPainted(false); b.add(bar); /* Center the WINDOW */ pack(); Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle bounds = getBounds(); setLocation((screenDim.width - bounds.width) / 2, (screenDim.height - bounds.height) / 2); setVisible(true); repaint(); } // must move to panel public void paint(Graphics g) { super.paint(g); if (splashIm != null) { g.drawImage(splashIm, 0, 0, this); } } } }
gpl-2.0
DavidARivkin/mzmine2
src/main/java/net/sf/mzmine/desktop/impl/projecttree/RawDataTreeModel.java
6313
/* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.desktop.impl.projecttree; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import net.sf.mzmine.datamodel.MZmineProject; import net.sf.mzmine.datamodel.MassList; import net.sf.mzmine.datamodel.PeakList; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.Scan; import net.sf.mzmine.datamodel.impl.RemoteJob; /** * Project tree model implementation */ public class RawDataTreeModel extends DefaultTreeModel { /** * */ private static final long serialVersionUID = 1L; public static final String dataFilesNodeName = "Raw data files"; private Hashtable<Object, DefaultMutableTreeNode> treeObjects = new Hashtable<Object, DefaultMutableTreeNode>(); private ProjectTreeNode rootNode; public RawDataTreeModel(MZmineProject project) { super(new ProjectTreeNode(dataFilesNodeName)); rootNode = (ProjectTreeNode) super.getRoot(); } /** * This method must be called from Swing thread */ public void addObject(final Object object) { assert object != null; if (!SwingUtilities.isEventDispatchThread()) { throw new IllegalStateException( "This method must be called from Swing thread"); } // Create new node final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode( object); treeObjects.put(object, newNode); if (object instanceof RawDataFile) { int childCount = getChildCount(rootNode); insertNodeInto(newNode, rootNode, childCount); RawDataFile dataFile = (RawDataFile) object; int scanNumbers[] = dataFile.getScanNumbers(); for (int i = 0; i < scanNumbers.length; i++) { Scan scan = dataFile.getScan(scanNumbers[i]); DefaultMutableTreeNode scanNode = new DefaultMutableTreeNode( scan); treeObjects.put(scan, scanNode); insertNodeInto(scanNode, newNode, i); MassList massLists[] = scan.getMassLists(); for (int j = 0; j < massLists.length; j++) { DefaultMutableTreeNode mlNode = new DefaultMutableTreeNode( massLists[j]); treeObjects.put(massLists[j], mlNode); insertNodeInto(mlNode, scanNode, j); } } ArrayList<RemoteJob> jobs = dataFile.getJobs(); int i = 0; for (RemoteJob job : jobs) { DefaultMutableTreeNode jobNode = new DefaultMutableTreeNode(job); treeObjects.put(job, jobNode); insertNodeInto(jobNode, newNode, i++); } } else if (object instanceof RemoteJob) { RemoteJob job = (RemoteJob) object; final DefaultMutableTreeNode rawNode = treeObjects.get(job.getRawDataFile()); if (rawNode != null) insertNodeInto(newNode, rawNode, 0); } else if (object instanceof MassList) { Scan scan = ((MassList) object).getScan(); final DefaultMutableTreeNode scNode = treeObjects.get(scan); assert scNode != null; int index = scNode.getChildCount(); insertNodeInto(newNode, scNode, index); } } /** * This method must be called from Swing thread */ public void removeObject(final Object object) { if (!SwingUtilities.isEventDispatchThread()) { throw new IllegalStateException( "This method must be called from Swing thread"); } final DefaultMutableTreeNode node = treeObjects.get(object); assert node != null; // Remove all children from treeObjects Enumeration<?> e = node.depthFirstEnumeration(); while (e.hasMoreElements()) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) e .nextElement(); Object nodeObject = childNode.getUserObject(); treeObjects.remove(nodeObject); } // Remove the node from the tree, that also remove child // nodes removeNodeFromParent(node); // Remove the node object from treeObjects treeObjects.remove(object); } public synchronized RawDataFile[] getDataFiles() { int childrenCount = getChildCount(rootNode); RawDataFile result[] = new RawDataFile[childrenCount]; for (int j = 0; j < childrenCount; j++) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) getChild( rootNode, j); result[j] = (RawDataFile) child.getUserObject(); } return result; } public void valueForPathChanged(TreePath path, Object value) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent(); Object object = node.getUserObject(); String newName = (String) value; if (object instanceof RawDataFile) { RawDataFile df = (RawDataFile) object; df.setName(newName); } if (object instanceof PeakList) { PeakList pl = (PeakList) object; pl.setName(newName); } } public void notifyObjectChanged(Object object, boolean structureChanged) { if (rootNode.getUserObject() == object) { if (structureChanged) nodeStructureChanged(rootNode); else nodeChanged(rootNode); return; } Enumeration<?> nodes = rootNode.breadthFirstEnumeration(); while (nodes.hasMoreElements()) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes .nextElement(); if (node.getUserObject() == object) { if (structureChanged) nodeStructureChanged(node); else nodeChanged(node); return; } } } public DefaultMutableTreeNode getRoot() { return rootNode; } }
gpl-2.0
mobile-event-processing/Asper
source/src/com/espertech/esper/epl/spec/StatementSpecUnMapResult.java
1965
/************************************************************************************** * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * **************************************************************************************/ package com.espertech.esper.epl.spec; import com.espertech.esper.client.soda.EPStatementObjectModel; import java.util.Map; /** * Return result for unmap operators unmapping an intermal statement representation to the SODA object model. */ public class StatementSpecUnMapResult { private final EPStatementObjectModel objectModel; private final Map<Integer, SubstitutionParameterExpression> indexedParams; /** * Ctor. * @param objectModel of the statement * @param indexedParams a map of parameter index and parameter */ public StatementSpecUnMapResult(EPStatementObjectModel objectModel, Map<Integer, SubstitutionParameterExpression> indexedParams) { this.objectModel = objectModel; this.indexedParams = indexedParams; } /** * Returns the object model. * @return object model */ public EPStatementObjectModel getObjectModel() { return objectModel; } /** * Returns the substitution paremeters keyed by the parameter's index. * @return map of index and parameter */ public Map<Integer, SubstitutionParameterExpression> getIndexedParams() { return indexedParams; } }
gpl-2.0
SpoonLabs/astor
examples/math_106/src/java/org/apache/commons/math/distribution/PascalDistribution.java
1808
/* * Copyright 2006 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.apache.commons.math.distribution; /** * The Pascal Distribution. * * Instances of PascalDistribution objects should be created using * {@link DistributionFactory#createPascalDistribution(int, double)}. * * <p> * References: * <ul> * <li><a href="http://mathworld.wolfram.com/NegativeBinomialDistribution.html"> * Negative Binomial Distribution</a></li> * </ul> * </p> * * @version $Revision:$ */ public interface PascalDistribution extends IntegerDistribution { /** * Access the number of successes for this distribution. * * @return the number of successes */ int getNumberOfSuccesses(); /** * Access the probability of success for this distribution. * * @return the probability of success */ double getProbabilityOfSuccess(); /** * Change the number of successes for this distribution. * * @param successes the new number of successes */ void setNumberOfSuccesses(int successes); /** * Change the probability of success for this distribution. * * @param p the new probability of success */ void setProbabilityOfSuccess(double p); }
gpl-2.0
ianopolous/JPC
src/org/jpc/emulator/execution/opcodes/pm/fsubp_ST7_ST7.java
2011
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.pm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fsubp_ST7_ST7 extends Executable { public fsubp_ST7_ST7(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(7); double freg1 = cpu.fpu.ST(7); if ((freg0 == Double.NEGATIVE_INFINITY && freg1 == Double.NEGATIVE_INFINITY) || (freg0 == Double.POSITIVE_INFINITY && freg1 == Double.POSITIVE_INFINITY)) cpu.fpu.setInvalidOperation(); cpu.fpu.setST(7, freg0-freg1); cpu.fpu.pop(); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
georgenicoll/esper
esper/src/main/java/com/espertech/esper/epl/enummethod/eval/EnumEvalTakeLast.java
2385
/* * ************************************************************************************* * Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.epl.enummethod.eval; import com.espertech.esper.client.EventBean; import com.espertech.esper.epl.expression.core.ExprEvaluator; import com.espertech.esper.epl.expression.core.ExprEvaluatorContext; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class EnumEvalTakeLast implements EnumEval { private ExprEvaluator sizeEval; private int numStreams; public EnumEvalTakeLast(ExprEvaluator sizeEval, int numStreams) { this.sizeEval = sizeEval; this.numStreams = numStreams; } public int getStreamNumSize() { return numStreams; } public Object evaluateEnumMethod(EventBean[] eventsLambda, Collection target, boolean isNewData, ExprEvaluatorContext context) { Object sizeObj = sizeEval.evaluate(eventsLambda, isNewData, context); if (sizeObj == null) { return null; } if (target.isEmpty()) { return target; } int size = ((Number) sizeObj).intValue(); if (size <= 0) { return Collections.emptyList(); } if (target.size() < size) { return target; } if (size == 1) { Object last = null; for (Object next : target) { last = next; } return Collections.singletonList(last); } ArrayList<Object> result = new ArrayList<Object>(); for (Object next : target) { result.add(next); if (result.size() > size) { result.remove(0); } } return result; } }
gpl-2.0
CharlesZ-Chen/checker-framework
checker/src/org/checkerframework/checker/guieffect/qual/AlwaysSafe.java
917
package org.checkerframework.checker.guieffect.qual; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.checkerframework.framework.qual.DefaultQualifierInHierarchy; import org.checkerframework.framework.qual.ImplicitFor; import org.checkerframework.framework.qual.LiteralKind; import org.checkerframework.framework.qual.SubtypeOf; /** * Annotation to override the UI effect on a class, and make a field or method safe for non-UI code * to use. * * @checker_framework.manual #guieffect-checker GUI Effect Checker */ @SubtypeOf({UI.class}) @DefaultQualifierInHierarchy @ImplicitFor(literals = LiteralKind.NULL) @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) public @interface AlwaysSafe {}
gpl-2.0
0359xiaodong/YiIM_V4
src/com/chyitech/yiim/entity/RosterGroup.java
970
package com.chyitech.yiim.entity; /** * 分组数据模型 * @author saint * */ public class RosterGroup { /** * 分组名称 */ private String mName; /** * 分组成员总数 */ private int mEntryCount; /** * 在线或已出席的成员数 */ private int mOnlineCount; public RosterGroup() { mName = ""; mEntryCount = 0; mOnlineCount = 0; } public String getName() { return mName; } public void setName(String name) { this.mName = name; } public int getEntryCount() { return mEntryCount; } public void setEntryCount(int entryCount) { this.mEntryCount = entryCount; } public int getOnlineCount() { return mOnlineCount; } public void setOnlineCount(int onlineCount) { this.mOnlineCount = onlineCount; } public void addOnlineCount() { mOnlineCount++; } public void addEntryCount() { mEntryCount++; } @Override public String toString() { // TODO Auto-generated method stub return mName; } }
gpl-2.0
Distrotech/icedtea6-1.12
generated/com/sun/java/swing/plaf/nimbus/FormattedTextFieldPainter.java
15170
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.java.swing.plaf.nimbus; import com.sun.java.swing.Painter; import java.awt.*; import java.awt.geom.*; import java.awt.image.*; import javax.swing.*; final class FormattedTextFieldPainter extends AbstractRegionPainter { //package private integers representing the available states that //this painter will paint. These are used when creating a new instance //of FormattedTextFieldPainter to determine which region/state is being painted //by that instance. static final int BACKGROUND_DISABLED = 1; static final int BACKGROUND_ENABLED = 2; static final int BACKGROUND_SELECTED = 3; static final int BORDER_DISABLED = 4; static final int BORDER_FOCUSED = 5; static final int BORDER_ENABLED = 6; private int state; //refers to one of the static final ints above private PaintContext ctx; //the following 4 variables are reused during the painting code of the layers private Path2D path = new Path2D.Float(); private Rectangle2D rect = new Rectangle2D.Float(0, 0, 0, 0); private RoundRectangle2D roundRect = new RoundRectangle2D.Float(0, 0, 0, 0, 0, 0); private Ellipse2D ellipse = new Ellipse2D.Float(0, 0, 0, 0); //All Colors used for painting are stored here. Ideally, only those colors being used //by a particular instance of FormattedTextFieldPainter would be created. For the moment at least, //however, all are created for each instance. private Color color1 = decodeColor("nimbusBlueGrey", -0.015872955f, -0.07995863f, 0.15294117f, 0); private Color color2 = decodeColor("nimbusLightBackground", 0.0f, 0.0f, 0.0f, 0); private Color color3 = decodeColor("nimbusBlueGrey", -0.006944418f, -0.07187897f, 0.06666666f, 0); private Color color4 = decodeColor("nimbusBlueGrey", 0.007936537f, -0.07826825f, 0.10588235f, 0); private Color color5 = decodeColor("nimbusBlueGrey", 0.007936537f, -0.07856284f, 0.11372548f, 0); private Color color6 = decodeColor("nimbusBlueGrey", 0.007936537f, -0.07796818f, 0.09803921f, 0); private Color color7 = decodeColor("nimbusBlueGrey", -0.027777791f, -0.0965403f, -0.18431371f, 0); private Color color8 = decodeColor("nimbusBlueGrey", 0.055555582f, -0.1048766f, -0.05098039f, 0); private Color color9 = decodeColor("nimbusLightBackground", 0.6666667f, 0.004901961f, -0.19999999f, 0); private Color color10 = decodeColor("nimbusBlueGrey", 0.055555582f, -0.10512091f, -0.019607842f, 0); private Color color11 = decodeColor("nimbusBlueGrey", 0.055555582f, -0.105344966f, 0.011764705f, 0); private Color color12 = decodeColor("nimbusFocus", 0.0f, 0.0f, 0.0f, 0); //Array of current component colors, updated in each paint call private Object[] componentColors; public FormattedTextFieldPainter(PaintContext ctx, int state) { super(); this.state = state; this.ctx = ctx; } @Override protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) { //populate componentColors array with colors calculated in getExtendedCacheKeys call componentColors = extendedCacheKeys; //generate this entire method. Each state/bg/fg/border combo that has //been painted gets its own KEY and paint method. switch(state) { case BACKGROUND_DISABLED: paintBackgroundDisabled(g); break; case BACKGROUND_ENABLED: paintBackgroundEnabled(g); break; case BACKGROUND_SELECTED: paintBackgroundSelected(g); break; case BORDER_DISABLED: paintBorderDisabled(g); break; case BORDER_FOCUSED: paintBorderFocused(g); break; case BORDER_ENABLED: paintBorderEnabled(g); break; } } protected Object[] getExtendedCacheKeys(JComponent c) { Object[] extendedCacheKeys = null; switch(state) { case BACKGROUND_ENABLED: extendedCacheKeys = new Object[] { getComponentColor(c, "background", color2, 0.0f, 0.0f, 0)}; break; case BORDER_FOCUSED: extendedCacheKeys = new Object[] { getComponentColor(c, "background", color9, 0.004901961f, -0.19999999f, 0), getComponentColor(c, "background", color2, 0.0f, 0.0f, 0)}; break; case BORDER_ENABLED: extendedCacheKeys = new Object[] { getComponentColor(c, "background", color9, 0.004901961f, -0.19999999f, 0), getComponentColor(c, "background", color2, 0.0f, 0.0f, 0)}; break; } return extendedCacheKeys; } @Override protected final PaintContext getPaintContext() { return ctx; } private void paintBackgroundDisabled(Graphics2D g) { rect = decodeRect1(); g.setPaint(color1); g.fill(rect); } private void paintBackgroundEnabled(Graphics2D g) { rect = decodeRect1(); g.setPaint((Color)componentColors[0]); g.fill(rect); } private void paintBackgroundSelected(Graphics2D g) { rect = decodeRect1(); g.setPaint(color2); g.fill(rect); } private void paintBorderDisabled(Graphics2D g) { rect = decodeRect2(); g.setPaint(decodeGradient1(rect)); g.fill(rect); rect = decodeRect3(); g.setPaint(decodeGradient2(rect)); g.fill(rect); rect = decodeRect4(); g.setPaint(color6); g.fill(rect); rect = decodeRect5(); g.setPaint(color4); g.fill(rect); rect = decodeRect6(); g.setPaint(color4); g.fill(rect); } private void paintBorderFocused(Graphics2D g) { rect = decodeRect7(); g.setPaint(decodeGradient3(rect)); g.fill(rect); rect = decodeRect8(); g.setPaint(decodeGradient4(rect)); g.fill(rect); rect = decodeRect9(); g.setPaint(color10); g.fill(rect); rect = decodeRect10(); g.setPaint(color10); g.fill(rect); rect = decodeRect11(); g.setPaint(color11); g.fill(rect); path = decodePath1(); g.setPaint(color12); g.fill(path); } private void paintBorderEnabled(Graphics2D g) { rect = decodeRect7(); g.setPaint(decodeGradient5(rect)); g.fill(rect); rect = decodeRect8(); g.setPaint(decodeGradient4(rect)); g.fill(rect); rect = decodeRect9(); g.setPaint(color10); g.fill(rect); rect = decodeRect10(); g.setPaint(color10); g.fill(rect); rect = decodeRect11(); g.setPaint(color11); g.fill(rect); } private Rectangle2D decodeRect1() { rect.setRect(decodeX(0.4f), //x decodeY(0.4f), //y decodeX(2.6f) - decodeX(0.4f), //width decodeY(2.6f) - decodeY(0.4f)); //height return rect; } private Rectangle2D decodeRect2() { rect.setRect(decodeX(0.6666667f), //x decodeY(0.4f), //y decodeX(2.3333333f) - decodeX(0.6666667f), //width decodeY(1.0f) - decodeY(0.4f)); //height return rect; } private Rectangle2D decodeRect3() { rect.setRect(decodeX(1.0f), //x decodeY(0.6f), //y decodeX(2.0f) - decodeX(1.0f), //width decodeY(1.0f) - decodeY(0.6f)); //height return rect; } private Rectangle2D decodeRect4() { rect.setRect(decodeX(0.6666667f), //x decodeY(1.0f), //y decodeX(1.0f) - decodeX(0.6666667f), //width decodeY(2.0f) - decodeY(1.0f)); //height return rect; } private Rectangle2D decodeRect5() { rect.setRect(decodeX(0.6666667f), //x decodeY(2.3333333f), //y decodeX(2.3333333f) - decodeX(0.6666667f), //width decodeY(2.0f) - decodeY(2.3333333f)); //height return rect; } private Rectangle2D decodeRect6() { rect.setRect(decodeX(2.0f), //x decodeY(1.0f), //y decodeX(2.3333333f) - decodeX(2.0f), //width decodeY(2.0f) - decodeY(1.0f)); //height return rect; } private Rectangle2D decodeRect7() { rect.setRect(decodeX(0.4f), //x decodeY(0.4f), //y decodeX(2.6f) - decodeX(0.4f), //width decodeY(1.0f) - decodeY(0.4f)); //height return rect; } private Rectangle2D decodeRect8() { rect.setRect(decodeX(0.6f), //x decodeY(0.6f), //y decodeX(2.4f) - decodeX(0.6f), //width decodeY(1.0f) - decodeY(0.6f)); //height return rect; } private Rectangle2D decodeRect9() { rect.setRect(decodeX(0.4f), //x decodeY(1.0f), //y decodeX(0.6f) - decodeX(0.4f), //width decodeY(2.6f) - decodeY(1.0f)); //height return rect; } private Rectangle2D decodeRect10() { rect.setRect(decodeX(2.4f), //x decodeY(1.0f), //y decodeX(2.6f) - decodeX(2.4f), //width decodeY(2.6f) - decodeY(1.0f)); //height return rect; } private Rectangle2D decodeRect11() { rect.setRect(decodeX(0.6f), //x decodeY(2.4f), //y decodeX(2.4f) - decodeX(0.6f), //width decodeY(2.6f) - decodeY(2.4f)); //height return rect; } private Path2D decodePath1() { path.reset(); path.moveTo(decodeX(0.4f), decodeY(0.4f)); path.lineTo(decodeX(0.4f), decodeY(2.6f)); path.lineTo(decodeX(2.6f), decodeY(2.6f)); path.lineTo(decodeX(2.6f), decodeY(0.4f)); path.curveTo(decodeAnchorX(2.5999999046325684f, 0.0f), decodeAnchorY(0.4000000059604645f, 0.0f), decodeAnchorX(2.880000352859497f, 0.09999999999999432f), decodeAnchorY(0.4000000059604645f, 0.0f), decodeX(2.8800004f), decodeY(0.4f)); path.curveTo(decodeAnchorX(2.880000352859497f, 0.09999999999999432f), decodeAnchorY(0.4000000059604645f, 0.0f), decodeAnchorX(2.880000352859497f, 0.0f), decodeAnchorY(2.879999876022339f, 0.0f), decodeX(2.8800004f), decodeY(2.8799999f)); path.lineTo(decodeX(0.120000005f), decodeY(2.8799999f)); path.lineTo(decodeX(0.120000005f), decodeY(0.120000005f)); path.lineTo(decodeX(2.8800004f), decodeY(0.120000005f)); path.lineTo(decodeX(2.8800004f), decodeY(0.4f)); path.lineTo(decodeX(0.4f), decodeY(0.4f)); path.closePath(); return path; } private Paint decodeGradient1(Shape s) { Rectangle2D bounds = s.getBounds2D(); float x = (float)bounds.getX(); float y = (float)bounds.getY(); float w = (float)bounds.getWidth(); float h = (float)bounds.getHeight(); return decodeGradient((0.5f * w) + x, (0.0f * h) + y, (0.5f * w) + x, (1.0f * h) + y, new float[] { 0.0f,0.5f,1.0f }, new Color[] { color3, decodeColor(color3,color4,0.5f), color4}); } private Paint decodeGradient2(Shape s) { Rectangle2D bounds = s.getBounds2D(); float x = (float)bounds.getX(); float y = (float)bounds.getY(); float w = (float)bounds.getWidth(); float h = (float)bounds.getHeight(); return decodeGradient((0.5f * w) + x, (0.0f * h) + y, (0.5f * w) + x, (1.0f * h) + y, new float[] { 0.0f,0.5f,1.0f }, new Color[] { color5, decodeColor(color5,color1,0.5f), color1}); } private Paint decodeGradient3(Shape s) { Rectangle2D bounds = s.getBounds2D(); float x = (float)bounds.getX(); float y = (float)bounds.getY(); float w = (float)bounds.getWidth(); float h = (float)bounds.getHeight(); return decodeGradient((0.25f * w) + x, (0.0f * h) + y, (0.25f * w) + x, (0.1625f * h) + y, new float[] { 0.1f,0.49999997f,0.9f }, new Color[] { color7, decodeColor(color7,color8,0.5f), color8}); } private Paint decodeGradient4(Shape s) { Rectangle2D bounds = s.getBounds2D(); float x = (float)bounds.getX(); float y = (float)bounds.getY(); float w = (float)bounds.getWidth(); float h = (float)bounds.getHeight(); return decodeGradient((0.5f * w) + x, (0.0f * h) + y, (0.5f * w) + x, (1.0f * h) + y, new float[] { 0.1f,0.49999997f,0.9f }, new Color[] { (Color)componentColors[0], decodeColor((Color)componentColors[0],(Color)componentColors[1],0.5f), (Color)componentColors[1]}); } private Paint decodeGradient5(Shape s) { Rectangle2D bounds = s.getBounds2D(); float x = (float)bounds.getX(); float y = (float)bounds.getY(); float w = (float)bounds.getWidth(); float h = (float)bounds.getHeight(); return decodeGradient((0.5f * w) + x, (0.0f * h) + y, (0.5f * w) + x, (1.0f * h) + y, new float[] { 0.1f,0.49999997f,0.9f }, new Color[] { color7, decodeColor(color7,color8,0.5f), color8}); } }
gpl-2.0
karambir252/WordPress-Android
WordPress/src/main/java/org/xmlrpc/android/XMLRPCUtils.java
25979
package org.xmlrpc.android; import android.support.annotation.StringRes; import android.text.TextUtils; import android.util.Xml; import android.webkit.URLUtil; import com.android.volley.TimeoutError; import org.apache.http.conn.ConnectTimeoutException; import org.wordpress.android.R; import org.wordpress.android.analytics.AnalyticsTracker; import org.wordpress.android.util.AppLog; import org.wordpress.android.util.BlogUtils; import org.wordpress.android.util.UrlUtils; import org.wordpress.android.util.WPUrlUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlrpc.android.XMLRPCUtils.XMLRPCUtilsException.Kind; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; public class XMLRPCUtils { public static class XMLRPCUtilsException extends Exception { public enum Kind { SITE_URL_CANNOT_BE_EMPTY, INVALID_URL, MISSING_XMLRPC_METHOD, ERRONEOUS_SSL_CERTIFICATE, HTTP_AUTH_REQUIRED, SITE_TIME_OUT, NO_SITE_ERROR, XMLRPC_MALFORMED_RESPONSE, XMLRPC_ERROR } public final Kind kind; public final @StringRes int errorMsgId; public final String failedUrl; public final String clientResponse; public XMLRPCUtilsException(Kind kind, @StringRes int errorMsgId, String failedUrl, String clientResponse) { this.kind = kind; this.errorMsgId = errorMsgId; this.failedUrl = failedUrl; this.clientResponse = clientResponse; } } private static @StringRes int handleXmlRpcFault(XMLRPCFault xmlRpcFault) { AppLog.e(AppLog.T.NUX, "XMLRPCFault received from XMLRPC call wp.getUsersBlogs", xmlRpcFault); switch (xmlRpcFault.getFaultCode()) { case 403: return org.wordpress.android.R.string.username_or_password_incorrect; case 404: return org.wordpress.android.R.string.xmlrpc_error; case 425: return org.wordpress.android.R.string.account_two_step_auth_enabled; default: return org.wordpress.android.R.string.no_site_error; } } private static boolean isHTTPAuthErrorMessage(Exception e) { return e != null && e.getMessage() != null && e.getMessage().contains("401"); } private static Object doSystemListMethodsXMLRPC(String url, String httpUsername, String httpPassword) throws XMLRPCException, IOException, XmlPullParserException, XMLRPCUtilsException { if (!UrlUtils.isValidUrlAndHostNotNull(url)) { AppLog.e(AppLog.T.NUX, "invalid URL: " + url); throw new XMLRPCUtilsException(Kind.INVALID_URL, org.wordpress.android.R.string .invalid_site_url_message, url, null); } AppLog.i(AppLog.T.NUX, "Trying system.listMethods on the following URL: " + url); URI uri = URI.create(url); XMLRPCClientInterface client = XMLRPCFactory.instantiate(uri, httpUsername, httpPassword); return client.call(ApiHelper.Method.LIST_METHODS); } private static boolean validateListMethodsResponse(Object[] availableMethods) { if (availableMethods == null) { AppLog.e(AppLog.T.NUX, "The response of system.listMethods was empty!"); return false; } // validate xmlrpc methods String[] requiredMethods = {"wp.getUsersBlogs", "wp.getPage", "wp.getCommentStatusList", "wp.newComment", "wp.editComment", "wp.deleteComment", "wp.getComments", "wp.getComment", "wp.getOptions", "wp.uploadFile", "wp.newCategory", "wp.getTags", "wp.getCategories", "wp.editPage", "wp.deletePage", "wp.newPage", "wp.getPages"}; for (String currentRequiredMethod : requiredMethods) { boolean match = false; for (Object currentAvailableMethod : availableMethods) { if ((currentAvailableMethod).equals(currentRequiredMethod)) { match = true; break; } } if (!match) { AppLog.e(AppLog.T.NUX, "The following XML-RPC method: " + currentRequiredMethod + " is missing on the" + " server."); return false; } } return true; } // Append "xmlrpc.php" if missing in the URL private static String appendXMLRPCPath(String url) { // Don't use 'ends' here! Some hosting wants parameters passed to baseURL/xmlrpc-php?my-authcode=XXX if (url.contains("xmlrpc.php")) { return url; } else { return url + "/xmlrpc.php"; } } /** * Truncate a string beginning at the marker * @param url input string * @param marker the marker to begin the truncation from * @return new string truncated to the begining of the marker or the input string if marker is not found */ private static String truncateUrl(String url, String marker) { if (TextUtils.isEmpty(marker) || url.indexOf(marker) < 0) { return url; } final String newUrl = url.substring(0, url.indexOf(marker)); return URLUtil.isValidUrl(newUrl) ? newUrl : url; } public static String sanitizeSiteUrl(String siteUrl, boolean addHttps) throws XMLRPCUtilsException { // remove padding whitespace String url = siteUrl.trim(); if (TextUtils.isEmpty(url)) { throw new XMLRPCUtilsException(XMLRPCUtilsException.Kind.SITE_URL_CANNOT_BE_EMPTY, R.string .invalid_site_url_message, siteUrl, null); } // Convert IDN names to punycode if necessary url = UrlUtils.convertUrlToPunycodeIfNeeded(url); // Add http to the beginning of the URL if needed url = UrlUtils.addUrlSchemeIfNeeded(url, addHttps); // strip url from known usual trailing paths url = XMLRPCUtils.stripKnownPaths(url); if (!(URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url))) { throw new XMLRPCUtilsException(Kind.INVALID_URL, R.string.invalid_site_url_message, url, null); } return url; } private static String stripKnownPaths(String url) { // Remove 'wp-login.php' if available in the URL String sanitizedURL = truncateUrl(url, "wp-login.php"); // Remove '/wp-admin' if available in the URL sanitizedURL = truncateUrl(sanitizedURL, "/wp-admin"); // Remove '/wp-content' if available in the URL sanitizedURL = truncateUrl(sanitizedURL, "/wp-content"); sanitizedURL = truncateUrl(sanitizedURL, "/xmlrpc.php?rsd"); // remove any trailing slashes while (sanitizedURL.endsWith("/")) { sanitizedURL = sanitizedURL.substring(0, sanitizedURL.length() - 1); } return sanitizedURL; } private static boolean checkXMLRPCEndpointValidity(String url, String httpUsername, String httpPassword) throws XMLRPCUtilsException { try { Object[] methods = (Object[]) doSystemListMethodsXMLRPC(url, httpUsername, httpPassword); if (methods == null) { AppLog.e(AppLog.T.NUX, "The response of system.listMethods was empty!"); return false; } // Exit the loop on the first URL that replies with a XML-RPC doc. AppLog.i(AppLog.T.NUX, "system.listMethods replied with XML-RPC objects on the URL: " + url); AppLog.i(AppLog.T.NUX, "Validating the XML-RPC response..."); if (validateListMethodsResponse(methods)) { // Endpoint address found and works fine. AppLog.i(AppLog.T.NUX, "Validation ended with success!!! Endpoint found!!!"); return true; } else { // Endpoint found, but it has problem. AppLog.w(AppLog.T.NUX, "Validation ended with errors!!! Endpoint found but doesn't contain all the " + "required methods."); throw new XMLRPCUtilsException(Kind.MISSING_XMLRPC_METHOD, org.wordpress.android .R.string.xmlrpc_missing_method_error, url, null); } } catch (XMLRPCException e) { AppLog.e(AppLog.T.NUX, "system.listMethods failed on: " + url, e); if (isHTTPAuthErrorMessage(e)) { throw new XMLRPCUtilsException(Kind.HTTP_AUTH_REQUIRED, 0, url, null); } } catch (SSLHandshakeException | SSLPeerUnverifiedException e) { if (!WPUrlUtils.isWordPressCom(url)) { throw new XMLRPCUtilsException(Kind.ERRONEOUS_SSL_CERTIFICATE, 0, url, null); } AppLog.e(AppLog.T.NUX, "SSL error. Erroneous SSL certificate detected.", e); } catch (IOException | XmlPullParserException e) { AnalyticsTracker.track(AnalyticsTracker.Stat.LOGIN_FAILED_TO_GUESS_XMLRPC); AppLog.e(AppLog.T.NUX, "system.listMethods failed on: " + url, e); if (isHTTPAuthErrorMessage(e)) { throw new XMLRPCUtilsException(Kind.HTTP_AUTH_REQUIRED, 0, url, null); } } catch (IllegalArgumentException e) { // The XML-RPC client returns this error in case of redirect to an invalid URL. AnalyticsTracker.track(AnalyticsTracker.Stat.LOGIN_FAILED_TO_GUESS_XMLRPC); throw new XMLRPCUtilsException(Kind.INVALID_URL, org.wordpress.android.R.string .invalid_site_url_message, url, null); } return false; } public static String verifyOrDiscoverXmlRpcUrl(final String siteUrl, final String httpUsername, final String httpPassword) throws XMLRPCUtilsException { String xmlrpcUrl = XMLRPCUtils.verifyXmlrpcUrl(siteUrl, httpUsername, httpPassword); if (xmlrpcUrl == null) { AppLog.w(AppLog.T.NUX, "The XML-RPC endpoint was not found by using our 'smart' cleaning approach" + ". Time to start the Endpoint discovery process"); // Try to discover the XML-RPC Endpoint address xmlrpcUrl = XMLRPCUtils.discoverSelfHostedXmlrpcUrl(siteUrl, httpUsername, httpPassword); } // Validate the XML-RPC URL we've found before. This check prevents a crash that can occur // during the setup of self-hosted sites that have malformed xmlrpc URLs in their declaration. if (!URLUtil.isValidUrl(xmlrpcUrl)) { throw new XMLRPCUtilsException(Kind.NO_SITE_ERROR, R.string.invalid_site_url_message, xmlrpcUrl, null); } return xmlrpcUrl; } private static String verifyXmlrpcUrl(final String siteUrl, final String httpUsername, final String httpPassword) throws XMLRPCUtilsException { // Ordered set of Strings that contains the URLs we want to try. No discovery ;) final Set<String> urlsToTry = new LinkedHashSet<>(); final String sanitizedSiteUrlHttps = XMLRPCUtils.sanitizeSiteUrl(siteUrl, true); final String sanitizedSiteUrlHttp = XMLRPCUtils.sanitizeSiteUrl(siteUrl, false); // start by adding the https URL with 'xmlrpc.php'. This will be the first URL to try. urlsToTry.add(XMLRPCUtils.appendXMLRPCPath(sanitizedSiteUrlHttp)); urlsToTry.add(XMLRPCUtils.appendXMLRPCPath(sanitizedSiteUrlHttps)); // add the sanitized https URL without the '/xmlrpc.php' suffix added to it urlsToTry.add(sanitizedSiteUrlHttp); urlsToTry.add(sanitizedSiteUrlHttps); // add the user provided URL as well urlsToTry.add(siteUrl); AppLog.i(AppLog.T.NUX, "The app will call system.listMethods on the following URLs: " + urlsToTry); for (String url : urlsToTry) { try { if (XMLRPCUtils.checkXMLRPCEndpointValidity(url, httpUsername, httpPassword)) { // Endpoint found and works fine. return url; } } catch (XMLRPCUtilsException e) { if (e.kind == XMLRPCUtilsException.Kind.ERRONEOUS_SSL_CERTIFICATE || e.kind == XMLRPCUtilsException.Kind.HTTP_AUTH_REQUIRED || e.kind == XMLRPCUtilsException.Kind.MISSING_XMLRPC_METHOD) { throw e; } // swallow the error since we are just verifying various URLs continue; } catch (RuntimeException re) { // depending how corrupt the user entered URL is, it can generate several kind of runtime exceptions, // ignore them continue; } } // input url was not verified to be working return null; } // Attempts to retrieve the xmlrpc url for a self-hosted site. // See diagrams here https://github.com/wordpress-mobile/WordPress-Android/issues/3805 for details about the // whole process. private static String discoverSelfHostedXmlrpcUrl(String siteUrl, String httpUsername, String httpPassword) throws XMLRPCUtilsException { // Ordered set of Strings that contains the URLs we want to try final Set<String> urlsToTry = new LinkedHashSet<>(); // add the url as provided by the user urlsToTry.add(siteUrl); // add a sanitized version of the https url (if the user didn't specify it) urlsToTry.add(sanitizeSiteUrl(siteUrl, true)); // add a sanitized version of the http url (if the user didn't specify it) urlsToTry.add(sanitizeSiteUrl(siteUrl, false)); AppLog.i(AppLog.T.NUX, "The app will call the RSD discovery process on the following URLs: " + urlsToTry); String xmlrpcUrl = null; for (String currentURL : urlsToTry) { try { // Download the HTML content AppLog.i(AppLog.T.NUX, "Downloading the HTML content at the following URL: " + currentURL); String responseHTML = ApiHelper.getResponse(currentURL); if (TextUtils.isEmpty(responseHTML)) { AppLog.w(AppLog.T.NUX, "Content downloaded but it's empty or null. Skipping this URL"); continue; } // Try to find the RSD tag with a regex String rsdUrl = getRSDMetaTagHrefRegEx(responseHTML); // If the regex approach fails try to parse the HTML doc and retrieve the RSD tag. if (rsdUrl == null) { rsdUrl = getRSDMetaTagHref(responseHTML); } rsdUrl = UrlUtils.addUrlSchemeIfNeeded(rsdUrl, false); // if the RSD URL is empty here, try to see if there is already the pingback or the Apilink in the doc // the user could have inserted a direct link to the xml-rpc endpoint if (rsdUrl == null) { AppLog.i(AppLog.T.NUX, "Can't find the RSD endpoint in the HTML document. Try to check the " + "pingback tag, and the apiLink tag."); xmlrpcUrl = UrlUtils.addUrlSchemeIfNeeded(getXMLRPCPingback(responseHTML), false); if (xmlrpcUrl == null) { xmlrpcUrl = UrlUtils.addUrlSchemeIfNeeded(getXMLRPCApiLink(responseHTML), false); } } else { AppLog.i(AppLog.T.NUX, "RSD endpoint found at the following address: " + rsdUrl); AppLog.i(AppLog.T.NUX, "Downloading the RSD document..."); String rsdEndpointDocument = ApiHelper.getResponse(rsdUrl); if (TextUtils.isEmpty(rsdEndpointDocument)) { AppLog.w(AppLog.T.NUX, "Content downloaded but it's empty or null. Skipping this RSD document" + " URL."); continue; } AppLog.i(AppLog.T.NUX, "Extracting the XML-RPC Endpoint address from the RSD document"); xmlrpcUrl = UrlUtils.addUrlSchemeIfNeeded(getXMLRPCApiLink(rsdEndpointDocument), false); } if (xmlrpcUrl != null) { AppLog.i(AppLog.T.NUX, "Found the XML-RPC endpoint in the HTML document!!!"); break; } else { AppLog.i(AppLog.T.NUX, "XML-RPC endpoint NOT found"); } } catch (SSLHandshakeException e) { if (!WPUrlUtils.isWordPressCom(currentURL)) { throw new XMLRPCUtilsException(Kind.ERRONEOUS_SSL_CERTIFICATE, 0, currentURL, null); } AppLog.w(AppLog.T.NUX, "SSLHandshakeException failed. Erroneous SSL certificate detected."); return null; } catch (TimeoutError | TimeoutException e) { AppLog.w(AppLog.T.NUX, "Timeout error while connecting to the site: " + currentURL); throw new XMLRPCUtilsException(Kind.SITE_TIME_OUT, org.wordpress.android.R .string.site_timeout_error, currentURL, null); } } if (URLUtil.isValidUrl(xmlrpcUrl)) { if (checkXMLRPCEndpointValidity(xmlrpcUrl, httpUsername, httpPassword)) { // Endpoint found and works fine. return xmlrpcUrl; } } throw new XMLRPCUtilsException(Kind.NO_SITE_ERROR, org.wordpress.android.R.string.no_site_error, null, null); } public static List<Map<String, Object>> getUserBlogsList(URI xmlrpcUri, String username, String password, String httpUsername, String httpPassword) throws XMLRPCUtilsException { XMLRPCClientInterface client = XMLRPCFactory.instantiate(xmlrpcUri, httpUsername, httpPassword); Object[] params = { username, password }; try { Object[] userBlogs = (Object[]) client.call(ApiHelper.Method.GET_BLOGS, params); if (userBlogs == null) { // Could happen if the returned server response is truncated throw new XMLRPCUtilsException(Kind.XMLRPC_MALFORMED_RESPONSE, R.string.xmlrpc_malformed_response_error, xmlrpcUri.toString(), client.getResponse()); } Arrays.sort(userBlogs, BlogUtils.BlogNameComparator); List<Map<String, Object>> userBlogList = new ArrayList<>(); for (Object blog : userBlogs) { try { userBlogList.add((Map<String, Object>) blog); } catch (ClassCastException e) { AppLog.e(AppLog.T.NUX, "invalid data received from XMLRPC call wp.getUsersBlogs"); } } return userBlogList; } catch (XmlPullParserException parserException) { AppLog.e(AppLog.T.NUX, "invalid data received from XMLRPC call wp.getUsersBlogs", parserException); throw new XMLRPCUtilsException(Kind.XMLRPC_ERROR, R.string.xmlrpc_error, xmlrpcUri.toString(), client .getResponse()); } catch (XMLRPCFault xmlRpcFault) { AppLog.e(AppLog.T.NUX, "XMLRPCFault received from XMLRPC call wp.getUsersBlogs", xmlRpcFault); throw new XMLRPCUtilsException(Kind.XMLRPC_ERROR, handleXmlRpcFault(xmlRpcFault), xmlrpcUri.toString() , client.getResponse()); } catch (XMLRPCException xmlRpcException) { AppLog.e(AppLog.T.NUX, "XMLRPCException received from XMLRPC call wp.getUsersBlogs", xmlRpcException); throw new XMLRPCUtilsException(Kind.XMLRPC_ERROR, R.string.no_site_error, xmlrpcUri.toString(), client .getResponse()); } catch (SSLHandshakeException e) { if (!WPUrlUtils.isWordPressCom(xmlrpcUri.toString())) { throw new XMLRPCUtilsException(Kind.ERRONEOUS_SSL_CERTIFICATE, 0, xmlrpcUri.toString(), null); } AppLog.w(AppLog.T.NUX, "SSLHandshakeException failed. Erroneous SSL certificate detected."); } catch (ConnectTimeoutException e) { AppLog.e(AppLog.T.NUX, "Timeout exception when calling wp.getUsersBlogs", e); throw new XMLRPCUtilsException(Kind.SITE_TIME_OUT, R.string.site_timeout_error, xmlrpcUri.toString(), client.getResponse()); } catch (IOException e) { AppLog.e(AppLog.T.NUX, "Exception received from XMLRPC call wp.getUsersBlogs", e); throw new XMLRPCUtilsException(Kind.XMLRPC_ERROR, R.string.no_site_error, xmlrpcUri.toString(), client .getResponse()); } throw new XMLRPCUtilsException(Kind.XMLRPC_ERROR, R.string.no_site_error, xmlrpcUri.toString(), client .getResponse()); } /** * Regex pattern for matching the RSD link found in most WordPress sites. */ private static final Pattern rsdLink = Pattern.compile( "<link\\s*?rel=\"EditURI\"\\s*?type=\"application/rsd\\+xml\"\\s*?title=\"RSD\"\\s*?href=\"(.*?)\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); /** * Returns RSD URL based on regex match * * @return String RSD url */ private static String getRSDMetaTagHrefRegEx(String html) { if (html != null) { Matcher matcher = rsdLink.matcher(html); if (matcher.find()) { return matcher.group(1); } } return null; } /** * Returns RSD URL based on html tag search * * @return String RSD url */ private static String getRSDMetaTagHref(String data) { // parse the html and get the attribute for xmlrpc endpoint if (data != null) { // Many WordPress configs can output junk before the xml response (php warnings for example), this cleans // it. int indexOfFirstXML = data.indexOf("<?xml"); if (indexOfFirstXML > 0) { data = data.substring(indexOfFirstXML); } StringReader stringReader = new StringReader(data); XmlPullParser parser = Xml.newPullParser(); try { // auto-detect the encoding from the stream parser.setInput(stringReader); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String name; String rel = ""; String type = ""; String href = ""; switch (eventType) { case XmlPullParser.START_TAG: name = parser.getName(); if (name.equalsIgnoreCase("link")) { for (int i = 0; i < parser.getAttributeCount(); i++) { String attrName = parser.getAttributeName(i); String attrValue = parser.getAttributeValue(i); if (attrName.equals("rel")) { rel = attrValue; } else if (attrName.equals("type")) type = attrValue; else if (attrName.equals("href")) href = attrValue; } if (rel.equals("EditURI") && type.equals("application/rsd+xml")) { return href; } // currentMessage.setLink(parser.nextText()); } break; } eventType = parser.next(); } } catch (XmlPullParserException e) { AppLog.e(AppLog.T.API, e); return null; } catch (IOException e) { AppLog.e(AppLog.T.API, e); return null; } } return null; // never found the rsd tag } /** * Find the XML-RPC endpoint for the WordPress API. * * @return XML-RPC endpoint for the specified blog, or null if unable to discover endpoint. */ private static String getXMLRPCApiLink(String html) { Pattern xmlrpcLink = Pattern.compile("<api\\s*?name=\"WordPress\".*?apiLink=\"(.*?)\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); if (html != null) { Matcher matcher = xmlrpcLink.matcher(html); if (matcher.find()) { return matcher.group(1); } } return null; // never found the api link tag } /** * Find the XML-RPC endpoint by using the pingback tag * * @return String XML-RPC url */ private static String getXMLRPCPingback(String html) { Pattern pingbackLink = Pattern.compile( "<link\\s*?rel=\"pingback\"\\s*?href=\"(.*?)\"", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); if (html != null) { Matcher matcher = pingbackLink.matcher(html); if (matcher.find()) { return matcher.group(1); } } return null; } }
gpl-2.0
FauxFaux/jdk9-jdk
test/javax/sound/midi/Gervill/ModelByteBuffer/RandomFileInputStream/Available.java
3673
/* * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @summary Test ModelByteBuffer.RandomFileInputStream available() method @modules java.desktop/com.sun.media.sound */ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.*; import com.sun.media.sound.*; public class Available { static float[] testarray; static byte[] test_byte_array; static File test_file; static AudioFormat format = new AudioFormat(44100, 16, 1, true, false); static void setUp() throws Exception { testarray = new float[1024]; for (int i = 0; i < 1024; i++) { double ii = i / 1024.0; ii = ii * ii; testarray[i] = (float)Math.sin(10*ii*2*Math.PI); testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI); testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI); testarray[i] *= 0.3; } test_byte_array = new byte[testarray.length*2]; AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array); test_file = File.createTempFile("test", ".raw"); FileOutputStream fos = new FileOutputStream(test_file); fos.write(test_byte_array); } static void tearDown() throws Exception { if(!test_file.delete()) test_file.deleteOnExit(); } public static void main(String[] args) throws Exception { try { setUp(); for (int i = 0; i < 8; i++) { ModelByteBuffer buff; if(i % 2 == 0) buff = new ModelByteBuffer(test_file); else buff = new ModelByteBuffer(test_byte_array); if((i / 2) == 1) buff.subbuffer(5); if((i / 2) == 2) buff.subbuffer(5,500); if((i / 2) == 3) buff.subbuffer(5,600,true); long capacity = buff.capacity(); InputStream is = buff.getInputStream(); try { int ret = is.available(); if(ret != capacity) throw new RuntimeException("is.available() return unexpected value!"); } finally { is.close(); } if(buff.capacity() != capacity) throw new RuntimeException("Capacity variable should not change!"); } } finally { tearDown(); } } }
gpl-2.0
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/rm/fcom_ST0_ST7.java
2118
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.rm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fcom_ST0_ST7 extends Executable { public fcom_ST0_ST7(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { int newcode = 0xd; double freg0 = cpu.fpu.ST(0); double freg1 = cpu.fpu.ST(7); if (Double.isNaN(freg0) || Double.isNaN(freg1)) cpu.fpu.setInvalidOperation(); else { if (freg0 > freg1) newcode = 0; else if (freg0 < freg1) newcode = 1; else newcode = 8; } cpu.fpu.conditionCode &= 2; cpu.fpu.conditionCode |= newcode; return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0