text
stringlengths
7
1.01M
package com.capgemini.organizeIT.core.event.services; import com.capgemini.organizeIT.infrastructure.comment.repositories.CommentRepository; import com.capgemini.organizeIT.infrastructure.event.entities.Event; import com.capgemini.organizeIT.infrastructure.event.repositories.EventRepository; import com.capgemini.organizeIT.infrastructure.project.entities.Membership; import com.capgemini.organizeIT.infrastructure.project.entities.Ownership; import com.capgemini.organizeIT.infrastructure.project.entities.Project; import com.capgemini.organizeIT.infrastructure.project.repositories.ProjectRepository; import com.capgemini.organizeIT.infrastructure.user.entities.User; import com.capgemini.organizeIT.infrastructure.user.repositories.UserRepository; import lombok.RequiredArgsConstructor; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.springframework.core.io.InputStreamResource; import org.springframework.stereotype.Service; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @Service @RequiredArgsConstructor public class EventService { private final EventRepository eventRepository; private final UserRepository userRepository; public Optional<Event> findById(Long id) { return eventRepository.findById(id); } public InputStreamResource exportCSV() { ByteArrayInputStream byteArrayOutputStream; try (ByteArrayOutputStream out = new ByteArrayOutputStream(); CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out), CSVFormat.DEFAULT.withHeader(createCSVHeader()))) { createCSVBody().forEach(record -> { try { csvPrinter.printRecord(record); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } }); csvPrinter.flush(); byteArrayOutputStream = new ByteArrayInputStream(out.toByteArray()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } return new InputStreamResource(byteArrayOutputStream); } private String[] createCSVHeader() { return new String[]{ "firstName", "lastName", "email", "city", "shirtType", "shirtSize", "foodPreferences", "projectTitle", "projectStatus", "projectCity" }; } private List<List<String>> createCSVBody() { return userRepository.findAll().stream().map(user -> Stream.of(getUserInfo(user), getProjectInfo(user)) .flatMap(Collection::stream) .collect(Collectors.toList()) ).collect(Collectors.toList()); } private List<String> getUserInfo(User user) { return Arrays.asList(user.getFirstName(), user.getLastName(), user.getEmail(), user.getCity().toString(), user.getShirtType().toString(), user.getShirtSize().getSize(), user.getFoodPreferences()); } private List<String> getProjectInfo(User user) { List<String> projectInfo = new ArrayList<>(); user.getMemberships().stream().filter(Membership::getApproved).map(Membership::getProject).findAny().ifPresent(project -> { projectInfo.add(project.getTitle()); projectInfo.add(getProjectStatus(project)); projectInfo.add(project.getCity().toString()); }); //TODO: This overrides membership with ownership user.getOwnerships().stream().map(Ownership::getProject).findAny().ifPresent(project -> { projectInfo.clear(); projectInfo.add(project.getTitle()); projectInfo.add(getProjectStatus(project)); projectInfo.add(project.getCity().toString()); }); return projectInfo; } private String getProjectStatus(Project project) { //TODO: Note to self, projectStatus should be an enum if (project.getVerified()) { return "VERIFIED"; } else if (project.getConfirmed()) { return "CONFIRMED"; } else { return "UNVERIFIED"; } } public Event save(Event event) { return eventRepository.save(event); } }
/** * Copyright 2011-2021 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.dmdl.directio.text.csv; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Scanner; import java.util.function.Consumer; import java.util.zip.GZIPInputStream; import org.junit.Before; import org.junit.Test; import com.asakusafw.dmdl.directio.common.driver.GeneratorTesterRoot; import com.asakusafw.dmdl.directio.text.mock.EmptyLineFilter; import com.asakusafw.dmdl.directio.text.mock.UpperCaseTransformer; import com.asakusafw.dmdl.directio.text.tabular.TabularTextEmitterTest; import com.asakusafw.dmdl.java.emitter.driver.ObjectDriver; import com.asakusafw.runtime.directio.BinaryStreamFormat; import com.asakusafw.runtime.io.ModelInput; import com.asakusafw.runtime.io.ModelOutput; import com.asakusafw.runtime.value.IntOption; import com.asakusafw.runtime.value.LongOption; import com.asakusafw.runtime.value.StringOption; /** * Test for {@link CsvTextEmitter}. * @see TabularTextEmitterTest */ public class CsvTextEmitterTest extends GeneratorTesterRoot { /** * Initializes the test. * @throws Exception if some errors were occurred */ @Before public void setUp() throws Exception { emitDrivers.add(new CsvTextEmitter()); emitDrivers.add(new ObjectDriver()); } /** * simple case. * @throws Exception if failed */ @Test public void simple() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv", "simple = { value : TEXT; };", }); ModelWrapper model = loaded.newModel("Simple") .setOption("value", new StringOption("Hello, world!")); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getSupportedType(), is((Object) model.unwrap().getClass())); assertThat(support.getMinimumFragmentSize(), is(greaterThan(0L))); BinaryStreamFormat<Object> unsafe = unsafe(support); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (ModelOutput<Object> writer = unsafe.createOutput(unsafe.getSupportedType(), "hello", output)) { writer.write(model.unwrap()); } assertThat(text(output), is("\"Hello, world!\"\r\n")); Object buffer = loaded.newModel("Simple").unwrap(); try (ModelInput<Object> reader = unsafe.createInput(unsafe.getSupportedType(), "hello", in(output))) { assertThat(reader.readTo(buffer), is(true)); assertThat(buffer, is(model.unwrap())); assertThat(reader.readTo(buffer), is(false)); } } /** * w/ multiple rows/cols. * @throws Exception if failed */ @Test public void multiple() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv", "simple = {", " a : TEXT;", " b : TEXT;", " c : TEXT;", "};", }); byte[] contents = restore(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("0a")) .setOption("b", new StringOption("0b")) .setOption("c", new StringOption("0c")), loaded.newModel("Simple") .setOption("a", new StringOption("1a")) .setOption("b", new StringOption("1b")) .setOption("c", new StringOption("1c")), loaded.newModel("Simple") .setOption("a", new StringOption("2a")) .setOption("b", new StringOption("2b")) .setOption("c", new StringOption("2c"))); assertThat(text(contents), is("0a,0b,0c\r\n1a,1b,1c\r\n2a,2b,2c\r\n")); } /** * w/ {@code charset}. * @throws Exception if failed */ @Test public void charset() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " charset = 'UTF-16LE',", ")", "simple = {", " a : TEXT;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(-1L)); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("Hello, world!")); byte[] contents = write(loaded, model); assertThat(new String(contents, StandardCharsets.UTF_16LE), is("\"Hello, world!\"\r\n")); } /** * w/ {@code compression}. * @throws Exception if failed */ @Test public void compression() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " compression = gzip,", ")", "simple = {", " a : TEXT;", "};", }); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("Hello, world!")); byte[] contents = write(loaded, model); ByteArrayInputStream input = new ByteArrayInputStream(contents); try (Scanner s = new Scanner(new GZIPInputStream(input), StandardCharsets.UTF_8.name())) { assertThat(s.hasNextLine(), is(true)); assertThat(s.nextLine(), is("\"Hello, world!\"")); assertThat(s.hasNextLine(), is(false)); } } /** * w/ {@code line_separator}. * @throws Exception if failed */ @Test public void line_separator() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " line_separator = unix,", ")", "simple = {", " a : TEXT;", "};", }); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("Hello, world!")); byte[] contents = restore(loaded, model); assertThat(text(contents), is("\"Hello, world!\"\n")); } /** * w/ {@code field_separator}. * @throws Exception if failed */ @Test public void field_separator() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " field_separator = ':',", ")", "simple = {", " a : TEXT;", " b : TEXT;", " c : TEXT;", "};", }); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B")) .setOption("c", new StringOption("C")); byte[] contents = restore(loaded, model); assertThat(text(contents), is("A:B:C\r\n")); } /** * w/ {@code quote_character}. * @throws Exception if failed */ @Test public void quote_character() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " quote_character = '%',", ")", "simple = {", " a : TEXT;", "};", }); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("Hello, world!")); byte[] contents = restore(loaded, model); assertThat(text(contents), is("%Hello, world!%\r\n")); } /** * w/ {@code allow_linefeed}. * @throws Exception if failed */ @Test public void allow_linefeed() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " allow_linefeed = true,", ")", "simple = {", " a : TEXT;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(-1L)); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("Hello\nworld!")); byte[] contents = restore(loaded, model); assertThat(text(contents), is("\"Hello\nworld!\"\r\n")); } /** * w/ {@code quote_style}. * @throws Exception if failed */ @Test public void quote_style() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " quote_style = always,", ")", "simple = {", " a : TEXT;", "};", }); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("Hello!")); byte[] contents = restore(loaded, model); assertThat(text(contents), is("\"Hello!\"\r\n")); } /** * w/ {@code quote_style}. * @throws Exception if failed */ @Test public void quote_style_field() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv", "simple = {", " a : TEXT;", " @directio.text.field(quote_style = always)", " b : TEXT;", "};", }); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B")); byte[] contents = restore(loaded, model); assertThat(text(contents), is("A,\"B\"\r\n")); } /** * w/ {@code header}. * @throws Exception if failed */ @Test public void header() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " header = force,", ")", "simple = {", " @directio.text.field(name = 'Hello, world!')", " a : TEXT;", " b : TEXT;", "};", }); byte[] contents = restore(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B"))); assertThat(text(contents), is("\"Hello, world!\",b\r\nA,B\r\n")); } /** * w/ {@code header_quote_style}. * @throws Exception if failed */ @Test public void header_quote_style() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " header = force,", " header_quote_style = always,", ")", "simple = {", " a : TEXT;", " b : TEXT;", "};", }); byte[] contents = restore(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B"))); assertThat(text(contents), is("\"a\",\"b\"\r\nA,B\r\n")); } /** * w/ {@code quote_style} inherits to header. * @throws Exception if failed */ @Test public void quote_style_inherit_header() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " header = force,", " quote_style = always,", ")", "simple = {", " a : TEXT;", " b : TEXT;", "};", }); byte[] contents = restore(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B"))); assertThat(text(contents), is("\"a\",\"b\"\r\n\"A\",\"B\"\r\n")); } /** * w/ {@code header_quote_style}. * @throws Exception if failed */ @Test public void header_quote_style_override() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " header = force,", " quote_style = always,", " header_quote_style = never,", ")", "simple = {", " @directio.text.field(quote_style = always)", " a : TEXT;", " b : TEXT;", "};", }); byte[] contents = restore(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B"))); assertThat(text(contents), is("a,b\r\n\"A\",\"B\"\r\n")); } /** * w/ {@code input_transformer}. * @throws Exception if failed */ @Test public void input_transformer() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " input_transformer = '" + EmptyLineFilter.class.getName() + "'", ")", "simple = {", " a : TEXT;", "};", }); read(loaded, "\n\nHello!\n\n", wrapper -> { assertThat(wrapper.getOption("a"), is(new StringOption("Hello!"))); }); } /** * w/ {@code output_transformer}. * @throws Exception if failed */ @Test public void output_transformer() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " output_transformer = '" + UpperCaseTransformer.class.getName() + "'", ")", "simple = {", " a : TEXT;", "};", }); ModelWrapper model = loaded.newModel("Simple") .setOption("a", new StringOption("hello")); byte[] contents = write(loaded, model); assertThat(text(contents), is("HELLO\r\n")); } /** * w/ {@code directio.text.field}. * @throws Exception if failed */ @Test public void field_field() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv", "simple = {", " @directio.text.field", " a : TEXT;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(greaterThan(0L))); byte[] contents = write(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A"))); read(contents, loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A"))); assertThat(text(contents), is("A\r\n")); } /** * w/ {@code directio.text.ignore}. * @throws Exception if failed */ @Test public void field_ignore() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv", "simple = {", " a : TEXT;", " @directio.text.ignore", " b : TEXT;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(greaterThan(0L))); byte[] contents = write(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B"))); read(contents, loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption())); assertThat(text(contents), is("A\r\n")); } /** * w/ {@code directio.text.file_name}. * @throws Exception if failed */ @Test public void field_file_name() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv", "simple = {", " a : TEXT;", " @directio.text.file_name", " b : TEXT;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(greaterThan(0L))); byte[] contents = write(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("B"))); read(contents, loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new StringOption("testing"))); assertThat(text(contents), is("A\r\n")); } /** * w/ {@code directio.text.line_number}. * @throws Exception if failed */ @Test public void field_line_number() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " input_transformer = '" + EmptyLineFilter.class.getName() + "'", ")", "simple = {", " a : TEXT;", " @directio.text.line_number", " b : LONG;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(-1L)); byte[] contents = write(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new LongOption(-1))); assertThat(text(contents), is("A\r\n")); read(loaded, "\n\nHello!\n\n", wrapper -> { assertThat(wrapper.getOption("a"), is(new StringOption("Hello!"))); assertThat(wrapper.getOption("b"), is(new LongOption(3))); }); } /** * w/ {@code directio.text.line_number}. * @throws Exception if failed */ @Test public void field_line_number_int() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " input_transformer = '" + EmptyLineFilter.class.getName() + "'", ")", "simple = {", " a : TEXT;", " @directio.text.line_number", " b : INT;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(-1L)); byte[] contents = write(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new IntOption(-1))); assertThat(text(contents), is("A\r\n")); read(loaded, "\n\nHello!\n\n", wrapper -> { assertThat(wrapper.getOption("a"), is(new StringOption("Hello!"))); assertThat(wrapper.getOption("b"), is(new IntOption(3))); }); } /** * w/ {@code directio.text.record_number}. * @throws Exception if failed */ @Test public void field_record_number() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " input_transformer = '" + EmptyLineFilter.class.getName() + "'", ")", "simple = {", " a : TEXT;", " @directio.text.record_number", " b : LONG;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(-1L)); byte[] contents = write(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new LongOption(-1))); assertThat(text(contents), is("A\r\n")); read(loaded, "\n\nHello!\n\n", wrapper -> { assertThat(wrapper.getOption("a"), is(new StringOption("Hello!"))); assertThat(wrapper.getOption("b"), is(new LongOption(1))); }); } /** * w/ {@code directio.text.record_number}. * @throws Exception if failed */ @Test public void field_record_number_int() throws Exception { ModelLoader loaded = generateJavaFromLines(new String[] { "@directio.text.csv(", " input_transformer = '" + EmptyLineFilter.class.getName() + "'", ")", "simple = {", " a : TEXT;", " @directio.text.record_number", " b : INT;", "};", }); BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("text", "SimpleCsvTextFormat"); assertThat(support.getMinimumFragmentSize(), is(-1L)); byte[] contents = write(loaded, loaded.newModel("Simple") .setOption("a", new StringOption("A")) .setOption("b", new IntOption(-1))); assertThat(text(contents), is("A\r\n")); read(loaded, "\n\nHello!\n\n", wrapper -> { assertThat(wrapper.getOption("a"), is(new StringOption("Hello!"))); assertThat(wrapper.getOption("b"), is(new IntOption(1))); }); } /** * w/ malformed quote_character. * @throws Exception if failed */ @Test public void invalid_quote_character_malformed() throws Exception { shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " quote_character = '<>',", ")", "simple = {", " a : TEXT;", "};", }); } /** * quote_character conflict w/ line separator. * @throws Exception if failed */ @Test public void invalid_quote_character_conflict_line_separator() throws Exception { shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " quote_character = '\\r',", ")", "simple = {", " a : TEXT;", "};", }); shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " quote_character = '\\n',", ")", "simple = {", " a : TEXT;", "};", }); } /** * quote_character conflict w/ line separator. * @throws Exception if failed */ @Test public void invalid_quote_character_conflict_field_separator() throws Exception { shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " field_separator = ':',", " quote_character = ':',", ")", "simple = {", " a : TEXT;", "};", }); shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " quote_character = ',',", ")", "simple = {", " a : TEXT;", "};", }); } /** * true_format conflict w/ null_format. * @throws Exception if failed */ @Test public void invalid_true_format_conflict_null_format_inherited() throws Exception { shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " null_format = 'a',", ")", "simple = {", " @directio.text.field(true_format = 'a')", " a : BOOLEAN;", "};", }); } /** * false_format conflict w/ null_format. * @throws Exception if failed */ @Test public void invalid_false_format_conflict_null_format_inherited() throws Exception { shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " null_format = 'a',", ")", "simple = {", " @directio.text.field(false_format = 'a')", " a : BOOLEAN;", "};", }); } /** * false_format conflict w/ true_format. * @throws Exception if failed */ @Test public void invalid_false_format_conflict_true_format_inherited() throws Exception { shouldSemanticErrorFromLines(new String[] { "@directio.text.csv(", " true_format = 'a',", ")", "simple = {", " @directio.text.field(false_format = 'a')", " a : BOOLEAN;", "};", }); } /** * w/o valid fields. * @throws Exception if failed */ @Test public void invalid_field_empty() throws Exception { shouldSemanticErrorFromLines(new String[] { "@directio.text.csv", "simple = {", " @directio.text.ignore", " a : TEXT;", "};", }); } private static byte[] write(ModelLoader loaded, ModelWrapper... objects) { String name = objects[0].getModelClass().getSimpleName(); BinaryStreamFormat<Object> unsafe = unsafe(loaded.newObject("text", name + "CsvTextFormat")); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (ModelOutput<Object> writer = unsafe.createOutput(unsafe.getSupportedType(), "testing", output)) { for (ModelWrapper object : objects) { writer.write(object.unwrap()); } } catch (IOException | InterruptedException e) { throw new AssertionError(e); } return output.toByteArray(); } private static void read(ModelLoader loaded, String contents, Consumer<ModelWrapper> tester) { BinaryStreamFormat<Object> unsafe = unsafe(loaded.newObject("text", "SimpleCsvTextFormat")); ModelWrapper wrapper = loaded.newModel("Simple"); Object buffer = wrapper.unwrap(); try (ModelInput<Object> reader = unsafe.createInput(unsafe.getSupportedType(), "testing", in(contents))) { assertThat(reader.readTo(buffer), is(true)); tester.accept(wrapper); assertThat(reader.readTo(buffer), is(false)); } catch (IOException | InterruptedException e) { throw new AssertionError(e); } } private static void read( byte[] contents, ModelLoader loaded, ModelWrapper... objects) throws IOException, InterruptedException { String name = objects[0].getModelClass().getSimpleName(); BinaryStreamFormat<Object> unsafe = unsafe(loaded.newObject("text", name + "CsvTextFormat")); Object buffer = loaded.newModel(name).unwrap(); try (ModelInput<Object> reader = unsafe.createInput(unsafe.getSupportedType(), "testing", new ByteArrayInputStream(contents))) { for (ModelWrapper object : objects) { assertThat(reader.readTo(buffer), is(true)); assertThat(buffer, is(object.unwrap())); } assertThat(reader.readTo(buffer), is(false)); } } private byte[] restore(ModelLoader loaded, ModelWrapper... objects) throws IOException, InterruptedException { byte[] contents = write(loaded, objects); read(contents, loaded, objects); return contents; } @SuppressWarnings("unchecked") private static BinaryStreamFormat<Object> unsafe(Object support) { return (BinaryStreamFormat<Object>) support; } private static ByteArrayInputStream in(String contents) { return new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8)); } private static ByteArrayInputStream in(ByteArrayOutputStream output) { return new ByteArrayInputStream(output.toByteArray()); } private static String text(ByteArrayOutputStream output) { return text(output.toByteArray()); } private static String text(byte[] contents) { return new String(contents, StandardCharsets.UTF_8); } }
/******************************************************************************* * Copyright (C) 2018 Joao Sousa * * 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.rookit.test.generator; import com.google.inject.Provider; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.function.Supplier; @SuppressWarnings("javadoc") public interface Generator<T> extends Supplier<T>, Provider<T> { T createRandom(); @Override default T get() { return createRandom(); } List<T> createRandomList(); Set<T> createRandomSet(); T createRandomUnique(T item); Set<T> createRandomUniqueSet(Collection<T> items); }
/* * Copyright (c) 2010-2017 Evolveum * * 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.evolveum.midpoint.web.page.admin.resources; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.web.application.Url; import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; import com.evolveum.midpoint.web.component.search.*; import com.evolveum.midpoint.web.page.admin.PageAdminObjectList; import com.evolveum.midpoint.web.session.PageStorage; import com.evolveum.midpoint.web.session.SessionStorage; import com.evolveum.midpoint.web.session.UserProfileStorage; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.StringUtils; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import com.evolveum.midpoint.gui.api.GuiStyleConstants; import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; import com.evolveum.midpoint.gui.api.model.LoadableModel; import com.evolveum.midpoint.gui.api.page.PageBase; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.application.AuthorizationAction; import com.evolveum.midpoint.web.application.PageDescriptor; import com.evolveum.midpoint.web.component.data.Table; import com.evolveum.midpoint.web.component.data.column.ColumnMenuAction; import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; import com.evolveum.midpoint.web.component.util.SelectableBean; import com.evolveum.midpoint.web.page.admin.configuration.PageDebugView; import com.evolveum.midpoint.web.session.ResourcesStorage; import com.evolveum.midpoint.web.session.UserProfileStorage.TableId; import com.evolveum.midpoint.web.util.OnePageParameterEncoder; /** * @author lazyman */ @PageDescriptor( urls = { @Url(mountUrl = "/admin/resources", matchUrlForSecurity = "/admin/resources") }, action = { @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_RESOURCES_ALL_URL, label = "PageAdminResources.auth.resourcesAll.label", description = "PageAdminResources.auth.resourcesAll.description"), @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_RESOURCES_URL, label = "PageResources.auth.resources.label", description = "PageResources.auth.resources.description") }) public class PageResources extends PageAdminObjectList<ResourceType> { private static final long serialVersionUID = 1L; private static final Trace LOGGER = TraceManager.getTrace(PageResources.class); private static final String DOT_CLASS = PageResources.class.getName() + "."; private static final String OPERATION_TEST_RESOURCE = DOT_CLASS + "testResource"; private static final String OPERATION_DELETE_RESOURCES = DOT_CLASS + "deleteResources"; private static final String OPERATION_REFRESH_SCHEMA = DOT_CLASS + "refreshSchema"; private static final String ID_MAIN_FORM = "mainForm"; private static final String ID_TABLE = "table"; private static final String ID_CONNECTOR_TABLE = "connectorTable"; private ResourceType singleDelete; public PageResources() { this(""); } public PageResources(String searchText) { super(); if (StringUtils.isNotEmpty(searchText)){ initSearch(searchText); } } protected void initLayout(){ super.initLayout(); getObjectListPanel().setAdditionalBoxCssClasses(GuiStyleConstants.CLASS_OBJECT_RESOURCE_BOX_CSS_CLASSES); } private void initSearch(String text){ PageStorage storage = getSessionStorage().getPageStorageMap().get(SessionStorage.KEY_RESOURCES); if (storage == null) { storage = getSessionStorage().initPageStorage(SessionStorage.KEY_RESOURCES); } Search search = SearchFactory.createSearch(ResourceType.class, this); if (SearchBoxModeType.FULLTEXT.equals(search.getSearchType())){ search.setFullText(text); } else if (search.getItems() != null && search.getItems().size() > 0){ SearchItem searchItem = search.getItems().get(0); searchItem.getValues().add(new SearchValue<>(text)); } storage.setSearch(search); getSessionStorage().getPageStorageMap().put(SessionStorage.KEY_RESOURCES, storage); } @Override protected List<InlineMenuItem> createRowActions() { return PageResources.this.createRowMenuItems(); } @Override protected List<IColumn<SelectableBean<ResourceType>, String>> initColumns() { return PageResources.this.initResourceColumns(); } @Override protected void objectDetailsPerformed(AjaxRequestTarget target, ResourceType object) { PageResources.this.resourceDetailsPerformed(target, object.getOid()); } @Override protected void newObjectActionPerformed(AjaxRequestTarget target, CompiledObjectCollectionView collectionView) { navigateToNext(PageResourceWizard.class); } @Override protected Class<ResourceType> getType(){ return ResourceType.class; } @Override protected Collection<SelectorOptions<GetOperationOptions>> getQueryOptions(){ return getOperationOptionsBuilder() .noFetch() .item(ResourceType.F_CONNECTOR).resolve() .build(); } @Override protected UserProfileStorage.TableId getTableId(){ return UserProfileStorage.TableId.TABLE_RESOURCES; } private List<InlineMenuItem> createRowMenuItems() { List<InlineMenuItem> menuItems = new ArrayList<>(); menuItems.add(new ButtonInlineMenuItem(createStringResource("PageResources.inlineMenuItem.test")) { private static final long serialVersionUID = 1L; @Override public InlineMenuItemAction initAction() { return new ColumnMenuAction<SelectableBean<ResourceType>>() { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { SelectableBean<ResourceType> rowDto = getRowModel().getObject(); testResourcePerformed(target, rowDto.getValue()); } }; } @Override public boolean isHeaderMenuItem(){ return false; } @Override public String getButtonIconCssClass() { return GuiStyleConstants.CLASS_TEST_CONNECTION_MENU_ITEM; } }); menuItems.add(new ButtonInlineMenuItem(createStringResource("pageResources.button.editAsXml")) { private static final long serialVersionUID = 1L; @Override public InlineMenuItemAction initAction() { return new ColumnMenuAction<SelectableBean<ResourceType>>() { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { SelectableBean<ResourceType> rowDto = getRowModel().getObject(); editAsXmlPerformed(rowDto.getValue()); } }; } @Override public boolean isHeaderMenuItem(){ return false; } @Override public String getButtonIconCssClass() { return GuiStyleConstants.CLASS_EDIT_MENU_ITEM; } }); menuItems.add(new InlineMenuItem(createStringResource("pageResources.inlineMenuItem.editResource")) { private static final long serialVersionUID = 1L; @Override public InlineMenuItemAction initAction() { return new ColumnMenuAction<SelectableBean<ResourceType>>() { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { SelectableBean<ResourceType> rowDto = getRowModel().getObject(); editResourcePerformed(rowDto.getValue()); } }; } @Override public boolean isHeaderMenuItem(){ return false; } }); menuItems.add(new InlineMenuItem(createStringResource("pageResource.button.refreshSchema")) { private static final long serialVersionUID = 1L; @Override public InlineMenuItemAction initAction() { return new ColumnMenuAction<SelectableBean<ResourceType>>() { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { SelectableBean<ResourceType> rowDto = getRowModel().getObject(); refreshSchemaPerformed(rowDto.getValue(), target); } }; } @Override public boolean isHeaderMenuItem(){ return false; } }); menuItems.add(new ButtonInlineMenuItem(createStringResource("PageBase.button.delete")) { private static final long serialVersionUID = 1L; @Override public InlineMenuItemAction initAction() { return new ColumnMenuAction<SelectableBean<ResourceType>>() { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { if (getRowModel() == null) { deleteResourcePerformed(target, null); } else { SelectableBean<ResourceType> rowDto = getRowModel().getObject(); deleteResourcePerformed(target, rowDto.getValue()); } } }; } @Override public String getButtonIconCssClass() { return GuiStyleConstants.CLASS_DELETE_MENU_ITEM; } }); menuItems.add(new InlineMenuItem(createStringResource("pageResources.inlineMenuItem.deleteSyncToken")) { private static final long serialVersionUID = 1L; @Override public InlineMenuItemAction initAction() { return new ColumnMenuAction<SelectableBean<ResourceType>>() { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { SelectableBean<ResourceType> rowDto = getRowModel().getObject(); deleteResourceSyncTokenPerformed(target, rowDto.getValue()); } }; } @Override public boolean isHeaderMenuItem(){ return false; } }); return menuItems; } private List<IColumn<SelectableBean<ResourceType>, String>> initResourceColumns() { List<IColumn<SelectableBean<ResourceType>, String>> columns = new ArrayList<>(); columns.add(new PropertyColumn(createStringResource("pageResources.connectorType"), SelectableBean.F_VALUE + ".connector.connectorType")); columns.add(new PropertyColumn(createStringResource("pageResources.version"), SelectableBean.F_VALUE + ".connector.connectorVersion")); return columns; } private void resourceDetailsPerformed(AjaxRequestTarget target, String oid) { clearSessionStorageForResourcePage(); PageParameters parameters = new PageParameters(); parameters.add(OnePageParameterEncoder.PARAMETER, oid); navigateToNext(PageResource.class, parameters); } private List<ResourceType> isAnyResourceSelected(AjaxRequestTarget target, ResourceType single) { List<ResourceType> selected = null; if (single != null) { selected = new ArrayList<>(1); selected.add(single); return selected; } selected = getResourceTable().getSelectedObjects(); return selected; } private void refreshSchemaPerformed(ResourceType resource, AjaxRequestTarget target) { ConfirmationPanel dialog = new ConfirmationPanel(((PageBase)getPage()).getMainPopupBodyId(), createStringResource("pageResources.message.refreshResourceSchemaConfirm")){ @Override public void yesPerformed(AjaxRequestTarget target) { WebComponentUtil.refreshResourceSchema(resource.asPrismObject(), OPERATION_REFRESH_SCHEMA, target, PageResources.this); } }; ((PageBase)getPage()).showMainPopup(dialog, target); } private void deleteResourcePerformed(AjaxRequestTarget target, ResourceType single) { List<ResourceType> selected = isAnyResourceSelected(target, single); if (selected.size() < 1) { warn(createStringResource("pageResources.message.noResourceSelected").getString()); target.add(getFeedbackPanel()); return; } singleDelete = single; if (selected.isEmpty()) { return; } ConfirmationPanel dialog = new ConfirmationPanel(((PageBase)getPage()).getMainPopupBodyId(), createDeleteConfirmString("pageResources.message.deleteResourceConfirm", "pageResources.message.deleteResourcesConfirm", true)){ @Override public void yesPerformed(AjaxRequestTarget target) { deleteResourceConfirmedPerformed(target); } }; ((PageBase)getPage()).showMainPopup(dialog, target); } private MainObjectListPanel<ResourceType, CompiledObjectCollectionView> getResourceTable() { return (MainObjectListPanel<ResourceType, CompiledObjectCollectionView>) get(createComponentPath(ID_MAIN_FORM, ID_TABLE)); } /** * @param oneDeleteKey * message if deleting one item * @param moreDeleteKey * message if deleting more items * @param resources * if true selecting resources if false selecting from hosts */ private IModel<String> createDeleteConfirmString(final String oneDeleteKey, final String moreDeleteKey, final boolean resources) { return new IModel<String>() { @Override public String getObject() { List selected = new ArrayList(); if (singleDelete != null) { selected.add(singleDelete); } else { selected = getResourceTable().getSelectedObjects(); } switch (selected.size()) { case 1: Object first = selected.get(0); String name = WebComponentUtil.getName(((ResourceType) first)); return createStringResource(oneDeleteKey, name).getString(); default: return createStringResource(moreDeleteKey, selected.size()).getString(); } } }; } private void deleteResourceConfirmedPerformed(AjaxRequestTarget target) { List<ResourceType> selected = new ArrayList<>(); if (singleDelete != null) { selected.add(singleDelete); } else { selected = getResourceTable().getSelectedObjects(); } OperationResult result = new OperationResult(OPERATION_DELETE_RESOURCES); for (ResourceType resource : selected) { try { Task task = createSimpleTask(OPERATION_DELETE_RESOURCES); ObjectDelta<ResourceType> delta = getPrismContext().deltaFactory().object().createDeleteDelta(ResourceType.class, resource.getOid()); getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, task, result); } catch (Exception ex) { result.recordPartialError(createStringResource("PageResources.message.deleteResourceConfirmedPerformed.partialError").getString(), ex); LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete resource", ex); } } result.recomputeStatus(); if (result.isSuccess()) { result.recordStatus(OperationResultStatus.SUCCESS, createStringResource("PageResources.message.deleteResourceConfirmedPerformed.success").getString()); } getResourceTable().clearCache(); showResult(result); target.add(getFeedbackPanel(), (Component) getResourceTable()); } private void testResourcePerformed(AjaxRequestTarget target, ResourceType resourceType) { OperationResult result = new OperationResult(OPERATION_TEST_RESOURCE); if (StringUtils.isEmpty(resourceType.getOid())) { result.recordFatalError(createStringResource("PageResources.message.testResourcePerformed.partialError").getString()); } Task task = createSimpleTask(OPERATION_TEST_RESOURCE); try { result = getModelService().testResource(resourceType.getOid(), task); // todo de-duplicate code (see the same operation in PageResource) // this provides some additional tests, namely a test for schema // handling section getModelService().getObject(ResourceType.class, resourceType.getOid(), null, task, result); } catch (Exception ex) { result.recordFatalError("Failed to test resource connection", ex); } // a bit of hack: result of TestConnection contains a result of // getObject as a subresult // so in case of TestConnection succeeding we recompute the result to // show any (potential) getObject problems if (result.isSuccess()) { result.recomputeStatus(); } // if (!result.isSuccess()) { showResult(result); target.add(getFeedbackPanel()); // } target.add(getResourceTable()); } private void deleteResourceSyncTokenPerformed(AjaxRequestTarget target, ResourceType resourceType) { WebComponentUtil.deleteSyncTokenPerformed(target, resourceType, PageResources.this); } private void editResourcePerformed(ResourceType resourceType) { PageParameters parameters = new PageParameters(); parameters.add(OnePageParameterEncoder.PARAMETER, resourceType.getOid()); navigateToNext(new PageResourceWizard(parameters)); } private void editAsXmlPerformed(ResourceType resourceType) { PageParameters parameters = new PageParameters(); parameters.add(PageDebugView.PARAM_OBJECT_ID, resourceType.getOid()); parameters.add(PageDebugView.PARAM_OBJECT_TYPE, ResourceType.class.getSimpleName()); navigateToNext(PageDebugView.class, parameters); } private void clearSessionStorageForResourcePage() { ((PageBase) getPage()).getSessionStorage().clearResourceContentStorage(); } }
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.plugin.use.internal; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import org.gradle.api.Transformer; import org.gradle.groovy.scripts.ScriptSource; import org.gradle.internal.exceptions.LocationAwareException; import org.gradle.plugin.internal.InvalidPluginIdException; import org.gradle.plugin.internal.InvalidPluginVersionException; import org.gradle.plugin.management.internal.DefaultPluginRequest; import org.gradle.plugin.management.internal.InvalidPluginRequestException; import org.gradle.plugin.management.internal.PluginRequestInternal; import org.gradle.plugin.management.internal.PluginRequests; import org.gradle.plugin.use.PluginDependenciesSpec; import org.gradle.plugin.use.PluginDependencySpec; import org.gradle.plugin.use.PluginId; import org.gradle.util.internal.CollectionUtils; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.gradle.util.internal.CollectionUtils.collect; /** * The real delegate of the plugins {} block. * * The {@link PluginUseScriptBlockMetadataCompiler} interacts with this type. */ public class PluginRequestCollector { public static final String EMPTY_VALUE = "cannot be null or empty"; private final ScriptSource scriptSource; public PluginRequestCollector(ScriptSource scriptSource) { this.scriptSource = scriptSource; } private final List<PluginDependencySpecImpl> specs = new LinkedList<PluginDependencySpecImpl>(); public PluginDependenciesSpec createSpec(final int pluginsBlockLineNumber) { return new PluginDependenciesSpecImpl(pluginsBlockLineNumber); } public PluginRequests getPluginRequests() { if (specs.isEmpty()) { return PluginRequests.EMPTY; } return PluginRequests.of(listPluginRequests()); } @VisibleForTesting List<PluginRequestInternal> listPluginRequests() { List<PluginRequestInternal> pluginRequests = collect(specs, new Transformer<PluginRequestInternal, PluginDependencySpecImpl>() { @Override public PluginRequestInternal transform(PluginDependencySpecImpl original) { return new DefaultPluginRequest(original.id, original.version, original.apply, original.lineNumber, scriptSource); } }); Map<PluginId, Collection<PluginRequestInternal>> groupedById = CollectionUtils.groupBy(pluginRequests, new Transformer<PluginId, PluginRequestInternal>() { @Override public PluginId transform(PluginRequestInternal pluginRequest) { return pluginRequest.getId(); } }); // Check for duplicates for (PluginId key : groupedById.keySet()) { Collection<PluginRequestInternal> pluginRequestsForId = groupedById.get(key); if (pluginRequestsForId.size() > 1) { Iterator<PluginRequestInternal> iterator = pluginRequestsForId.iterator(); PluginRequestInternal first = iterator.next(); PluginRequestInternal second = iterator.next(); InvalidPluginRequestException exception = new InvalidPluginRequestException(second, "Plugin with id '" + key + "' was already requested at line " + first.getLineNumber()); throw new LocationAwareException(exception, second.getScriptDisplayName(), second.getLineNumber()); } } return pluginRequests; } private class PluginDependenciesSpecImpl implements PluginDependenciesSpec { private final int blockLineNumber; public PluginDependenciesSpecImpl(int blockLineNumber) { this.blockLineNumber = blockLineNumber; } @Override public PluginDependencySpec id(String id) { return id(id, blockLineNumber); } public PluginDependencySpec id(String id, int requestLineNumber) { PluginDependencySpecImpl spec = new PluginDependencySpecImpl(id, requestLineNumber); specs.add(spec); return spec; } } private static class PluginDependencySpecImpl implements PluginDependencySpec { private final PluginId id; private String version; private boolean apply; private final int lineNumber; private PluginDependencySpecImpl(String id, int lineNumber) { if (Strings.isNullOrEmpty(id)) { throw new InvalidPluginIdException(id, EMPTY_VALUE); } this.id = DefaultPluginId.of(id); this.apply = true; this.lineNumber = lineNumber; } @Override public PluginDependencySpec version(String version) { if (Strings.isNullOrEmpty(version)) { throw new InvalidPluginVersionException(version, EMPTY_VALUE); } this.version = version; return this; } @Override public PluginDependencySpec apply(boolean apply) { this.apply = apply; return this; } } }
package lc.common.util.math; import java.util.EnumSet; import java.util.Random; import net.minecraft.util.EnumFacing; /** * Vector orientation map. * * @author AfterLifeLochie * */ public enum Orientations { /** Not an orientation */ VOID(null, 0.0f), /** Cardinal north */ NORTH(Matrix3.turnRotations[0], 0.0f), /** Cardinal south */ SOUTH(Matrix3.turnRotations[2], 180.0f), /** Cardinal east */ EAST(Matrix3.turnRotations[1], 270.0f), /** Cardinal west */ WEST(Matrix3.turnRotations[3], 90.0f), /** Cardinal northeast */ NORTHEAST(Matrix3.ident, 45.0f), /** Cardinal southeast */ SOUTHEAST(Matrix3.ident, 135.0f), /** Cardinal southwest */ SOUTHWEST(Matrix3.ident, 225.0f), /** Cardinal northwest */ NORTHWEST(Matrix3.ident, 315.0f), /** Facing north-south */ NORTHSOUTH(Matrix3.ident, 0.0f), /** Facing east-west */ EASTWEST(Matrix3.ident, 90.0f); private final Matrix3 rotation; private final float angle; Orientations(Matrix3 rotation, float angle) { this.rotation = rotation; this.angle = angle; } /** * Get the rotation matrix for this Orientation, based around the zero * rotation * * @return The rotation matrix for this Orientation */ public Matrix3 rotation() { return rotation; } /** * Convert a EnumFacing facing to an Orientation facing * * @param dir * The source direction * @return The resultant Orientation */ public static Orientations from(EnumFacing dir) { switch (dir) { case NORTH: return Orientations.NORTH; case SOUTH: return Orientations.SOUTH; case EAST: return Orientations.EAST; case WEST: return Orientations.WEST; default: return Orientations.VOID; } } /** * @return A list of all cardinal directions */ public static EnumSet<Orientations> getCardinals() { return EnumSet.of(NORTH, EAST, SOUTH, WEST); } /** * @param r * The random number generator * @return A random cardinal */ public static Orientations randomCardinal(Random r) { return Orientations.values()[1 + r.nextInt(4)]; } /** * @return A list of all unique rotation cardinals */ public static EnumSet<Orientations> getFacings() { return EnumSet.of(NORTH, EAST); } /** * @return The angle of an Orientation's rotation */ public float angle() { return angle; } /** * @return The EnumFacing of this Orientation */ public EnumFacing forge() { switch (this) { case NORTH: return EnumFacing.NORTH; case SOUTH: return EnumFacing.SOUTH; case EAST: return EnumFacing.EAST; case WEST: return EnumFacing.WEST; default: return null; } } }
package com.moringaschool.allrecipe.models; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.parceler.Parcel; @Parcel public class RecipesResponse { @SerializedName("q") @Expose private String q; @SerializedName("from") @Expose private Integer from; @SerializedName("to") @Expose private Integer to; @SerializedName("more") @Expose private Boolean more; @SerializedName("count") @Expose private Integer count; @SerializedName("hits") @Expose private List<Hit> hits = null; /** * No args constructor for use in serialization * */ public RecipesResponse() { } /** * * @param hits * @param q * @param more * @param count * @param from * @param to */ public RecipesResponse(String q, Integer from, Integer to, Boolean more, Integer count, List<Hit> hits) { super(); this.q = q; this.from = from; this.to = to; this.more = more; this.count = count; this.hits = hits; } public String getQ() { return q; } public void setQ(String q) { this.q = q; } public Integer getFrom() { return from; } public void setFrom(Integer from) { this.from = from; } public Integer getTo() { return to; } public void setTo(Integer to) { this.to = to; } public Boolean getMore() { return more; } public void setMore(Boolean more) { this.more = more; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public List<Hit> getHits() { return hits; } public void setHits(List<Hit> hits) { this.hits = hits; } }
/* ******************************************************************************* * Copyright (c) 2018 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * 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.eclipse.microprofile.fault.tolerance.tck.fallbackmethod.beans; import javax.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.faulttolerance.Fallback; @ApplicationScoped public class FallbackMethodGenericDeepBeanA extends FallbackMethodGenericDeepBeanB<Long> { @Fallback(fallbackMethod = "fallback") public String method(int a, Long b) { throw new RuntimeException("test"); } }
/* * 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.catalina.loader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.security.AccessControlException; import java.security.AccessController; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Policy; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import javax.naming.Binding; import javax.naming.NameClassPair; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; import org.apache.catalina.Globals; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleState; import org.apache.naming.JndiPermission; import org.apache.naming.resources.ProxyDirContext; import org.apache.naming.resources.Resource; import org.apache.naming.resources.ResourceAttributes; import org.apache.tomcat.InstrumentableClassLoader; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.compat.JreCompat; import org.apache.tomcat.util.compat.JreVendor; import org.apache.tomcat.util.res.StringManager; /** * Specialized web application class loader. * <p> * This class loader is a full reimplementation of the * <code>URLClassLoader</code> from the JDK. It is designed to be fully * compatible with a normal <code>URLClassLoader</code>, although its internal * behavior may be completely different. * <p> * <strong>IMPLEMENTATION NOTE</strong> - By default, this class loader follows * the delegation model required by the specification. The system class * loader will be queried first, then the local repositories, and only then * delegation to the parent class loader will occur. This allows the web * application to override any shared class except the classes from J2SE. * Special handling is provided from the JAXP XML parser interfaces, the JNDI * interfaces, and the classes from the servlet API, which are never loaded * from the webapp repositories. The <code>delegate</code> property * allows an application to modify this behavior to move the parent class loader * ahead of the local repositories. * <p> * <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in Jasper * compilation technology, any repository which contains classes from * the servlet API will be ignored by the class loader. * <p> * <strong>IMPLEMENTATION NOTE</strong> - The class loader generates source * URLs which include the full JAR URL when a class is loaded from a JAR file, * which allows setting security permission at the class level, even when a * class is contained inside a JAR. * <p> * <strong>IMPLEMENTATION NOTE</strong> - Local repositories are searched in * the order they are added via the initial constructor and/or any subsequent * calls to <code>addRepository()</code> or <code>addJar()</code>. * <p> * <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or * security is made unless a security manager is present. * <p> * TODO: Is there any requirement to provide a proper Lifecycle implementation * rather than the current stubbed implementation? * <strong>IMPLEMENTATION NOTE</strong> - As of 7.0.64/8.0, this class * loader implements {@link InstrumentableClassLoader}, permitting web * application classes to instrument other classes in the same web * application. It does not permit instrumentation of system or container * classes or classes in other web apps. * * @author Remy Maucherat * @author Craig R. McClanahan */ public abstract class WebappClassLoaderBase extends URLClassLoader implements Lifecycle, InstrumentableClassLoader { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(WebappClassLoaderBase.class); private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); /** * List of ThreadGroup names to ignore when scanning for web application * started threads that need to be shut down. */ private static final List<String> JVM_THREAD_GROUP_NAMES = new ArrayList<String>(); private static final String JVM_THREAD_GROUP_SYSTEM = "system"; private static final String SERVICES_PREFIX = "META-INF/services/"; private static final String CLASS_FILE_SUFFIX = ".class"; private static final Manifest MANIFEST_UNKNOWN = new Manifest(); private static final Method GET_CLASSLOADING_LOCK_METHOD; protected static final StringManager sm = StringManager.getManager(Constants.Package); static { // Register this base class loader as parallel capable on Java 7+ JREs Method getClassLoadingLockMethod = null; try { if (JreCompat.isJre7Available()) { final Method registerParallel = ClassLoader.class.getDeclaredMethod("registerAsParallelCapable"); AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { registerParallel.setAccessible(true); return null; } }); registerParallel.invoke(null); getClassLoadingLockMethod = ClassLoader.class.getDeclaredMethod("getClassLoadingLock", String.class); } } catch (Exception e) { // ignore } GET_CLASSLOADING_LOCK_METHOD = getClassLoadingLockMethod; JVM_THREAD_GROUP_NAMES.add(JVM_THREAD_GROUP_SYSTEM); JVM_THREAD_GROUP_NAMES.add("RMI Runtime"); } protected class PrivilegedFindResourceByName implements PrivilegedAction<ResourceEntry> { protected String name; protected String path; protected boolean manifestRequired; PrivilegedFindResourceByName(String name, String path, boolean manifestRequired) { this.name = name; this.path = path; this.manifestRequired = manifestRequired; } @Override public ResourceEntry run() { return findResourceInternal(name, path, manifestRequired); } } protected static final class PrivilegedGetClassLoader implements PrivilegedAction<ClassLoader> { public Class<?> clazz; public PrivilegedGetClassLoader(Class<?> clazz){ this.clazz = clazz; } @Override public ClassLoader run() { return clazz.getClassLoader(); } } // ------------------------------------------------------- Static Variables /** * The set of trigger classes that will cause a proposed repository not * to be added if this class is visible to the class loader that loaded * this factory class. Typically, trigger classes will be listed for * components that have been integrated into the JDK for later versions, * but where the corresponding JAR files are required to run on * earlier versions. */ protected static final String[] triggers = { "javax.servlet.Servlet", "javax.el.Expression" // Servlet API }; /** * Set of package names which are not allowed to be loaded from a webapp * class loader without delegating first. */ protected static final String[] packageTriggers = { }; /** * Use anti JAR locking code, which does URL rerouting when accessing * resources. */ boolean antiJARLocking = false; // ----------------------------------------------------------- Constructors /** * Construct a new ClassLoader with no defined repositories and no * parent ClassLoader. */ public WebappClassLoaderBase() { super(new URL[0]); ClassLoader p = getParent(); if (p == null) { p = getSystemClassLoader(); } this.parent = p; ClassLoader j = String.class.getClassLoader(); if (j == null) { j = getSystemClassLoader(); while (j.getParent() != null) { j = j.getParent(); } } this.j2seClassLoader = j; securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } } /** * Construct a new ClassLoader with no defined repositories and the given * parent ClassLoader. * <p> * Method is used via reflection - * see {@link WebappLoader#createClassLoader()} * * @param parent Our parent class loader */ public WebappClassLoaderBase(ClassLoader parent) { super(new URL[0], parent); ClassLoader p = getParent(); if (p == null) { p = getSystemClassLoader(); } this.parent = p; ClassLoader j = String.class.getClassLoader(); if (j == null) { j = getSystemClassLoader(); while (j.getParent() != null) { j = j.getParent(); } } this.j2seClassLoader = j; securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } } // ----------------------------------------------------- Instance Variables /** * Associated directory context giving access to the resources in this * webapp. */ protected DirContext resources = null; /** * The cache of ResourceEntry for classes and resources we have loaded, * keyed by resource name. */ protected HashMap<String, ResourceEntry> resourceEntries = new HashMap<String, ResourceEntry>(); /** * The list of not found resources. */ protected HashMap<String, String> notFoundResources = new LinkedHashMap<String, String>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry( Map.Entry<String, String> eldest) { return size() > 1000; } }; /** * Should this class loader delegate to the parent class loader * <strong>before</strong> searching its own repositories (i.e. the * usual Java2 delegation model)? If set to <code>false</code>, * this class loader will search its own repositories first, and * delegate to the parent only if the class or resource is not * found locally. Note that the default, <code>false</code>, is * the behavior called for by the servlet specification. */ protected boolean delegate = false; /** * Last time a JAR was accessed. */ protected long lastJarAccessed = 0L; /** * The list of local repositories, in the order they should be searched * for locally loaded classes or resources. */ protected String[] repositories = new String[0]; /** * Repositories URLs, used to cache the result of getURLs. */ protected URL[] repositoryURLs = null; /** * Repositories translated as path in the work directory (for Jasper * originally), but which is used to generate fake URLs should getURLs be * called. */ protected File[] files = new File[0]; /** * The list of JARs, in the order they should be searched * for locally loaded classes or resources. */ protected JarFile[] jarFiles = new JarFile[0]; /** * The list of JARs, in the order they should be searched * for locally loaded classes or resources. */ protected File[] jarRealFiles = new File[0]; /** * The path which will be monitored for added Jar files. */ protected String jarPath = null; /** * The list of JARs, in the order they should be searched * for locally loaded classes or resources. */ protected String[] jarNames = new String[0]; /** * The list of JARs last modified dates, in the order they should be * searched for locally loaded classes or resources. */ protected long[] lastModifiedDates = new long[0]; /** * The list of resources which should be checked when checking for * modifications. */ protected String[] paths = new String[0]; /** * A list of read File and Jndi Permission's required if this loader * is for a web application context. */ protected ArrayList<Permission> permissionList = new ArrayList<Permission>(); /** * Path where resources loaded from JARs will be extracted. */ protected File loaderDir = null; protected String canonicalLoaderDir = null; /** * The PermissionCollection for each CodeSource for a web * application context. */ protected HashMap<String, PermissionCollection> loaderPC = new HashMap<String, PermissionCollection>(); /** * Instance of the SecurityManager installed. */ protected SecurityManager securityManager = null; /** * The parent class loader. */ protected ClassLoader parent = null; /** * The system class loader. */ protected ClassLoader system = null; /** * The bootstrap class loader used to load the JavaSE classes. In some * implementations this class loader is always <code>null</null> and in * those cases {@link ClassLoader#getParent()} will be called recursively on * the system class loader and the last non-null result used. */ protected ClassLoader j2seClassLoader; /** * Has this component been started? */ protected boolean started = false; /** * Has external repositories. */ protected boolean hasExternalRepositories = false; /** * Search external repositories first */ protected boolean searchExternalFirst = false; /** * need conversion for properties files */ protected boolean needConvert = false; /** * All permission. */ protected Permission allPermission = new java.security.AllPermission(); /** * Should Tomcat attempt to null out any static or final fields from loaded * classes when a web application is stopped as a work around for apparent * garbage collection bugs and application coding errors? There have been * some issues reported with log4j when this option is true. Applications * without memory leaks using recent JVMs should operate correctly with this * option set to <code>false</code>. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStatic = false; /** * Should Tomcat attempt to terminate threads that have been started by the * web application? Stopping threads is performed via the deprecated (for * good reason) <code>Thread.stop()</code> method and is likely to result in * instability. As such, enabling this should be viewed as an option of last * resort in a development environment and is not recommended in a * production environment. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStopThreads = false; /** * Should Tomcat attempt to terminate any {@link java.util.TimerThread}s * that have been started by the web application? If not specified, the * default value of <code>false</code> will be used. */ private boolean clearReferencesStopTimerThreads = false; /** * Should Tomcat call {@link org.apache.juli.logging.LogFactory#release()} * when the class loader is stopped? If not specified, the default value * of <code>true</code> is used. Changing the default setting is likely to * lead to memory leaks and other issues. */ private boolean clearReferencesLogFactoryRelease = true; /** * If an HttpClient keep-alive timer thread has been started by this web * application and is still running, should Tomcat change the context class * loader from the current {@link WebappClassLoaderBase} to * {@link WebappClassLoaderBase#parent} to prevent a memory leak? Note that * the keep-alive timer thread will stop on its own once the keep-alives all * expire however, on a busy system that might not happen for some time. */ private boolean clearReferencesHttpClientKeepAliveThread = true; /** * Name of associated context used with logging and JMX to associate with * the right web application. Particularly useful for the clear references * messages. Defaults to unknown but if standard Tomcat components are used * it will be updated during initialisation from the resources. */ private String contextName = "unknown"; /** * Holds the class file transformers decorating this class loader. The * CopyOnWriteArrayList is thread safe. It is expensive on writes, but * those should be rare. It is very fast on reads, since synchronization * is not actually used. Importantly, the ClassLoader will never block * iterating over the transformers while loading a class. */ private final List<ClassFileTransformer> transformers = new CopyOnWriteArrayList<ClassFileTransformer>(); /** * Code base to use for classes loaded from WEB-INF/classes. */ private URL webInfClassesCodeBase = null; // ------------------------------------------------------------- Properties /** * Get associated resources. */ public DirContext getResources() { return this.resources; } /** * Set associated resources. */ public void setResources(DirContext resources) { this.resources = resources; if (resources instanceof ProxyDirContext) { contextName = ((ProxyDirContext) resources).getContextName(); } } /** * Return the context name for this class loader. */ public String getContextName() { return (this.contextName); } /** * Return the "delegate first" flag for this class loader. */ public boolean getDelegate() { return (this.delegate); } /** * Set the "delegate first" flag for this class loader. * If this flag is true, this class loader delegates * to the parent class loader * <strong>before</strong> searching its own repositories, as * in an ordinary (non-servlet) chain of Java class loaders. * If set to <code>false</code> (the default), * this class loader will search its own repositories first, and * delegate to the parent only if the class or resource is not * found locally, as per the servlet specification. * * @param delegate The new "delegate first" flag */ public void setDelegate(boolean delegate) { this.delegate = delegate; } /** * @return Returns the antiJARLocking. */ public boolean getAntiJARLocking() { return antiJARLocking; } /** * @param antiJARLocking The antiJARLocking to set. */ public void setAntiJARLocking(boolean antiJARLocking) { this.antiJARLocking = antiJARLocking; } /** * @return Returns the searchExternalFirst. */ public boolean getSearchExternalFirst() { return searchExternalFirst; } /** * @param searchExternalFirst Whether external repositories should be searched first */ public void setSearchExternalFirst(boolean searchExternalFirst) { this.searchExternalFirst = searchExternalFirst; } /** * If there is a Java SecurityManager create a read FilePermission * or JndiPermission for the file directory path. * * @param filepath file directory path */ public void addPermission(String filepath) { if (filepath == null) { return; } String path = filepath; if (securityManager != null) { Permission permission = null; if (path.startsWith("jndi:") || path.startsWith("jar:jndi:")) { if (!path.endsWith("/")) { path = path + "/"; } permission = new JndiPermission(path + "*"); addPermission(permission); } else { if (!path.endsWith(File.separator)) { permission = new FilePermission(path, "read"); addPermission(permission); path = path + File.separator; } permission = new FilePermission(path + "-", "read"); addPermission(permission); } } } /** * If there is a Java SecurityManager create a read FilePermission * or JndiPermission for URL. * * @param url URL for a file or directory on local system */ public void addPermission(URL url) { if (url != null) { addPermission(url.toString()); } } /** * If there is a Java SecurityManager create a Permission. * * @param permission The permission */ public void addPermission(Permission permission) { if ((securityManager != null) && (permission != null)) { permissionList.add(permission); } } /** * Return the JAR path. */ public String getJarPath() { return this.jarPath; } /** * Change the Jar path. */ public void setJarPath(String jarPath) { this.jarPath = jarPath; } /** * Change the work directory. */ public void setWorkDir(File workDir) { this.loaderDir = new File(workDir, "loader"); if (loaderDir == null) { canonicalLoaderDir = null; } else { try { canonicalLoaderDir = loaderDir.getCanonicalPath(); if (!canonicalLoaderDir.endsWith(File.separator)) { canonicalLoaderDir += File.separator; } } catch (IOException ioe) { canonicalLoaderDir = null; } } } /** * Utility method for use in subclasses. * Must be called before Lifecycle methods to have any effect. * * @deprecated Will be removed in 8.0.x onwards. */ @Deprecated protected void setParentClassLoader(ClassLoader pcl) { parent = pcl; } /** * Return the clearReferencesStatic flag for this Context. */ public boolean getClearReferencesStatic() { return (this.clearReferencesStatic); } /** * Set the clearReferencesStatic feature for this Context. * * @param clearReferencesStatic The new flag value */ public void setClearReferencesStatic(boolean clearReferencesStatic) { this.clearReferencesStatic = clearReferencesStatic; } /** * Return the clearReferencesStopThreads flag for this Context. */ public boolean getClearReferencesStopThreads() { return (this.clearReferencesStopThreads); } /** * Set the clearReferencesStopThreads feature for this Context. * * @param clearReferencesStopThreads The new flag value */ public void setClearReferencesStopThreads( boolean clearReferencesStopThreads) { this.clearReferencesStopThreads = clearReferencesStopThreads; } /** * Return the clearReferencesStopTimerThreads flag for this Context. */ public boolean getClearReferencesStopTimerThreads() { return (this.clearReferencesStopTimerThreads); } /** * Set the clearReferencesStopTimerThreads feature for this Context. * * @param clearReferencesStopTimerThreads The new flag value */ public void setClearReferencesStopTimerThreads( boolean clearReferencesStopTimerThreads) { this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads; } /** * Return the clearReferencesLogFactoryRelease flag for this Context. */ public boolean getClearReferencesLogFactoryRelease() { return (this.clearReferencesLogFactoryRelease); } /** * Set the clearReferencesLogFactoryRelease feature for this Context. * * @param clearReferencesLogFactoryRelease The new flag value */ public void setClearReferencesLogFactoryRelease( boolean clearReferencesLogFactoryRelease) { this.clearReferencesLogFactoryRelease = clearReferencesLogFactoryRelease; } /** * Return the clearReferencesHttpClientKeepAliveThread flag for this * Context. */ public boolean getClearReferencesHttpClientKeepAliveThread() { return (this.clearReferencesHttpClientKeepAliveThread); } /** * Set the clearReferencesHttpClientKeepAliveThread feature for this * Context. * * @param clearReferencesHttpClientKeepAliveThread The new flag value */ public void setClearReferencesHttpClientKeepAliveThread( boolean clearReferencesHttpClientKeepAliveThread) { this.clearReferencesHttpClientKeepAliveThread = clearReferencesHttpClientKeepAliveThread; } // ------------------------------------------------------- Reloader Methods /** * Adds the specified class file transformer to this class loader. The * transformer will then be able to modify the bytecode of any classes * loaded by this class loader after the invocation of this method. * * @param transformer The transformer to add to the class loader */ @Override public void addTransformer(ClassFileTransformer transformer) { if (transformer == null) { throw new IllegalArgumentException(sm.getString( "webappClassLoader.addTransformer.illegalArgument", getContextName())); } if (this.transformers.contains(transformer)) { // if the same instance of this transformer was already added, bail out log.warn(sm.getString("webappClassLoader.addTransformer.duplicate", transformer, getContextName())); return; } this.transformers.add(transformer); log.info(sm.getString("webappClassLoader.addTransformer", transformer, getContextName())); } /** * Removes the specified class file transformer from this class loader. * It will no longer be able to modify the byte code of any classes * loaded by the class loader after the invocation of this method. * However, any classes already modified by this transformer will * remain transformed. * * @param transformer The transformer to remove */ @Override public void removeTransformer(ClassFileTransformer transformer) { if (transformer == null) { return; } if (this.transformers.remove(transformer)) { log.info(sm.getString("webappClassLoader.removeTransformer", transformer, getContextName())); return; } } protected void copyStateWithoutTransformers(WebappClassLoaderBase base) { base.antiJARLocking = this.antiJARLocking; base.resources = this.resources; base.files = this.files; base.delegate = this.delegate; base.lastJarAccessed = this.lastJarAccessed; base.repositories = this.repositories; base.jarPath = this.jarPath; base.loaderDir = this.loaderDir; base.canonicalLoaderDir = this.canonicalLoaderDir; base.clearReferencesStatic = this.clearReferencesStatic; base.clearReferencesStopThreads = this.clearReferencesStopThreads; base.clearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads; base.clearReferencesLogFactoryRelease = this.clearReferencesLogFactoryRelease; base.clearReferencesHttpClientKeepAliveThread = this.clearReferencesHttpClientKeepAliveThread; base.repositoryURLs = this.repositoryURLs.clone(); base.jarFiles = this.jarFiles.clone(); base.jarRealFiles = this.jarRealFiles.clone(); base.jarNames = this.jarNames.clone(); base.lastModifiedDates = this.lastModifiedDates.clone(); base.paths = this.paths.clone(); base.notFoundResources.putAll(this.notFoundResources); base.permissionList.addAll(this.permissionList); base.loaderPC.putAll(this.loaderPC); base.contextName = this.contextName; base.hasExternalRepositories = this.hasExternalRepositories; base.searchExternalFirst = this.searchExternalFirst; } /** * Add a new repository to the set of places this ClassLoader can look for * classes to be loaded. * * @param repository Name of a source of classes to be loaded, such as a * directory pathname, a JAR file pathname, or a ZIP file pathname * * @exception IllegalArgumentException if the specified repository is * invalid or does not exist */ public void addRepository(String repository) { // Ignore any of the standard repositories, as they are set up using // either addJar or addRepository if (repository.startsWith("/WEB-INF/lib") || repository.startsWith("/WEB-INF/classes")) return; // Add this repository to our underlying class loader try { URL url = new URL(repository); super.addURL(url); hasExternalRepositories = true; repositoryURLs = null; } catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException ("Invalid repository: " + repository); iae.initCause(e); throw iae; } } /** * Add a new repository to the set of places this ClassLoader can look for * classes to be loaded. * * @param repository Name of a source of classes to be loaded, such as a * directory pathname, a JAR file pathname, or a ZIP file pathname * * @exception IllegalArgumentException if the specified repository is * invalid or does not exist */ synchronized void addRepository(String repository, File file) { // Note : There should be only one (of course), but I think we should // keep this a bit generic if (repository == null) return; if (log.isDebugEnabled()) log.debug("addRepository(" + repository + ")"); int i; // Add this repository to our internal list String[] result = new String[repositories.length + 1]; for (i = 0; i < repositories.length; i++) { result[i] = repositories[i]; } result[repositories.length] = repository; repositories = result; // Add the file to the list File[] result2 = new File[files.length + 1]; for (i = 0; i < files.length; i++) { result2[i] = files[i]; } result2[files.length] = file; files = result2; } synchronized void addJar(String jar, JarFile jarFile, File file) throws IOException { if (jar == null) return; if (jarFile == null) return; if (file == null) return; if (log.isDebugEnabled()) log.debug("addJar(" + jar + ")"); int i; if ((jarPath != null) && (jar.startsWith(jarPath))) { String jarName = jar.substring(jarPath.length()); while (jarName.startsWith("/")) jarName = jarName.substring(1); String[] result = new String[jarNames.length + 1]; for (i = 0; i < jarNames.length; i++) { result[i] = jarNames[i]; } result[jarNames.length] = jarName; jarNames = result; } try { // Register the JAR for tracking long lastModified = ((ResourceAttributes) resources.getAttributes(jar)) .getLastModified(); String[] result = new String[paths.length + 1]; for (i = 0; i < paths.length; i++) { result[i] = paths[i]; } result[paths.length] = jar; paths = result; long[] result3 = new long[lastModifiedDates.length + 1]; for (i = 0; i < lastModifiedDates.length; i++) { result3[i] = lastModifiedDates[i]; } result3[lastModifiedDates.length] = lastModified; lastModifiedDates = result3; } catch (NamingException e) { // Ignore } // If the JAR currently contains invalid classes, don't actually use it // for classloading if (!validateJarFile(file)) return; JarFile[] result2 = new JarFile[jarFiles.length + 1]; for (i = 0; i < jarFiles.length; i++) { result2[i] = jarFiles[i]; } result2[jarFiles.length] = jarFile; jarFiles = result2; // Add the file to the list File[] result4 = new File[jarRealFiles.length + 1]; for (i = 0; i < jarRealFiles.length; i++) { result4[i] = jarRealFiles[i]; } result4[jarRealFiles.length] = file; jarRealFiles = result4; } /** * Return a String array of the current repositories for this class * loader. If there are no repositories, a zero-length array is * returned.For security reason, returns a clone of the Array (since * String are immutable). */ public String[] findRepositories() { return (repositories.clone()); } /** * Have one or more classes or resources been modified so that a reload * is appropriate? */ public boolean modified() { if (log.isDebugEnabled()) log.debug("modified()"); // Checking for modified loaded resources int length = paths.length; // A rare race condition can occur in the updates of the two arrays // It's totally ok if the latest class added is not checked (it will // be checked the next time int length2 = lastModifiedDates.length; if (length > length2) length = length2; for (int i = 0; i < length; i++) { try { long lastModified = ((ResourceAttributes) resources.getAttributes(paths[i])) .getLastModified(); if (lastModified != lastModifiedDates[i]) { if( log.isDebugEnabled() ) log.debug(" Resource '" + paths[i] + "' was modified; Date is now: " + new java.util.Date(lastModified) + " Was: " + new java.util.Date(lastModifiedDates[i])); return (true); } } catch (NamingException e) { log.error(" Resource '" + paths[i] + "' is missing"); return (true); } } length = jarNames.length; // Check if JARs have been added or removed if (getJarPath() != null) { try { NamingEnumeration<Binding> enumeration = resources.listBindings(getJarPath()); int i = 0; while (enumeration.hasMoreElements() && (i < length)) { NameClassPair ncPair = enumeration.nextElement(); String name = ncPair.getName(); // Ignore non JARs present in the lib folder if (!name.endsWith(".jar")) continue; if (!name.equals(jarNames[i])) { // Missing JAR log.info(" Additional JARs have been added : '" + name + "'"); return (true); } i++; } if (enumeration.hasMoreElements()) { while (enumeration.hasMoreElements()) { NameClassPair ncPair = enumeration.nextElement(); String name = ncPair.getName(); // Additional non-JAR files are allowed if (name.endsWith(".jar")) { // There was more JARs log.info(" Additional JARs have been added"); return (true); } } } else if (i < jarNames.length) { // There was less JARs log.info(" Additional JARs have been added"); return (true); } } catch (NamingException e) { if (log.isDebugEnabled()) log.debug(" Failed tracking modifications of '" + getJarPath() + "'"); } catch (ClassCastException e) { log.error(" Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage()); } } // No classes have been modified return (false); } /** * Render a String representation of this object. */ @Override public String toString() { StringBuilder sb = new StringBuilder(this.getClass().getSimpleName()); sb.append("\r\n context: "); sb.append(contextName); sb.append("\r\n delegate: "); sb.append(delegate); sb.append("\r\n repositories:\r\n"); if (repositories != null) { for (int i = 0; i < repositories.length; i++) { sb.append(" "); sb.append(repositories[i]); sb.append("\r\n"); } } if (this.parent != null) { sb.append("----------> Parent Classloader:\r\n"); sb.append(this.parent.toString()); sb.append("\r\n"); } if (this.transformers.size() > 0) { sb.append("----------> Class file transformers:\r\n"); for (ClassFileTransformer transformer : this.transformers) { sb.append(transformer).append("\r\n"); } } return (sb.toString()); } // ---------------------------------------------------- ClassLoader Methods /** * Add the specified URL to the classloader. */ @Override protected void addURL(URL url) { super.addURL(url); hasExternalRepositories = true; repositoryURLs = null; } /** * Expose this method for use by the unit tests. */ protected final Class<?> doDefineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain) { return super.defineClass(name, b, off, len, protectionDomain); } /** * Find the specified class in our local repositories, if possible. If * not found, throw <code>ClassNotFoundException</code>. * * @param name Name of the class to be loaded * * @exception ClassNotFoundException if the class was not found */ @Override public Class<?> findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); // Cannot load anything from local repositories if class loader is stopped if (!started) { throw new ClassNotFoundException(name); } // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0,i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class<?> clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); if (hasExternalRepositories && searchExternalFirst) { try { clazz = super.findClass(name); } catch(ClassNotFoundException cnfe) { // Ignore - will search internal repositories next } catch(AccessControlException ace) { log.warn("WebappClassLoaderBase.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null)) { try { clazz = findClassInternal(name); } catch(ClassNotFoundException cnfe) { if (!hasExternalRepositories || searchExternalFirst) { throw cnfe; } } catch(AccessControlException ace) { log.warn("WebappClassLoaderBase.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if ((clazz == null) && hasExternalRepositories && !searchExternalFirst) { try { clazz = super.findClass(name); } catch(AccessControlException ace) { log.warn("WebappClassLoaderBase.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if (clazz == null) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw new ClassNotFoundException(name); } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if (log.isTraceEnabled()) { ClassLoader cl; if (Globals.IS_SECURITY_ENABLED){ cl = AccessController.doPrivileged( new PrivilegedGetClassLoader(clazz)); } else { cl = clazz.getClassLoader(); } log.debug(" Loaded by " + cl.toString()); } return (clazz); } /** * Find the specified resource in our local repository, and return a * <code>URL</code> referring to it, or <code>null</code> if this resource * cannot be found. * * @param name Name of the resource to be found */ @Override public URL findResource(final String name) { if (log.isDebugEnabled()) log.debug(" findResource(" + name + ")"); URL url = null; if (hasExternalRepositories && searchExternalFirst) url = super.findResource(name); if (url == null) { ResourceEntry entry = resourceEntries.get(name); if (entry == null) { if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, name, false); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, name, false); } } if (entry != null) { url = entry.source; } } if ((url == null) && hasExternalRepositories && !searchExternalFirst) url = super.findResource(name); if (log.isDebugEnabled()) { if (url != null) log.debug(" --> Returning '" + url.toString() + "'"); else log.debug(" --> Resource not found, returning null"); } return (url); } /** * Return an enumeration of <code>URLs</code> representing all of the * resources with the given name. If no resources with this name are * found, return an empty enumeration. * * @param name Name of the resources to be found * * @exception IOException if an input/output error occurs */ @Override public Enumeration<URL> findResources(String name) throws IOException { if (log.isDebugEnabled()) log.debug(" findResources(" + name + ")"); //we use a LinkedHashSet instead of a Vector to avoid duplicates with virtualmappings LinkedHashSet<URL> result = new LinkedHashSet<URL>(); int jarFilesLength = jarFiles.length; int repositoriesLength = repositories.length; int i; // Adding the results of a call to the superclass if (hasExternalRepositories && searchExternalFirst) { Enumeration<URL> otherResourcePaths = super.findResources(name); while (otherResourcePaths.hasMoreElements()) { result.add(otherResourcePaths.nextElement()); } } // Looking at the repositories for (i = 0; i < repositoriesLength; i++) { try { String fullPath = repositories[i] + name; resources.lookup(fullPath); // Note : Not getting an exception here means the resource was // found try { result.add(getURI(new File(files[i], name))); } catch (MalformedURLException e) { // Ignore } } catch (NamingException e) { // Ignore } } // Looking at the JAR files synchronized (jarFiles) { if (openJARs()) { for (i = 0; i < jarFilesLength; i++) { JarEntry jarEntry = jarFiles[i].getJarEntry(name); if (jarEntry != null) { try { String jarFakeUrl = getURI(jarRealFiles[i]).toString(); jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name; result.add(new URL(jarFakeUrl)); } catch (MalformedURLException e) { // Ignore } } } } } // Adding the results of a call to the superclass if (hasExternalRepositories && !searchExternalFirst) { Enumeration<URL> otherResourcePaths = super.findResources(name); while (otherResourcePaths.hasMoreElements()) { result.add(otherResourcePaths.nextElement()); } } return Collections.enumeration(result); } /** * Find the resource with the given name. A resource is some data * (images, audio, text, etc.) that can be accessed by class code in a * way that is independent of the location of the code. The name of a * resource is a "/"-separated path name that identifies the resource. * If the resource cannot be found, return <code>null</code>. * <p> * This method searches according to the following algorithm, returning * as soon as it finds the appropriate URL. If the resource cannot be * found, returns <code>null</code>. * <ul> * <li>If the <code>delegate</code> property is set to <code>true</code>, * call the <code>getResource()</code> method of the parent class * loader, if any.</li> * <li>Call <code>findResource()</code> to find this resource in our * locally defined repositories.</li> * <li>Call the <code>getResource()</code> method of the parent class * loader, if any.</li> * </ul> * * @param name Name of the resource to return a URL for */ @Override public URL getResource(String name) { if (log.isDebugEnabled()) log.debug("getResource(" + name + ")"); URL url = null; // (1) Delegate to parent if requested if (delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader " + parent); url = parent.getResource(name); if (url != null) { if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return (url); } } // (2) Search local repositories url = findResource(name); if (url != null) { // Locating the repository for special handling in the case // of a JAR if (antiJARLocking) { ResourceEntry entry = resourceEntries.get(name); try { String repository = entry.codeBase.toString(); if ((repository.endsWith(".jar")) && (!(name.endsWith(CLASS_FILE_SUFFIX)))) { // Copy binary content to the work directory if not present File resourceFile = new File(loaderDir, name); url = getURI(resourceFile); } } catch (Exception e) { // Ignore } } if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return (url); } // (3) Delegate to parent unconditionally if not already attempted if( !delegate ) { url = parent.getResource(name); if (url != null) { if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return (url); } } // (4) Resource was not found if (log.isDebugEnabled()) log.debug(" --> Resource not found, returning null"); return (null); } /** * Find the resource with the given name, and return an input stream * that can be used for reading it. The search order is as described * for <code>getResource()</code>, after checking to see if the resource * data has been previously cached. If the resource cannot be found, * return <code>null</code>. * * @param name Name of the resource to return an input stream for */ @Override public InputStream getResourceAsStream(String name) { if (log.isDebugEnabled()) log.debug("getResourceAsStream(" + name + ")"); InputStream stream = null; // (0) Check for a cached copy of this resource stream = findLoadedResource(name); if (stream != null) { if (log.isDebugEnabled()) log.debug(" --> Returning stream from cache"); return (stream); } // (1) Delegate to parent if requested if (delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader " + parent); stream = parent.getResourceAsStream(name); if (stream != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return (stream); } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); URL url = findResource(name); if (url != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from local"); stream = findLoadedResource(name); try { if (hasExternalRepositories && (stream == null)) stream = url.openStream(); } catch (IOException e) { // Ignore } if (stream != null) return (stream); } // (3) Delegate to parent unconditionally if (!delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader unconditionally " + parent); stream = parent.getResourceAsStream(name); if (stream != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return (stream); } } // (4) Resource was not found if (log.isDebugEnabled()) log.debug(" --> Resource not found, returning null"); return (null); } /** * Load the class with the specified name. This method searches for * classes in the same manner as <code>loadClass(String, boolean)</code> * with <code>false</code> as the second argument. * * @param name Name of the class to be loaded * * @exception ClassNotFoundException if the class was not found */ @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return (loadClass(name, false)); } /** * Load the class with the specified name, searching using the following * algorithm until it finds and returns the class. If the class cannot * be found, returns <code>ClassNotFoundException</code>. * <ul> * <li>Call <code>findLoadedClass(String)</code> to check if the * class has already been loaded. If it has, the same * <code>Class</code> object is returned.</li> * <li>If the <code>delegate</code> property is set to <code>true</code>, * call the <code>loadClass()</code> method of the parent class * loader, if any.</li> * <li>Call <code>findClass()</code> to find this class in our locally * defined repositories.</li> * <li>Call the <code>loadClass()</code> method of our parent * class loader, if any.</li> * </ul> * If the class was found using the above steps, and the * <code>resolve</code> flag is <code>true</code>, this method will then * call <code>resolveClass(Class)</code> on the resulting Class object. * * @param name Name of the class to be loaded * @param resolve If <code>true</code> then resolve the class * * @exception ClassNotFoundException if the class was not found */ @SuppressWarnings("sync-override") @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLockInternal(name)) { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = j2seClassLoader.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); try { clazz = Class.forName(name, false, parent); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); try { clazz = Class.forName(name, false, parent); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } } throw new ClassNotFoundException(name); } private Object getClassLoadingLockInternal(String className) { if (JreCompat.isJre7Available() && GET_CLASSLOADING_LOCK_METHOD != null) { try { return GET_CLASSLOADING_LOCK_METHOD.invoke(this, className); } catch (Exception e) { // ignore } } return this; } /** * Get the Permissions for a CodeSource. If this instance * of WebappClassLoaderBase is for a web application context, * add read FilePermission or JndiPermissions for the base * directory (if unpacked), * the context URL, and jar file resources. * * @param codeSource where the code was loaded from * @return PermissionCollection for CodeSource */ @Override protected PermissionCollection getPermissions(CodeSource codeSource) { String codeUrl = codeSource.getLocation().toString(); PermissionCollection pc; if ((pc = loaderPC.get(codeUrl)) == null) { pc = super.getPermissions(codeSource); if (pc != null) { Iterator<Permission> perms = permissionList.iterator(); while (perms.hasNext()) { Permission p = perms.next(); pc.add(p); } loaderPC.put(codeUrl,pc); } } return (pc); } /** * Returns the search path of URLs for loading classes and resources. * This includes the original list of URLs specified to the constructor, * along with any URLs subsequently appended by the addURL() method. * @return the search path of URLs for loading classes and resources. */ @Override public URL[] getURLs() { if (repositoryURLs != null) { return repositoryURLs.clone(); } URL[] external = super.getURLs(); int filesLength = files.length; int jarFilesLength = jarRealFiles.length; int externalsLength = external.length; int off = 0; int i; try { URL[] urls = new URL[filesLength + jarFilesLength + externalsLength]; if (searchExternalFirst) { for (i = 0; i < externalsLength; i++) { urls[i] = external[i]; } off = externalsLength; } for (i = 0; i < filesLength; i++) { urls[off + i] = getURI(files[i]); } off += filesLength; for (i = 0; i < jarFilesLength; i++) { urls[off + i] = getURI(jarRealFiles[i]); } off += jarFilesLength; if (!searchExternalFirst) { for (i = 0; i < externalsLength; i++) { urls[off + i] = external[i]; } } repositoryURLs = urls; } catch (MalformedURLException e) { repositoryURLs = new URL[0]; } return repositoryURLs.clone(); } // ------------------------------------------------------ Lifecycle Methods /** * Add a lifecycle event listener to this component. * * @param listener The listener to add */ @Override public void addLifecycleListener(LifecycleListener listener) { // NOOP } /** * Get the lifecycle listeners associated with this lifecycle. If this * Lifecycle has no listeners registered, a zero-length array is returned. */ @Override public LifecycleListener[] findLifecycleListeners() { return new LifecycleListener[0]; } /** * Remove a lifecycle event listener from this component. * * @param listener The listener to remove */ @Override public void removeLifecycleListener(LifecycleListener listener) { // NOOP } /** * Obtain the current state of the source component. * * @return The current state of the source component. */ @Override public LifecycleState getState() { return LifecycleState.NEW; } /** * {@inheritDoc} */ @Override public String getStateName() { return getState().toString(); } @Override public void init() { // NOOP } /** * Start the class loader. * * @exception LifecycleException if a lifecycle error occurs */ @Override public void start() throws LifecycleException { started = true; String encoding = null; try { encoding = System.getProperty("file.encoding"); } catch (SecurityException e) { return; } if (encoding.indexOf("EBCDIC")!=-1) { needConvert = true; } for (int i = 0; i < repositories.length; i++) { if (repositories[i].equals("/WEB-INF/classes/")) { try { webInfClassesCodeBase = files[i].toURI().toURL(); } catch (MalformedURLException e) { // Ignore - leave it as null } break; } } } public boolean isStarted() { return started; } /** * Stop the class loader. * * @exception LifecycleException if a lifecycle error occurs */ @Override public void stop() throws LifecycleException { // Clearing references should be done before setting started to // false, due to possible side effects clearReferences(); started = false; int length = files.length; for (int i = 0; i < length; i++) { files[i] = null; } length = jarFiles.length; for (int i = 0; i < length; i++) { try { if (jarFiles[i] != null) { jarFiles[i].close(); } } catch (IOException e) { // Ignore } jarFiles[i] = null; } notFoundResources.clear(); resourceEntries.clear(); resources = null; repositories = null; repositoryURLs = null; files = null; jarFiles = null; jarRealFiles = null; jarPath = null; jarNames = null; lastModifiedDates = null; paths = null; hasExternalRepositories = false; parent = null; webInfClassesCodeBase = null; permissionList.clear(); loaderPC.clear(); if (loaderDir != null) { deleteDir(loaderDir); } } @Override public void destroy() { // NOOP } /** * Used to periodically signal to the classloader to release * JAR resources. */ public void closeJARs(boolean force) { if (jarFiles.length > 0) { synchronized (jarFiles) { if (force || (System.currentTimeMillis() > (lastJarAccessed + 90000))) { for (int i = 0; i < jarFiles.length; i++) { try { if (jarFiles[i] != null) { jarFiles[i].close(); jarFiles[i] = null; } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to close JAR", e); } } } } } } } // ------------------------------------------------------ Protected Methods protected ClassLoader getJavaseClassLoader() { return j2seClassLoader; } protected void setJavaseClassLoader(ClassLoader classLoader) { if (classLoader == null) { throw new IllegalArgumentException( sm.getString("webappClassLoader.javaseClassLoaderNull")); } j2seClassLoader = classLoader; } /** * Clear references. */ protected void clearReferences() { // De-register any remaining JDBC drivers clearReferencesJdbc(); // Stop any threads the web application started clearReferencesThreads(); // Check for leaks triggered by ThreadLocals loaded by this class loader checkThreadLocalsForLeaks(); // Clear RMI Targets loaded by this class loader clearReferencesRmiTargets(); // Null out any static or final fields from loaded classes, // as a workaround for apparent garbage collection bugs if (clearReferencesStatic) { clearReferencesStaticFinal(); } // Clear the IntrospectionUtils cache. IntrospectionUtils.clear(); // Clear the classloader reference in common-logging if (clearReferencesLogFactoryRelease) { org.apache.juli.logging.LogFactory.release(this); } // Clear the resource bundle cache // This shouldn't be necessary, the cache uses weak references but // it has caused leaks. Oddly, using the leak detection code in // standard host allows the class loader to be GC'd. This has been seen // on Sun but not IBM JREs. Maybe a bug in Sun's GC impl? clearReferencesResourceBundles(); // Clear the classloader reference in the VM's bean introspector java.beans.Introspector.flushCaches(); } /** * Deregister any JDBC drivers registered by the webapp that the webapp * forgot. This is made unnecessary complex because a) DriverManager * checks the class loader of the calling class (it would be much easier * if it checked the context class loader) b) using reflection would * create a dependency on the DriverManager implementation which can, * and has, changed. * * We can't just create an instance of JdbcLeakPrevention as it will be * loaded by the common class loader (since it's .class file is in the * $CATALINA_HOME/lib directory). This would fail DriverManager's check * on the class loader of the calling class. So, we load the bytes via * our parent class loader but define the class with this class loader * so the JdbcLeakPrevention looks like a webapp class to the * DriverManager. * * If only apps cleaned up after themselves... */ private final void clearReferencesJdbc() { InputStream is = getResourceAsStream( "org/apache/catalina/loader/JdbcLeakPrevention.class"); // We know roughly how big the class will be (~ 1K) so allow 2k as a // starting point byte[] classBytes = new byte[2048]; int offset = 0; try { int read = is.read(classBytes, offset, classBytes.length-offset); while (read > -1) { offset += read; if (offset == classBytes.length) { // Buffer full - double size byte[] tmp = new byte[classBytes.length * 2]; System.arraycopy(classBytes, 0, tmp, 0, classBytes.length); classBytes = tmp; } read = is.read(classBytes, offset, classBytes.length-offset); } Class<?> lpClass = defineClass("org.apache.catalina.loader.JdbcLeakPrevention", classBytes, 0, offset, this.getClass().getProtectionDomain()); Object obj = lpClass.newInstance(); @SuppressWarnings("unchecked") // clearJdbcDriverRegistrations() returns List<String> List<String> driverNames = (List<String>) obj.getClass().getMethod( "clearJdbcDriverRegistrations").invoke(obj); for (String name : driverNames) { log.error(sm.getString("webappClassLoader.clearJdbc", contextName, name)); } } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", contextName), t); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", contextName), ioe); } } } } private final void clearReferencesStaticFinal() { @SuppressWarnings("unchecked") // resourceEntries is HashMap<String, ResourceEntry> Collection<ResourceEntry> values = ((HashMap<String,ResourceEntry>) resourceEntries.clone()).values(); Iterator<ResourceEntry> loadedClasses = values.iterator(); // // walk through all loaded class to trigger initialization for // any uninitialized classes, otherwise initialization of // one class may call a previously cleared class. while(loadedClasses.hasNext()) { ResourceEntry entry = loadedClasses.next(); if (entry.loadedClass != null) { Class<?> clazz = entry.loadedClass; try { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if(Modifier.isStatic(fields[i].getModifiers())) { fields[i].get(null); break; } } } catch(Throwable t) { // Ignore } } } loadedClasses = values.iterator(); while (loadedClasses.hasNext()) { ResourceEntry entry = loadedClasses.next(); if (entry.loadedClass != null) { Class<?> clazz = entry.loadedClass; try { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) { continue; } if (Modifier.isStatic(mods)) { try { field.setAccessible(true); if (Modifier.isFinal(mods)) { if (!((field.getType().getName().startsWith("java.")) || (field.getType().getName().startsWith("javax.")))) { nullInstance(field.get(null)); } } else { field.set(null, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + clazz.getName()); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } } } } } private void nullInstance(Object instance) { if (instance == null) { return; } Field[] fields = instance.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) { continue; } try { field.setAccessible(true); if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) { // Doing something recursively is too risky continue; } Object value = field.get(instance); if (null != value) { Class<? extends Object> valueClass = value.getClass(); if (!loadedByThisOrChild(valueClass)) { if (log.isDebugEnabled()) { log.debug("Not setting field " + field.getName() + " to null in object of class " + instance.getClass().getName() + " because the referenced object was of type " + valueClass.getName() + " which was not loaded by this web application class loader."); } } else { field.set(instance, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + instance.getClass().getName()); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } } } } @SuppressWarnings("deprecation") // thread.stop() private void clearReferencesThreads() { Thread[] threads = getThreads(); List<Thread> executorThreadsToStop = new ArrayList<Thread>(); // Iterate over the set of threads for (Thread thread : threads) { if (thread != null) { ClassLoader ccl = thread.getContextClassLoader(); if (ccl == this) { // Don't warn about this thread if (thread == Thread.currentThread()) { continue; } // JVM controlled threads ThreadGroup tg = thread.getThreadGroup(); if (tg != null && JVM_THREAD_GROUP_NAMES.contains(tg.getName())) { // HttpClient keep-alive threads if (clearReferencesHttpClientKeepAliveThread && thread.getName().equals("Keep-Alive-Timer")) { thread.setContextClassLoader(parent); log.debug(sm.getString( "webappClassLoader.checkThreadsHttpClient")); } // Don't warn about remaining JVM controlled threads continue; } // Skip threads that have already died if (!thread.isAlive()) { continue; } // TimerThread can be stopped safely so treat separately // "java.util.TimerThread" in Sun/Oracle JDK // "java.util.Timer$TimerImpl" in Apache Harmony and in IBM JDK if (thread.getClass().getName().startsWith("java.util.Timer") && clearReferencesStopTimerThreads) { clearReferencesStopTimerThread(thread); continue; } if (isRequestThread(thread)) { log.error(sm.getString("webappClassLoader.warnRequestThread", contextName, thread.getName())); } else { log.error(sm.getString("webappClassLoader.warnThread", contextName, thread.getName())); } // Don't try an stop the threads unless explicitly // configured to do so if (!clearReferencesStopThreads) { continue; } // If the thread has been started via an executor, try // shutting down the executor boolean usingExecutor = false; try { // Runnable wrapped by Thread // "target" in Sun/Oracle JDK // "runnable" in IBM JDK // "action" in Apache Harmony Object target = null; for (String fieldName : new String[] { "target", "runnable", "action" }) { try { Field targetField = thread.getClass() .getDeclaredField(fieldName); targetField.setAccessible(true); target = targetField.get(thread); break; } catch (NoSuchFieldException nfe) { continue; } } // "java.util.concurrent" code is in public domain, // so all implementations are similar if (target != null && target.getClass().getCanonicalName() != null && target.getClass().getCanonicalName().equals( "java.util.concurrent.ThreadPoolExecutor.Worker")) { Field executorField = target.getClass().getDeclaredField("this$0"); executorField.setAccessible(true); Object executor = executorField.get(target); if (executor instanceof ThreadPoolExecutor) { ((ThreadPoolExecutor) executor).shutdownNow(); usingExecutor = true; } } } catch (SecurityException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); } catch (NoSuchFieldException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); } catch (IllegalArgumentException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); } catch (IllegalAccessException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), contextName), e); } if (usingExecutor) { // Executor may take a short time to stop all the // threads. Make a note of threads that should be // stopped and check them at the end of the method. executorThreadsToStop.add(thread); } else { // This method is deprecated and for good reason. This // is very risky code but is the only option at this // point. A *very* good reason for apps to do this // clean-up themselves. thread.stop(); } } } } // If thread stopping is enabled, executor threads should have been // stopped above when the executor was shut down but that depends on the // thread correctly handling the interrupt. Give all the executor // threads a few seconds shutdown and if they are still running // Give threads up to 2 seconds to shutdown int count = 0; for (Thread t : executorThreadsToStop) { while (t.isAlive() && count < 100) { try { Thread.sleep(20); } catch (InterruptedException e) { // Quit the while loop break; } count++; } if (t.isAlive()) { // This method is deprecated and for good reason. This is // very risky code but is the only option at this point. // A *very* good reason for apps to do this clean-up // themselves. t.stop(); } } } /* * Look at a threads stack trace to see if it is a request thread or not. It * isn't perfect, but it should be good-enough for most cases. */ private boolean isRequestThread(Thread thread) { StackTraceElement[] elements = thread.getStackTrace(); if (elements == null || elements.length == 0) { // Must have stopped already. Too late to ignore it. Assume not a // request processing thread. return false; } // Step through the methods in reverse order looking for calls to any // CoyoteAdapter method. All request threads will have this unless // Tomcat has been heavily modified - in which case there isn't much we // can do. for (int i = 0; i < elements.length; i++) { StackTraceElement element = elements[elements.length - (i+1)]; if ("org.apache.catalina.connector.CoyoteAdapter".equals( element.getClassName())) { return true; } } return false; } private void clearReferencesStopTimerThread(Thread thread) { // Need to get references to: // in Sun/Oracle JDK: // - newTasksMayBeScheduled field (in java.util.TimerThread) // - queue field // - queue.clear() // in IBM JDK, Apache Harmony: // - cancel() method (in java.util.Timer$TimerImpl) try { try { Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled"); newTasksMayBeScheduledField.setAccessible(true); Field queueField = thread.getClass().getDeclaredField("queue"); queueField.setAccessible(true); Object queue = queueField.get(thread); Method clearMethod = queue.getClass().getDeclaredMethod("clear"); clearMethod.setAccessible(true); synchronized(queue) { newTasksMayBeScheduledField.setBoolean(thread, false); clearMethod.invoke(queue); queue.notify(); // In case queue was already empty. } }catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } log.error(sm.getString("webappClassLoader.warnTimerThread", contextName, thread.getName())); } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); } } private void checkThreadLocalsForLeaks() { Thread[] threads = getThreads(); try { // Make the fields in the Thread class that store ThreadLocals // accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries"); expungeStaleEntriesMethod.setAccessible(true); for (int i = 0; i < threads.length; i++) { Object threadLocalMap; if (threads[i] != null) { // Clear the first map threadLocalMap = threadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } // Clear the second map threadLocalMap =inheritableThreadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), t); } } /** * Analyzes the given thread local map object. Also pass in the field that * points to the internal table to save re-calculating it on every * call to this method. */ private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (int j =0; j < table.length; j++) { Object obj = table[j]; if (obj != null) { boolean potentialLeak = false; // Check the key Object key = ((Reference<?>) obj).get(); if (this.equals(key) || loadedByThisOrChild(key)) { potentialLeak = true; } // Check the value Field valueField = obj.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(obj); if (this.equals(value) || loadedByThisOrChild(value)) { potentialLeak = true; } if (potentialLeak) { Object[] args = new Object[5]; args[0] = contextName; if (key != null) { args[1] = getPrettyClassName(key.getClass()); try { args[2] = key.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value != null) { args[3] = getPrettyClassName(value.getClass()); try { args[4] = value.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksDebug", args)); } } else { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks", args)); } } } } } } } private String getPrettyClassName(Class<?> clazz) { String name = clazz.getCanonicalName(); if (name==null){ name = clazz.getName(); } return name; } /** * @param o object to test, may be null * @return <code>true</code> if o has been loaded by the current classloader * or one of its descendants. */ private boolean loadedByThisOrChild(Object o) { if (o == null) { return false; } Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>) o; } else { clazz = o.getClass(); } ClassLoader cl = clazz.getClassLoader(); while (cl != null) { if (cl == this) { return true; } cl = cl.getParent(); } if (o instanceof Collection<?>) { Iterator<?> iter = ((Collection<?>) o).iterator(); try { while (iter.hasNext()) { Object entry = iter.next(); if (loadedByThisOrChild(entry)) { return true; } } } catch (ConcurrentModificationException e) { log.warn(sm.getString( "webappClassLoader", clazz.getName(), getContextName()), e); } } return false; } /* * Get the set of current threads as an array. */ private Thread[] getThreads() { // Get the current thread group ThreadGroup tg = Thread.currentThread().getThreadGroup(); // Find the root thread group try { while (tg.getParent() != null) { tg = tg.getParent(); } } catch (SecurityException se) { String msg = sm.getString( "webappClassLoader.getThreadGroupError", tg.getName()); if (log.isDebugEnabled()) { log.debug(msg, se); } else { log.warn(msg); } } int threadCountGuess = tg.activeCount() + 50; Thread[] threads = new Thread[threadCountGuess]; int threadCountActual = tg.enumerate(threads); // Make sure we don't miss any threads while (threadCountActual == threadCountGuess) { threadCountGuess *=2; threads = new Thread[threadCountGuess]; // Note tg.enumerate(Thread[]) silently ignores any threads that // can't fit into the array threadCountActual = tg.enumerate(threads); } return threads; } /** * This depends on the internals of the Sun JVM so it does everything by * reflection. */ private void clearReferencesRmiTargets() { try { // Need access to the ccl field of sun.rmi.transport.Target Class<?> objectTargetClass = Class.forName("sun.rmi.transport.Target"); Field cclField = objectTargetClass.getDeclaredField("ccl"); cclField.setAccessible(true); // Clear the objTable map Class<?> objectTableClass = Class.forName("sun.rmi.transport.ObjectTable"); Field objTableField = objectTableClass.getDeclaredField("objTable"); objTableField.setAccessible(true); Object objTable = objTableField.get(null); if (objTable == null) { return; } // Iterate over the values in the table if (objTable instanceof Map<?,?>) { Iterator<?> iter = ((Map<?,?>) objTable).values().iterator(); while (iter.hasNext()) { Object obj = iter.next(); Object cclObject = cclField.get(obj); if (this == cclObject) { iter.remove(); } } } // Clear the implTable map Field implTableField = objectTableClass.getDeclaredField("implTable"); implTableField.setAccessible(true); Object implTable = implTableField.get(null); if (implTable == null) { return; } // Iterate over the values in the table if (implTable instanceof Map<?,?>) { Iterator<?> iter = ((Map<?,?>) implTable).values().iterator(); while (iter.hasNext()) { Object obj = iter.next(); Object cclObject = cclField.get(obj); if (this == cclObject) { iter.remove(); } } } } catch (ClassNotFoundException e) { log.info(sm.getString("webappClassLoader.clearRmiInfo", contextName), e); } catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); } catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); } catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); } catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", contextName), e); } } /** * Clear the {@link ResourceBundle} cache of any bundles loaded by this * class loader or any class loader where this loader is a parent class * loader. Whilst {@link ResourceBundle#clearCache()} could be used there * are complications around the * {@link org.apache.jasper.servlet.JasperLoader} that mean a reflection * based approach is more likely to be complete. * * The ResourceBundle is using WeakReferences so it shouldn't be pinning the * class loader in memory. However, it is. Therefore clear ou the * references. */ private void clearReferencesResourceBundles() { // Get a reference to the cache try { Field cacheListField = ResourceBundle.class.getDeclaredField("cacheList"); cacheListField.setAccessible(true); // Java 6 uses ConcurrentMap // Java 5 uses SoftCache extends Abstract Map // So use Map and it *should* work with both Map<?,?> cacheList = (Map<?,?>) cacheListField.get(null); // Get the keys (loader references are in the key) Set<?> keys = cacheList.keySet(); Field loaderRefField = null; // Iterate over the keys looking at the loader instances Iterator<?> keysIter = keys.iterator(); int countRemoved = 0; while (keysIter.hasNext()) { Object key = keysIter.next(); if (loaderRefField == null) { loaderRefField = key.getClass().getDeclaredField("loaderRef"); loaderRefField.setAccessible(true); } WeakReference<?> loaderRef = (WeakReference<?>) loaderRefField.get(key); ClassLoader loader = (ClassLoader) loaderRef.get(); while (loader != null && loader != this) { loader = loader.getParent(); } if (loader != null) { keysIter.remove(); countRemoved++; } } if (countRemoved > 0 && log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesCount", Integer.valueOf(countRemoved), contextName)); } } catch (SecurityException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } catch (NoSuchFieldException e) { if (JreVendor.IS_ORACLE_JVM) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", getContextName()), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", getContextName()), e); } } catch (IllegalArgumentException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } catch (IllegalAccessException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", contextName), e); } } /** * Used to periodically signal to the classloader to release JAR resources. */ protected boolean openJARs() { if (started && (jarFiles.length > 0)) { lastJarAccessed = System.currentTimeMillis(); if (jarFiles[0] == null) { for (int i = 0; i < jarFiles.length; i++) { try { jarFiles[i] = new JarFile(jarRealFiles[i]); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to open JAR", e); } return false; } } } } return true; } /** * Find specified class in local repositories. * * @return the loaded class, or null if the class isn't found */ protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + CLASS_FILE_SUFFIX; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath, true); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath, true); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (getClassLoadingLockInternal(name)) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; } /** * Find specified resource in local repositories. * * @return the loaded resource, or null if the resource isn't found */ protected ResourceEntry findResourceInternal(File file, String path){ ResourceEntry entry = new ResourceEntry(); try { entry.source = getURI(new File(file, path)); String sourceString = entry.source.toString(); if (sourceString.startsWith(webInfClassesCodeBase.toString()) && sourceString.endsWith(CLASS_FILE_SUFFIX)) { entry.codeBase = webInfClassesCodeBase; } else { entry.codeBase = entry.source; } } catch (MalformedURLException e) { return null; } return entry; } /** * Find specified resource in local repositories. * * @return the loaded resource, or null if the resource isn't found */ protected ResourceEntry findResourceInternal(final String name, final String path, final boolean manifestRequired) { if (!started) { log.info(sm.getString("webappClassLoader.stopped", name)); return null; } if ((name == null) || (path == null)) return null; JarEntry jarEntry = null; ResourceEntry entry = resourceEntries.get(name); if (entry != null) { if (manifestRequired && entry.manifest == MANIFEST_UNKNOWN) { // This resource was added to the cache when a request was made // for the resource that did not need the manifest. Now the // manifest is required, the cache entry needs to be updated. synchronized (jarFiles) { if (openJARs()) { for (int i = 0; i < jarFiles.length; i++) { jarEntry = jarFiles[i].getJarEntry(path); if (jarEntry != null) { try { entry.manifest = jarFiles[i].getManifest(); } catch (IOException ioe) { // Ignore } break; } } } } } return entry; } int contentLength = -1; InputStream binaryStream = null; boolean isClassResource = path.endsWith(CLASS_FILE_SUFFIX); boolean isCacheable = isClassResource; if (!isCacheable) { isCacheable = path.startsWith(SERVICES_PREFIX); } int jarFilesLength = jarFiles.length; int repositoriesLength = repositories.length; int i; Resource resource = null; boolean fileNeedConvert = false; for (i = 0; (entry == null) && (i < repositoriesLength); i++) { try { String fullPath = repositories[i] + path; Object lookupResult = resources.lookup(fullPath); if (lookupResult instanceof Resource) { resource = (Resource) lookupResult; } // Note : Not getting an exception here means the resource was // found ResourceAttributes attributes = (ResourceAttributes) resources.getAttributes(fullPath); contentLength = (int) attributes.getContentLength(); String canonicalPath = attributes.getCanonicalPath(); if (canonicalPath != null) { // we create the ResourceEntry based on the information returned // by the DirContext rather than just using the path to the // repository. This allows to have smart DirContext implementations // that "virtualize" the docbase (e.g. Eclipse WTP) entry = findResourceInternal(new File(canonicalPath), ""); } else { // probably a resource not in the filesystem (e.g. in a // packaged war) entry = findResourceInternal(files[i], path); } entry.lastModified = attributes.getLastModified(); if (resource != null) { try { binaryStream = resource.streamContent(); } catch (IOException e) { return null; } if (needConvert) { if (path.endsWith(".properties")) { fileNeedConvert = true; } } // Register the full path for modification checking // Note: Only syncing on a 'constant' object is needed synchronized (allPermission) { int j; long[] result2 = new long[lastModifiedDates.length + 1]; for (j = 0; j < lastModifiedDates.length; j++) { result2[j] = lastModifiedDates[j]; } result2[lastModifiedDates.length] = entry.lastModified; lastModifiedDates = result2; String[] result = new String[paths.length + 1]; for (j = 0; j < paths.length; j++) { result[j] = paths[j]; } result[paths.length] = fullPath; paths = result; } } } catch (NamingException e) { // Ignore } } if ((entry == null) && (notFoundResources.containsKey(name))) return null; synchronized (jarFiles) { try { if (!openJARs()) { return null; } for (i = 0; (entry == null) && (i < jarFilesLength); i++) { jarEntry = jarFiles[i].getJarEntry(path); if (jarEntry != null) { entry = new ResourceEntry(); try { entry.codeBase = getURI(jarRealFiles[i]); String jarFakeUrl = entry.codeBase.toString(); jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path; entry.source = new URL(jarFakeUrl); entry.lastModified = jarRealFiles[i].lastModified(); } catch (MalformedURLException e) { return null; } contentLength = (int) jarEntry.getSize(); try { if (manifestRequired) { entry.manifest = jarFiles[i].getManifest(); } else { entry.manifest = MANIFEST_UNKNOWN; } binaryStream = jarFiles[i].getInputStream(jarEntry); } catch (IOException e) { return null; } // Extract resources contained in JAR to the workdir if (antiJARLocking && !(path.endsWith(CLASS_FILE_SUFFIX))) { byte[] buf = new byte[1024]; File resourceFile = new File (loaderDir, jarEntry.getName()); if (!resourceFile.exists()) { Enumeration<JarEntry> entries = jarFiles[i].entries(); while (entries.hasMoreElements()) { JarEntry jarEntry2 = entries.nextElement(); if (!(jarEntry2.isDirectory()) && (!jarEntry2.getName().endsWith (CLASS_FILE_SUFFIX))) { resourceFile = new File (loaderDir, jarEntry2.getName()); try { if (!resourceFile.getCanonicalPath().startsWith( canonicalLoaderDir)) { throw new IllegalArgumentException( sm.getString("webappClassLoader.illegalJarPath", jarEntry2.getName())); } } catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); } File parentFile = resourceFile.getParentFile(); if (!parentFile.mkdirs() && !parentFile.exists()) { // Ignore the error (like the IOExceptions below) } FileOutputStream os = null; InputStream is = null; try { is = jarFiles[i].getInputStream (jarEntry2); os = new FileOutputStream (resourceFile); while (true) { int n = is.read(buf); if (n <= 0) { break; } os.write(buf, 0, n); } resourceFile.setLastModified( jarEntry2.getTime()); } catch (IOException e) { // Ignore } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } try { if (os != null) { os.close(); } } catch (IOException e) { // Ignore } } } } } } } } if (entry == null) { synchronized (notFoundResources) { notFoundResources.put(name, name); } return null; } /* Only cache the binary content if there is some content * available one of the following is true: * a) It is a class file since the binary content is only cached * until the class has been loaded * or * b) The file needs conversion to address encoding issues (see * below) * or * c) The resource is a service provider configuration file located * under META=INF/services * * In all other cases do not cache the content to prevent * excessive memory usage if large resources are present (see * https://bz.apache.org/bugzilla/show_bug.cgi?id=53081). */ if (binaryStream != null && (isCacheable || fileNeedConvert)) { byte[] binaryContent = new byte[contentLength]; int pos = 0; try { while (true) { int n = binaryStream.read(binaryContent, pos, binaryContent.length - pos); if (n <= 0) break; pos += n; } } catch (IOException e) { log.error(sm.getString("webappClassLoader.readError", name), e); return null; } if (fileNeedConvert) { // Workaround for certain files on platforms that use // EBCDIC encoding, when they are read through FileInputStream. // See commit message of rev.303915 for details // http://svn.apache.org/viewvc?view=revision&revision=303915 String str = new String(binaryContent,0,pos); try { binaryContent = str.getBytes(CHARSET_UTF8); } catch (Exception e) { return null; } } entry.binaryContent = binaryContent; // The certificates are only available after the JarEntry // associated input stream has been fully read if (jarEntry != null) { entry.certificates = jarEntry.getCertificates(); } } } finally { if (binaryStream != null) { try { binaryStream.close(); } catch (IOException e) { /* Ignore */} } } } if (isClassResource && entry.binaryContent != null && this.transformers.size() > 0) { // If the resource is a class just being loaded, decorate it // with any attached transformers String className = name.endsWith(CLASS_FILE_SUFFIX) ? name.substring(0, name.length() - CLASS_FILE_SUFFIX.length()) : name; String internalName = className.replace(".", "/"); for (ClassFileTransformer transformer : this.transformers) { try { byte[] transformed = transformer.transform( this, internalName, null, null, entry.binaryContent ); if (transformed != null) { entry.binaryContent = transformed; } } catch (IllegalClassFormatException e) { log.error(sm.getString("webappClassLoader.transformError", name), e); return null; } } } // Add the entry in the local resource repository synchronized (resourceEntries) { // Ensures that all the threads which may be in a race to load // a particular class all end up with the same ResourceEntry // instance ResourceEntry entry2 = resourceEntries.get(name); if (entry2 == null) { resourceEntries.put(name, entry); } else { entry = entry2; } } return entry; } /** * Returns true if the specified package name is sealed according to the * given manifest. */ protected boolean isPackageSealed(String name, Manifest man) { String path = name.replace('.', '/') + '/'; Attributes attr = man.getAttributes(path); String sealed = null; if (attr != null) { sealed = attr.getValue(Name.SEALED); } if (sealed == null) { if ((attr = man.getMainAttributes()) != null) { sealed = attr.getValue(Name.SEALED); } } return "true".equalsIgnoreCase(sealed); } /** * Finds the resource with the given name if it has previously been * loaded and cached by this class loader, and return an input stream * to the resource data. If this resource has not been cached, return * <code>null</code>. * * @param name Name of the resource to return */ protected InputStream findLoadedResource(String name) { ResourceEntry entry = resourceEntries.get(name); if (entry != null) { if (entry.binaryContent != null) return new ByteArrayInputStream(entry.binaryContent); else { try { return entry.source.openStream(); } catch (IOException ioe) { // Ignore } } } return null; } /** * Finds the class with the given name if it has previously been * loaded and cached by this class loader, and return the Class object. * If this class has not been cached, return <code>null</code>. * * @param name Name of the resource to return */ protected Class<?> findLoadedClass0(String name) { ResourceEntry entry = resourceEntries.get(name); if (entry != null) { return entry.loadedClass; } return (null); // FIXME - findLoadedResource() } /** * Refresh the system policy file, to pick up eventual changes. */ protected void refreshPolicy() { try { // The policy file may have been modified to adjust // permissions, so we're reloading it when loading or // reloading a Context Policy policy = Policy.getPolicy(); policy.refresh(); } catch (AccessControlException e) { // Some policy files may restrict this, even for the core, // so this exception is ignored } } /** * Filter classes. * * @param name class name * @return true if the class should be filtered */ protected boolean filter(String name) { if (name == null) return false; // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); else return false; for (int i = 0; i < packageTriggers.length; i++) { if (packageName.startsWith(packageTriggers[i])) return true; } return false; } /** * Validate a classname. As per SRV.9.7.2, we must restrict loading of * classes from J2SE (java.*) and most classes of the servlet API * (javax.servlet.*). That should enhance robustness and prevent a number * of user error (where an older version of servlet.jar would be present * in /WEB-INF/lib). * * @param name class name * @return true if the name is valid */ protected boolean validate(String name) { // Need to be careful with order here if (name == null) { // Can't load a class without a name return false; } if (name.startsWith("java.")) { // Must never load java.* classes return false; } if (name.startsWith("javax.servlet.jsp.jstl")) { // OK for web apps to package JSTL return true; } if (name.startsWith("javax.servlet.")) { // Web apps should never package any other Servlet or JSP classes return false; } if (name.startsWith("javax.el")) { // Must never load javax.el.* classes return false; } // Assume everything else is OK return true; } /** * Check the specified JAR file, and return <code>true</code> if it does * not contain any of the trigger classes. * * @param file The JAR file to be checked * * @exception IOException if an input/output error occurs */ protected boolean validateJarFile(File file) throws IOException { if (triggers == null) return (true); JarFile jarFile = null; try { jarFile = new JarFile(file); for (int i = 0; i < triggers.length; i++) { Class<?> clazz = null; try { if (parent != null) { clazz = parent.loadClass(triggers[i]); } else { clazz = Class.forName(triggers[i]); } } catch (Exception e) { clazz = null; } if (clazz == null) continue; String name = triggers[i].replace('.', '/') + CLASS_FILE_SUFFIX; if (log.isDebugEnabled()) log.debug(" Checking for " + name); JarEntry jarEntry = jarFile.getJarEntry(name); if (jarEntry != null) { log.info("validateJarFile(" + file + ") - jar not loaded. See Servlet Spec 3.0, " + "section 10.7.2. Offending class: " + name); return false; } } return true; } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException ioe) { // Ignore } } } } /** * Get URL. * @deprecated Use {@link #getURI(File)} instead */ @Deprecated protected URL getURL(File file, boolean encoded) throws MalformedURLException { File realFile = file; try { realFile = realFile.getCanonicalFile(); } catch (IOException e) { // Ignore } if(encoded) { return getURI(realFile); } return realFile.toURI().toURL(); } /** * Get the URI for the given file. */ protected URL getURI(File file) throws MalformedURLException { File realFile = file; try { realFile = realFile.getCanonicalFile(); } catch (IOException e) { // Ignore } return realFile.toURI().toURL(); } /** * Delete the specified directory, including all of its contents and * subdirectories recursively. * * @param dir File object representing the directory to be deleted */ protected static void deleteDir(File dir) { String files[] = dir.list(); if (files == null) { files = new String[0]; } for (int i = 0; i < files.length; i++) { File file = new File(dir, files[i]); if (file.isDirectory()) { deleteDir(file); } else { file.delete(); } } dir.delete(); } }
package com.marc.world; import java.awt.image.BufferedImage; public class WallTile extends Tile { public WallTile(int tileX, int tileY, BufferedImage sprite) { super(tileX, tileY, sprite); } }
package GerenciadoresLayout; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.*; public class TesteJFrame4 extends JFrame implements ActionListener, ItemListener { JTextField cpf, cpfDigito, rg, rgDigito, nome, nascimento, profissao, situacao; JComboBox<String> sexo, falecido; public TesteJFrame4 (String title) { //Título da janela setTitle(title); //Tamanho da janela setSize(1000, 400); // Anula o layout padrão setLayout(null); // Cor de fundo da janela no padrão RGB (Red Green Blue) getContentPane().setBackground(new Color(173,216,230)); //Provoca o término da execução (encerra o programa); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); add(criarJLabel("CPF:", 10, 10, 50, 25)); cpf = criarJTextField(110, 10, 120, 25); add(cpf); add(criarJLabel("-", 240, 10, 10, 25)); cpfDigito = criarJTextField(260, 10, 30, 25); add(cpfDigito); add(criarJLabel("RG:", 310, 10, 30, 25)); rg = criarJTextField(350, 10, 120, 25); add(rg); add(criarJLabel("-", 480, 10, 10, 25)); rgDigito = (criarJTextField(500, 10, 30, 25)); add(rgDigito); add(criarJLabel("Nome:", 10, 60, 100, 25)); nome = criarJTextField(110, 60, 600, 25); add(nome); add(criarJLabel("Sexo:", 10, 110, 100, 25)); sexo = criarJComboBox(110, 110, 160, 25); sexo.addItem("Masculino"); sexo.addItem("Feminino"); sexo.setSelectedIndex(-1); sexo.addItemListener(this); add(sexo); add(criarJLabel("Nascimento:", 290, 110, 80, 25)); nascimento = criarJTextField(380, 110, 200, 25); add(nascimento); add(criarJLabel("Falecido:", 600, 110, 100, 25)); falecido = criarJComboBox(710, 110, 100, 25); add(falecido); falecido.addItem("Sim"); falecido.addItem("Não"); falecido.setSelectedIndex(-1); falecido.addItemListener(this); add(criarJLabel("Profissão:", 10, 160, 100, 25)); profissao = criarJTextField(110, 160, 300, 25); add(profissao); add(criarJLabel("Situação:", 430, 160, 70, 25)); situacao = criarJTextField(500, 160, 470, 25); add(situacao); } public static void main(String[] args) { String title; title = "Atualiza Dados Cadastrais"; TesteJFrame4 janela = new TesteJFrame4(title); janela.setVisible(true); } public JLabel criarJLabel(String label, int left, int top, int w, int h) { JLabel jl = new JLabel(); jl.setText(label); jl.setLocation(left, top); jl.setSize(w, h); //Torna opaco o fundo do rótulo jl.setOpaque(false); //jl.setBackground(new Color(255, 255, 255)); jl.setForeground(new Color(0, 0, 0)); jl.setFont(new Font("Courier new", Font.BOLD, 12)); jl.setToolTipText(label); jl.setHorizontalAlignment(SwingConstants.LEFT); jl.setVerticalAlignment(SwingConstants.CENTER); return jl; } public JTextField criarJTextField(int left, int top, int w, int h) { JTextField jt = new JTextField(); jt.setHorizontalAlignment(JTextField.LEFT); jt.setBounds(left, top, w, h); return jt; } public JComboBox<String> criarJComboBox(int left, int top, int w, int h) { JComboBox<String> jt = new JComboBox<>(); jt.setBounds(left, top, w, h); return jt; } public void actionPerformed(ActionEvent e) { } public void itemStateChanged(ItemEvent e) { if (e.getSource() == sexo) { System.out.println("Selecionado: "+ sexo.getSelectedItem()); } else if (e.getSource() == falecido) { System.out.println("Selecionado: "+ falecido.getSelectedItem()); } } }
// Copyright 2018 The Bazel Authors. 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.devtools.build.lib.starlarkbuildapi.apple; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.collect.nestedset.Depset; import com.google.devtools.build.lib.starlarkbuildapi.FileApi; import com.google.devtools.build.lib.starlarkbuildapi.SplitTransitionProviderApi; import com.google.devtools.build.lib.starlarkbuildapi.StarlarkRuleContextApi; import com.google.devtools.build.lib.starlarkbuildapi.apple.AppleStaticLibraryInfoApi.AppleStaticLibraryInfoProvider; import com.google.devtools.build.lib.starlarkbuildapi.core.ProviderApi; import com.google.devtools.build.lib.starlarkbuildapi.core.StructApi; import com.google.devtools.build.lib.starlarkbuildapi.platform.ConstraintValueInfoApi; import net.starlark.java.annot.Param; import net.starlark.java.annot.ParamType; import net.starlark.java.annot.StarlarkBuiltin; import net.starlark.java.annot.StarlarkMethod; import net.starlark.java.eval.Dict; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.NoneType; import net.starlark.java.eval.Sequence; import net.starlark.java.eval.StarlarkInt; import net.starlark.java.eval.StarlarkThread; import net.starlark.java.eval.StarlarkValue; /** Interface for a module with useful functions for creating apple-related rule implementations. */ @StarlarkBuiltin( name = "apple_common", doc = "Functions for Starlark to access internals of the apple rule implementations.") public interface AppleCommonApi< FileApiT extends FileApi, ConstraintValueT extends ConstraintValueInfoApi, StarlarkRuleContextT extends StarlarkRuleContextApi<ConstraintValueT>, ObjcProviderApiT extends ObjcProviderApi<?>, XcodeConfigInfoApiT extends XcodeConfigInfoApi<?, ?>, ApplePlatformApiT extends ApplePlatformApi> extends StarlarkValue { @StarlarkMethod( name = "apple_toolchain", doc = "Utilities for resolving items from the apple toolchain.") AppleToolchainApi<?> getAppleToolchain(); @StarlarkMethod( name = "platform_type", doc = "An enum-like struct that contains the following fields corresponding to Apple platform " + "types:<br><ul><li><code>ios</code></li><li><code>macos</code></li>" + "<li><code>tvos</code></li><li><code>watchos</code></li></ul><p>These values can" + " be passed to methods that expect a platform type, like the 'apple' configuration" + " fragment's <a href='apple.html#multi_arch_platform'>multi_arch_platform</a>" + " method.<p>Example:<p><pre class='language-python'>\n" + "ctx.fragments.apple.multi_arch_platform(apple_common.platform_type.ios)\n" + "</pre>", structField = true) StructApi getPlatformTypeStruct(); @StarlarkMethod( name = "platform", doc = "An enum-like struct that contains the following fields corresponding to Apple " + "platforms:<br><ul>" + "<li><code>ios_device</code></li>" + "<li><code>ios_simulator</code></li>" + "<li><code>macos</code></li>" + "<li><code>tvos_device</code></li>" + "<li><code>tvos_simulator</code></li>" + "<li><code>watchos_device</code></li>" + "<li><code>watchos_device</code></li>" + "</ul><p>" + "These values can be passed to methods that expect a platform, like " + "<a href='XcodeVersionConfig.html#sdk_version_for_platform'>" + "XcodeVersionConfig.sdk_version_for_platform</a>.", structField = true) StructApi getPlatformStruct(); @StarlarkMethod( name = "XcodeProperties", doc = "The constructor/key for the <code>XcodeVersionProperties</code> provider.<p>" + "If a target propagates the <code>XcodeVersionProperties</code> provider," + " use this as the key with which to retrieve it. Example:<br>" + "<pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.XcodeVersionProperties]\n" + "</pre>", structField = true) ProviderApi getXcodeVersionPropertiesConstructor(); @StarlarkMethod( name = "XcodeVersionConfig", doc = "The constructor/key for the <code>XcodeVersionConfig</code> provider.", structField = true) ProviderApi getXcodeVersionConfigConstructor(); @StarlarkMethod( // TODO(b/63899207): This currently does not match ObjcProvider.STARLARK_NAME as it requires // a migration of existing Starlark rules. name = "Objc", doc = "The constructor/key for the <code>Objc</code> provider.<p>" + "If a target propagates the <code>Objc</code> provider, use this as the " + "key with which to retrieve it. Example:<br>" + "<pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.Objc]\n" + "</pre>", structField = true) ProviderApi getObjcProviderConstructor(); @StarlarkMethod( name = "AppleDynamicFramework", doc = "The constructor/key for the <code>AppleDynamicFramework</code> provider.<p>" + "If a target propagates the <code>AppleDynamicFramework</code> provider, use this " + "as the key with which to retrieve it. Example:<br>" + "<pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.AppleDynamicFramework]\n" + "</pre>", structField = true) ProviderApi getAppleDynamicFrameworkConstructor(); @StarlarkMethod( name = "AppleDylibBinary", doc = "The constructor/key for the <code>AppleDylibBinary</code> provider.<p>If a target" + " propagates the <code>AppleDylibBinary</code> provider, use this as the key with" + " which to retrieve it. Example:<br><pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.AppleDylibBinary]\n" + "</pre>", structField = true) ProviderApi getAppleDylibBinaryConstructor(); @StarlarkMethod( name = "AppleExecutableBinary", doc = "The constructor/key for the <code>AppleExecutableBinary</code> provider.<p>" + "If a target propagates the <code>AppleExecutableBinary</code> provider," + " use this as the key with which to retrieve it. Example:<br>" + "<pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.AppleExecutableBinary]\n" + "</pre>", structField = true) ProviderApi getAppleExecutableBinaryConstructor(); @StarlarkMethod( name = "AppleStaticLibrary", doc = "The constructor/key for the <code>AppleStaticLibrary</code> provider.<p>" + "If a target propagates the <code>AppleStaticLibrary</code> provider, use " + "this as the key with which to retrieve it. Example:<br>" + "<pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.AppleStaticLibrary]\n" + "</pre>", structField = true) AppleStaticLibraryInfoProvider<?, ?> getAppleStaticLibraryProvider(); @StarlarkMethod( name = "AppleDebugOutputs", doc = "The constructor/key for the <code>AppleDebugOutputs</code> provider.<p>If a target" + " propagates the <code>AppleDebugOutputs</code> provider, use this as the key with" + " which to retrieve it. Example:<br><pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.AppleDebugOutputs]\n" + "</pre>", structField = true) ProviderApi getAppleDebugOutputsConstructor(); @StarlarkMethod( name = "AppleLoadableBundleBinary", doc = "The constructor/key for the <code>AppleLoadableBundleBinary</code> provider.<p>" + "If a target propagates the <code>AppleLoadableBundleBinary</code> provider, " + "use this as the key with which to retrieve it. Example:<br>" + "<pre class='language-python'>\n" + "dep = ctx.attr.deps[0]\n" + "p = dep[apple_common.AppleLoadableBundleBinary]\n" + "</pre>", structField = true) ProviderApi getAppleLoadableBundleBinaryConstructor(); @StarlarkMethod( name = "apple_host_system_env", doc = "Returns a <a href='dict.html'>dict</a> of environment variables that should be set " + "for actions that need to run build tools on an Apple host system, such as the " + " version of Xcode that should be used. The keys are variable names and the values " + " are their corresponding values.", parameters = { @Param( name = "xcode_config", positional = true, named = false, doc = "A provider containing information about the xcode configuration."), }) ImmutableMap<String, String> getAppleHostSystemEnv(XcodeConfigInfoApiT xcodeConfig); @StarlarkMethod( name = "target_apple_env", doc = "Returns a <code>dict</code> of environment variables that should be set for actions " + "that build targets of the given Apple platform type. For example, this dictionary " + "contains variables that denote the platform name and SDK version with which to " + "build. The keys are variable names and the values are their corresponding values.", parameters = { @Param( name = "xcode_config", positional = true, named = false, doc = "A provider containing information about the xcode configuration."), @Param( name = "platform", positional = true, named = false, doc = "The apple platform."), }) ImmutableMap<String, String> getTargetAppleEnvironment( XcodeConfigInfoApiT xcodeConfig, ApplePlatformApiT platform); @StarlarkMethod( name = "multi_arch_split", doc = "A configuration transition for rule attributes to build dependencies in one or more" + " Apple platforms. <p>Use of this transition requires that the 'platform_type' and" + " 'minimum_os_version' string attributes are defined and mandatory on the" + " rule.</p><p>The value of the platform_type attribute will dictate the target" + " architectures for which dependencies along this configuration transition will" + " be built.</p><p>Options are:</p><ul><li><code>ios</code>: architectures gathered" + " from <code>--ios_multi_cpus</code>.</li><li><code>macos</code>: architectures" + " gathered from <code>--macos_cpus</code>.</li><li><code>tvos</code>:" + " architectures gathered from" + " <code>--tvos_cpus</code>.</li><li><code>watchos</code>: architectures gathered" + " from <code>--watchos_cpus</code>.</li></ul><p>minimum_os_version should be a" + " dotted version string such as '7.3', and is used to set the minimum operating" + " system on the configuration similarly based on platform type. For example," + " specifying platform_type 'ios' and minimum_os_version '8.0' will ensure that" + " dependencies are built with minimum iOS version '8.0'.", structField = true) SplitTransitionProviderApi getMultiArchSplitProvider(); @StarlarkMethod( name = "new_objc_provider", doc = "Creates a new ObjcProvider instance.", parameters = {}, extraKeywords = @Param(name = "kwargs", defaultValue = "{}", doc = "Dictionary of arguments."), useStarlarkThread = true) // This method is registered statically for Starlark, and never called directly. ObjcProviderApi<?> newObjcProvider(Dict<String, Object> kwargs, StarlarkThread thread) throws EvalException; @StarlarkMethod( name = "new_dynamic_framework_provider", doc = "Creates a new AppleDynamicFramework provider instance.", parameters = { @Param( name = "binary", allowedTypes = { @ParamType(type = FileApi.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "The dylib binary artifact of the dynamic framework."), @Param( name = "objc", named = true, positional = false, doc = "An ObjcProvider which contains information about the transitive " + "dependencies linked into the binary."), @Param( name = "framework_dirs", allowedTypes = { @ParamType(type = Depset.class, generic1 = String.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "The framework path names used as link inputs in order to link against the dynamic " + "framework."), @Param( name = "framework_files", allowedTypes = { @ParamType(type = Depset.class, generic1 = FileApi.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "The full set of artifacts that should be included as inputs to link against the " + "dynamic framework") }) AppleDynamicFrameworkInfoApi<?> newDynamicFrameworkProvider( Object dylibBinary, ObjcProviderApiT depsObjcProvider, Object dynamicFrameworkDirs, Object dynamicFrameworkFiles) throws EvalException; @StarlarkMethod( name = "new_executable_binary_provider", doc = "Creates a new AppleExecutableBinaryInfo provider instance.", parameters = { @Param( name = "binary", allowedTypes = { @ParamType(type = FileApi.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "The binary artifact of the executable."), @Param( name = "objc", named = true, positional = false, doc = "An ObjcProvider which contains information about the transitive " + "dependencies linked into the binary.") }) AppleExecutableBinaryApi newExecutableBinaryProvider( Object executableBinary, ObjcProviderApiT depsObjcProvider) throws EvalException; @StarlarkMethod( name = "link_multi_arch_binary", doc = "Links a (potentially multi-architecture) binary targeting Apple platforms. This " + "method comprises a bulk of the logic of the <code>apple_binary</code> rule, and " + "is exposed as an API to iterate on migration of <code>apple_binary</code> to " + "Starlark.\n" + "<p>This API is <b>highly experimental</b> and subject to change at any time. Do " + "not depend on the stability of this function at this time.", parameters = { @Param(name = "ctx", named = true, positional = false, doc = "The Starlark rule context."), @Param( name = "avoid_deps", allowedTypes = { @ParamType(type = Sequence.class, generic1 = TransitiveInfoCollection.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "A list of <code>Target</code>s that are in the dependency graph of the binary but" + " whose libraries should not be linked into the binary. This is the case for" + " dependencies that will be found at runtime in another image, such as the" + " bundle loader or any dynamic libraries/frameworks that will be loaded by" + " this binary."), @Param( name = "extra_linkopts", allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)}, named = true, positional = false, defaultValue = "[]", doc = "Extra linkopts to be passed to the linker action."), @Param( name = "extra_link_inputs", allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, named = true, positional = false, defaultValue = "[]", doc = "Extra files to pass to the linker action."), @Param( name = "stamp", named = true, positional = false, defaultValue = "-1", doc = "Whether to include build information in the linked binary. If 1, build " + "information is always included. If 0, build information is always excluded. " + "If -1 (the default), then the behavior is determined by the --[no]stamp " + "flag. This should be set to 0 when generating the executable output for " + "test rules."), @Param( name = "should_lipo", named = true, positional = false, defaultValue = "True", doc = "If True, invoke lipo after linking to create a universal binary. This parameter " + "is temporary and defaults to True for legacy purposes. After rules_apple " + "has been updated to call this with False, the default will be changed to " + "False and the support for invoking lipo inside " + "<code>link_multi_arch_binary</code> will be removed, along with this " + "parameter.") }, useStarlarkThread = true) // TODO(b/70937317): Iterate on, improve, and solidify this API. StructApi linkMultiArchBinary( StarlarkRuleContextT starlarkRuleContext, Object avoidDeps, // Sequence<TransitiveInfoCollection> expected. Sequence<?> extraLinkopts, // <String> expected. Sequence<?> extraLinkInputs, // <? extends FileApi> expected. StarlarkInt stamp, Boolean shouldLipo, StarlarkThread thread) throws EvalException, InterruptedException; @StarlarkMethod( name = "dotted_version", doc = "Creates a new <a href=\"DottedVersion.html\">DottedVersion</a> instance.", parameters = { @Param(name = "version", doc = "The string representation of the DottedVersion.") }) DottedVersionApi<?> dottedVersion(String version) throws EvalException; }
package com.romajs.jaxrs; import com.romajs.jaxrs.feature.JerseyJacksonFeature; import org.glassfish.jersey.server.ResourceConfig; public class JerseyResourceConfig extends ResourceConfig { { register(JerseyJacksonFeature.class); } }
/* * GodGivenCVar.java * Copyright 2008, 2009, 2010, 2011, 2012, 2013 Fiji Systems Inc. * This file is part of the FIJI VM Software licensed under the FIJI PUBLIC * LICENSE Version 3 or any later version. A copy of the FIJI PUBLIC LICENSE is * available at fivm/LEGAL and can also be found at * http://www.fiji-systems.com/FPL3.txt * * By installing, reproducing, distributing, and/or using the FIJI VM Software * you agree to the terms of the FIJI PUBLIC LICENSE. You may exercise the * rights granted under the FIJI PUBLIC LICENSE subject to the conditions and * restrictions stated therein. Among other conditions and restrictions, the * FIJI PUBLIC LICENSE states that: * * a. You may only make non-commercial use of the FIJI VM Software. * * b. Any adaptation you make must be licensed under the same terms * of the FIJI PUBLIC LICENSE. * * c. You must include a copy of the FIJI PUBLIC LICENSE in every copy of any * file, adaptation or output code that you distribute and cause the output code * to provide a notice of the FIJI PUBLIC LICENSE. * * d. You must not impose any additional conditions. * * e. You must not assert or imply any connection, sponsorship or endorsement by * the author of the FIJI VM Software * * f. You must take no derogatory action in relation to the FIJI VM Software * which would be prejudicial to the FIJI VM Software author's honor or * reputation. * * * The FIJI VM Software is provided as-is. FIJI SYSTEMS INC does not make any * representation and provides no warranty of any kind concerning the software. * * The FIJI PUBLIC LICENSE and any rights granted therein terminate * automatically upon any breach by you of the terms of the FIJI PUBLIC LICENSE. */ package com.fiji.fivm.c1; import java.io.PrintWriter; public class GodGivenCVar extends CField { private GodGivenCVar(boolean typeUnknown, Basetype type,String name) { super(type,name); } public static GodGivenCVar make(Basetype type, String name) { return CTypesystemReferences.addGGCV(new GodGivenCVar(false, type, name)); } public static GodGivenCVar make(String name) { return CTypesystemReferences.addGGCV(new GodGivenCVar(true, Basetype.VOID, name)); } public void generateDeclaration(PrintWriter w) { // nothing to do } public String toString() { return "GodGivenCVar["+type+" "+name+"]"; } public RemoteFunction makeGetAddress() { return new RemoteFunction( Global.name+"_getAddress_"+name, new NativeSignature(Basetype.POINTER, Basetype.EMPTY, SideEffectMode.PURE, SafepointMode.CANNOT_SAFEPOINT, PollcheckMode.EXPLICIT_POLLCHECKS_ONLY)); } public RemoteFunction makeWrite() { return new RemoteFunction( Global.name+"_write_"+name, new NativeSignature(Basetype.VOID, new Basetype[]{ type }, SideEffectMode.CLOBBERS_WORLD, SafepointMode.CANNOT_SAFEPOINT, PollcheckMode.EXPLICIT_POLLCHECKS_ONLY)); } public RemoteFunction makeRead() { return new RemoteFunction( Global.name+"_read_"+name, new NativeSignature(type, Basetype.EMPTY, SideEffectMode.PURE, SafepointMode.CANNOT_SAFEPOINT, PollcheckMode.EXPLICIT_POLLCHECKS_ONLY)); } public LocalFunction makeGetAddressLocal() { RemoteFunction rf=makeGetAddress(); return new LocalFunction(rf.getName(),rf.getSignature()){ public void generateCode(PrintWriter w) { w.println(" return (uintptr_t)&"+GodGivenCVar.this.name+";"); } }; } public LocalFunction makeWriteLocal() { RemoteFunction rf=makeWrite(); return new LocalFunction(rf.getName(),rf.getSignature()){ public void generateCode(PrintWriter w) { w.println(" "+GodGivenCVar.this.name+" = arg0;"); } }; } public LocalFunction makeReadLocal() { RemoteFunction rf=makeRead(); return new LocalFunction(rf.getName(),rf.getSignature()){ public void generateCode(PrintWriter w) { w.println(" return "+GodGivenCVar.this.name+";"); } }; } }
package models.StatContainer; import models.Stat.*; import java.util.Map; public class AvatarStats extends StatContainer { // public AvatarStats(Map<String, Double> occupation_modifier, int level) {setStats(3.0, occupation_modifier, level);} // protected void setStats(double base_modifier, Map<String, Double> occupation_modifier, int level) { // this.BASE_MODIFIER = base_modifier; this.OCCUPATION_MODIFIER = occupation_modifier; // set key stats this.stats.put("LEVEL", new Level(level)); this.stats.put("LIVES", new Lives(3)); this.stats.put("CURRENT_LIVES", new CurrentLives((int)this.stats.get("LIVES").value())); this.stats.put("EXPERIENCE", new Experience(level)); this.stats.put("CURRENT_EXPERIENCE", new CurrentExperience()); // set primary stats this.stats.put("STRENGTH", new Strength(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("STRENGTH"), level)); this.stats.put("AGILITY", new Agility(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("AGILITY"), level)); this.stats.put("INTELLECT", new Intellect(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("INTELLECT"), level)); this.stats.put("HARDINESS", new Hardiness(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("HARDINESS"), level)); this.stats.put("RANGE",new Range(this.BASE_MODIFIER,2,level)); // set secondary stats this.stats.put("LIFE", new Life(this.stats.get("HARDINESS"), this.stats.get("LEVEL"))); this.stats.put("CURRENT_LIFE", new CurrentLife(this.stats.get("LIFE"))); this.stats.put("MANA", new Mana(this.stats.get("INTELLECT"), this.stats.get("LEVEL"))); this.stats.put("CURRENT_MANA", new CurrentMana(this.stats.get("MANA"))); this.stats.put("OFFENSE", new Offense(this.stats.get("STRENGTH"), this.stats.get("LEVEL"))); this.stats.put("DEFENSE", new Defense(this.stats.get("AGILITY"), this.stats.get("LEVEL"))); this.stats.put("ARMOR", new Armor(this.stats.get("HARDINESS"))); // set speed stats this.stats.put("MOVEMENT", new Movement(1.0)); this.stats.put("ATTACK", new Attack(2.0)); this.stats.put("BARGAIN", new Bargain(0.0)); } // public void levelUp() { // temp variables int level = (int)this.stats.get("LEVEL").value() + 1; int lives = (int)this.stats.get("LIVES").value(); // clear current stats this.stats.clear(); // set key stats this.stats.put("LEVEL", new Level(level)); this.stats.put("LIVES", new Lives(lives)); this.stats.put("CURRENT_LIVES", new CurrentLives(lives)); this.stats.put("EXPERIENCE", new Experience(level)); this.stats.put("CURRENT_EXPERIENCE", new CurrentExperience()); // set primary stats this.stats.put("STRENGTH", new Strength(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("STRENGTH"), level)); this.stats.put("AGILITY", new Agility(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("AGILITY"), level)); this.stats.put("INTELLECT", new Intellect(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("INTELLECT"), level)); this.stats.put("HARDINESS", new Hardiness(this.BASE_MODIFIER, this.OCCUPATION_MODIFIER.get("HARDINESS"), level)); // set secondary stats this.stats.put("LIFE", new Life(this.stats.get("HARDINESS"), this.stats.get("LEVEL"))); this.stats.put("CURRENT_LIFE", new CurrentLife(this.stats.get("LIFE"))); this.stats.put("MANA", new Mana(this.stats.get("INTELLECT"), this.stats.get("LEVEL"))); this.stats.put("CURRENT_MANA", new CurrentMana(this.stats.get("MANA"))); this.stats.put("OFFENSE", new Offense(this.stats.get("STRENGTH"), this.stats.get("LEVEL"))); this.stats.put("DEFENSE", new Defense(this.stats.get("AGILITY"), this.stats.get("LEVEL"))); this.stats.put("ARMOR", new Armor(this.stats.get("HARDINESS"))); // set tertiary stats this.stats.put("MOVEMENT", new Movement(1.0)); this.stats.put("ATTACK", new Attack(2.0)); this.stats.put("BARGAIN", new Bargain(0.0)); } }
/* * Copyright 2013 - 2019 The Original Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elasticsoftware.elasticactors; import java.util.Collection; import java.util.Map; import java.util.Set; /** * Encapsulates a {@link ThreadLocal} that holds the {@link ActorContext} for the {@link ElasticActor} that * is currently being executed. * * @author Joost van de Wijgerd */ public class ActorContextHolder { protected static final ThreadLocal<ActorContext> threadContext = new ThreadLocal<>(); protected ActorContextHolder() { } public static boolean hasActorContext() { return threadContext.get() != null; } /** * * @param stateClass the class that implements {@link ActorState} interface * @param <T> generic type info * @return the current {@link ActorState} for the current executing {@link ElasticActor} */ public static <T extends ActorState> T getState(Class<T> stateClass) { ActorContext actorContext = threadContext.get(); return actorContext.getState(stateClass); } /** * * @return the {@link ActorRef} to the current executing {@link ElasticActor} */ public static ActorRef getSelf() { ActorContext actorContext = threadContext.get(); return actorContext != null ? actorContext.getSelf() : null; } /** * * @return the {@link ActorSystem} that the current executing {@link ElasticActor} belongs to */ public static ActorSystem getSystem() { return threadContext.get().getActorSystem(); } public static Collection<PersistentSubscription> getSubscriptions() { return threadContext.get().getSubscriptions(); } public static Map<String, Set<ActorRef>> getSubscribers() { return threadContext.get().getSubscribers(); } }
/* * 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.cassandra.io.sstable; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.*; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.apache.cassandra.OrderedJUnit4ClassRunner; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.Operator; import org.apache.cassandra.db.*; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.compaction.OperationType; import org.apache.cassandra.db.lifecycle.LifecycleTransaction; import org.apache.cassandra.db.partitions.UnfilteredPartitionIterators; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.LocalPartitioner.LocalToken; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.index.Index; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.util.FileDataInput; import org.apache.cassandra.io.util.MmappedSegmentedFile; import org.apache.cassandra.io.util.SegmentedFile; import org.apache.cassandra.schema.CachingParams; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.service.CacheService; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.Pair; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(OrderedJUnit4ClassRunner.class) public class SSTableReaderTest { public static final String KEYSPACE1 = "SSTableReaderTest"; public static final String CF_STANDARD = "Standard1"; public static final String CF_STANDARD2 = "Standard2"; public static final String CF_INDEXED = "Indexed1"; public static final String CF_STANDARDLOWINDEXINTERVAL = "StandardLowIndexInterval"; private IPartitioner partitioner; Token t(int i) { return partitioner.getToken(ByteBufferUtil.bytes(String.valueOf(i))); } @BeforeClass public static void defineSchema() throws Exception { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD2), SchemaLoader.compositeIndexCFMD(KEYSPACE1, CF_INDEXED, true), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARDLOWINDEXINTERVAL) .minIndexInterval(8) .maxIndexInterval(256) .caching(CachingParams.CACHE_NOTHING)); } @Test public void testGetPositionsForRanges() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard2"); partitioner = store.getPartitioner(); // insert data and compact to a single sstable CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 10; j++) { new RowUpdateBuilder(store.metadata, j, String.valueOf(j)) .clustering("0") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store, false); List<Range<Token>> ranges = new ArrayList<Range<Token>>(); // 1 key ranges.add(new Range<>(t(0), t(1))); // 2 keys ranges.add(new Range<>(t(2), t(4))); // wrapping range from key to end ranges.add(new Range<>(t(6), partitioner.getMinimumToken())); // empty range (should be ignored) ranges.add(new Range<>(t(9), t(91))); // confirm that positions increase continuously SSTableReader sstable = store.getLiveSSTables().iterator().next(); long previous = -1; for (Pair<Long,Long> section : sstable.getPositionsForRanges(ranges)) { assert previous <= section.left : previous + " ! < " + section.left; assert section.left < section.right : section.left + " ! < " + section.right; previous = section.right; } } @Test public void testSpannedIndexPositions() throws IOException { MmappedSegmentedFile.MAX_SEGMENT_SIZE = 40; // each index entry is ~11 bytes, so this will generate lots of segments Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard1"); partitioner = store.getPartitioner(); // insert a bunch of data and compact to a single sstable CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 100; j += 2) { new RowUpdateBuilder(store.metadata, j, String.valueOf(j)) .clustering("0") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store, false); // check that all our keys are found correctly SSTableReader sstable = store.getLiveSSTables().iterator().next(); for (int j = 0; j < 100; j += 2) { DecoratedKey dk = Util.dk(String.valueOf(j)); FileDataInput file = sstable.getFileDataInput(sstable.getPosition(dk, SSTableReader.Operator.EQ).position); DecoratedKey keyInDisk = sstable.decorateKey(ByteBufferUtil.readWithShortLength(file)); assert keyInDisk.equals(dk) : String.format("%s != %s in %s", keyInDisk, dk, file.getPath()); } // check no false positives for (int j = 1; j < 110; j += 2) { DecoratedKey dk = Util.dk(String.valueOf(j)); assert sstable.getPosition(dk, SSTableReader.Operator.EQ) == null; } } @Test public void testPersistentStatistics() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard1"); partitioner = store.getPartitioner(); for (int j = 0; j < 100; j += 2) { new RowUpdateBuilder(store.metadata, j, String.valueOf(j)) .clustering("0") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); clearAndLoad(store); assert store.metric.maxPartitionSize.getValue() != 0; } private void clearAndLoad(ColumnFamilyStore cfs) { cfs.clearUnsafe(); cfs.loadNewSSTables(); } @Test public void testReadRateTracking() { // try to make sure CASSANDRA-8239 never happens again Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard1"); partitioner = store.getPartitioner(); for (int j = 0; j < 10; j++) { new RowUpdateBuilder(store.metadata, j, String.valueOf(j)) .clustering("0") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); SSTableReader sstable = store.getLiveSSTables().iterator().next(); assertEquals(0, sstable.getReadMeter().count()); DecoratedKey key = sstable.decorateKey(ByteBufferUtil.bytes("4")); Util.getAll(Util.cmd(store, key).build()); assertEquals(1, sstable.getReadMeter().count()); Util.getAll(Util.cmd(store, key).includeRow("0").build()); assertEquals(2, sstable.getReadMeter().count()); } @Test public void testGetPositionsForRangesWithKeyCache() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard2"); partitioner = store.getPartitioner(); CacheService.instance.keyCache.setCapacity(100); // insert data and compact to a single sstable CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 10; j++) { new RowUpdateBuilder(store.metadata, j, String.valueOf(j)) .clustering("0") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store, false); SSTableReader sstable = store.getLiveSSTables().iterator().next(); long p2 = sstable.getPosition(k(2), SSTableReader.Operator.EQ).position; long p3 = sstable.getPosition(k(3), SSTableReader.Operator.EQ).position; long p6 = sstable.getPosition(k(6), SSTableReader.Operator.EQ).position; long p7 = sstable.getPosition(k(7), SSTableReader.Operator.EQ).position; Pair<Long, Long> p = sstable.getPositionsForRanges(makeRanges(t(2), t(6))).get(0); // range are start exclusive so we should start at 3 assert p.left == p3; // to capture 6 we have to stop at the start of 7 assert p.right == p7; } @Test public void testPersistentStatisticsWithSecondaryIndex() { // Create secondary index and flush to disk Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF_INDEXED); partitioner = store.getPartitioner(); new RowUpdateBuilder(store.metadata, System.currentTimeMillis(), "k1") .clustering("0") .add("birthdate", 1L) .build() .applyUnsafe(); store.forceBlockingFlush(); // check if opening and querying works assertIndexQueryWorks(store); } public void testGetPositionsKeyCacheStats() { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard2"); partitioner = store.getPartitioner(); CacheService.instance.keyCache.setCapacity(1000); // insert data and compact to a single sstable CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 10; j++) { new RowUpdateBuilder(store.metadata, j, String.valueOf(j)) .clustering("0") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store, false); SSTableReader sstable = store.getLiveSSTables().iterator().next(); sstable.getPosition(k(2), SSTableReader.Operator.EQ); assertEquals(0, sstable.getKeyCacheHit()); assertEquals(1, sstable.getBloomFilterTruePositiveCount()); sstable.getPosition(k(2), SSTableReader.Operator.EQ); assertEquals(1, sstable.getKeyCacheHit()); assertEquals(2, sstable.getBloomFilterTruePositiveCount()); sstable.getPosition(k(15), SSTableReader.Operator.EQ); assertEquals(1, sstable.getKeyCacheHit()); assertEquals(2, sstable.getBloomFilterTruePositiveCount()); } @Test public void testOpeningSSTable() throws Exception { String ks = KEYSPACE1; String cf = "Standard1"; // clear and create just one sstable for this test Keyspace keyspace = Keyspace.open(ks); ColumnFamilyStore store = keyspace.getColumnFamilyStore(cf); store.clearUnsafe(); store.disableAutoCompaction(); DecoratedKey firstKey = null, lastKey = null; long timestamp = System.currentTimeMillis(); for (int i = 0; i < store.metadata.params.minIndexInterval; i++) { DecoratedKey key = Util.dk(String.valueOf(i)); if (firstKey == null) firstKey = key; if (lastKey == null) lastKey = key; if (store.metadata.getKeyValidator().compare(lastKey.getKey(), key.getKey()) < 0) lastKey = key; new RowUpdateBuilder(store.metadata, timestamp, key.getKey()) .clustering("col") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); SSTableReader sstable = store.getLiveSSTables().iterator().next(); Descriptor desc = sstable.descriptor; // test to see if sstable can be opened as expected SSTableReader target = SSTableReader.open(desc); Assert.assertEquals(target.getIndexSummarySize(), 1); Assert.assertArrayEquals(ByteBufferUtil.getArray(firstKey.getKey()), target.getIndexSummaryKey(0)); assert target.first.equals(firstKey); assert target.last.equals(lastKey); target.selfRef().release(); } @Test public void testLoadingSummaryUsesCorrectPartitioner() throws Exception { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Indexed1"); new RowUpdateBuilder(store.metadata, System.currentTimeMillis(), "k1") .clustering("0") .add("birthdate", 1L) .build() .applyUnsafe(); store.forceBlockingFlush(); for(ColumnFamilyStore indexCfs : store.indexManager.getAllIndexColumnFamilyStores()) { assert indexCfs.isIndex(); SSTableReader sstable = indexCfs.getLiveSSTables().iterator().next(); assert sstable.first.getToken() instanceof LocalToken; try (SegmentedFile.Builder ibuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getIndexAccessMode(), false); SegmentedFile.Builder dbuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getDiskAccessMode(), sstable.compression)) { sstable.saveSummary(ibuilder, dbuilder); } SSTableReader reopened = SSTableReader.open(sstable.descriptor); assert reopened.first.getToken() instanceof LocalToken; reopened.selfRef().release(); } } /** see CASSANDRA-5407 */ @Test public void testGetScannerForNoIntersectingRanges() throws Exception { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard1"); partitioner = store.getPartitioner(); new RowUpdateBuilder(store.metadata, 0, "k1") .clustering("xyz") .add("val", "abc") .build() .applyUnsafe(); store.forceBlockingFlush(); boolean foundScanner = false; for (SSTableReader s : store.getLiveSSTables()) { try (ISSTableScanner scanner = s.getScanner(new Range<Token>(t(0), t(1)), null)) { scanner.next(); // throws exception pre 5407 foundScanner = true; } } assertTrue(foundScanner); } @Test public void testGetPositionsForRangesFromTableOpenedForBulkLoading() throws IOException { Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard2"); partitioner = store.getPartitioner(); // insert data and compact to a single sstable. The // number of keys inserted is greater than index_interval // to ensure multiple segments in the index file CompactionManager.instance.disableAutoCompaction(); for (int j = 0; j < 130; j++) { new RowUpdateBuilder(store.metadata, j, String.valueOf(j)) .clustering("0") .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER) .build() .applyUnsafe(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store, false); // construct a range which is present in the sstable, but whose // keys are not found in the first segment of the index. List<Range<Token>> ranges = new ArrayList<Range<Token>>(); ranges.add(new Range<Token>(t(98), t(99))); SSTableReader sstable = store.getLiveSSTables().iterator().next(); List<Pair<Long,Long>> sections = sstable.getPositionsForRanges(ranges); assert sections.size() == 1 : "Expected to find range in sstable" ; // re-open the same sstable as it would be during bulk loading Set<Component> components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX); if (sstable.components.contains(Component.COMPRESSION_INFO)) components.add(Component.COMPRESSION_INFO); SSTableReader bulkLoaded = SSTableReader.openForBatch(sstable.descriptor, components, store.metadata); sections = bulkLoaded.getPositionsForRanges(ranges); assert sections.size() == 1 : "Expected to find range in sstable opened for bulk loading"; bulkLoaded.selfRef().release(); } @Test public void testIndexSummaryReplacement() throws IOException, ExecutionException, InterruptedException { Keyspace keyspace = Keyspace.open(KEYSPACE1); final ColumnFamilyStore store = keyspace.getColumnFamilyStore("StandardLowIndexInterval"); // index interval of 8, no key caching CompactionManager.instance.disableAutoCompaction(); final int NUM_PARTITIONS = 512; for (int j = 0; j < NUM_PARTITIONS; j++) { new RowUpdateBuilder(store.metadata, j, String.format("%3d", j)) .clustering("0") .add("val", String.format("%3d", j)) .build() .applyUnsafe(); } store.forceBlockingFlush(); CompactionManager.instance.performMaximal(store, false); Collection<SSTableReader> sstables = store.getLiveSSTables(); assert sstables.size() == 1; final SSTableReader sstable = sstables.iterator().next(); ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5); List<Future> futures = new ArrayList<>(NUM_PARTITIONS * 2); for (int i = 0; i < NUM_PARTITIONS; i++) { final ByteBuffer key = ByteBufferUtil.bytes(String.format("%3d", i)); final int index = i; futures.add(executor.submit(new Runnable() { public void run() { Row row = Util.getOnlyRowUnfiltered(Util.cmd(store, key).build()); assertEquals(0, ByteBufferUtil.compare(String.format("%3d", index).getBytes(), row.cells().iterator().next().value())); } })); futures.add(executor.submit(new Runnable() { public void run() { Iterable<DecoratedKey> results = store.keySamples( new Range<>(sstable.getPartitioner().getMinimumToken(), sstable.getPartitioner().getToken(key))); assertTrue(results.iterator().hasNext()); } })); } SSTableReader replacement; try (LifecycleTransaction txn = store.getTracker().tryModify(Arrays.asList(sstable), OperationType.UNKNOWN)) { replacement = sstable.cloneWithNewSummarySamplingLevel(store, 1); txn.update(replacement, true); txn.finish(); } for (Future future : futures) future.get(); assertEquals(sstable.estimatedKeys(), replacement.estimatedKeys(), 1); } private void assertIndexQueryWorks(ColumnFamilyStore indexedCFS) { assert "Indexed1".equals(indexedCFS.name); // make sure all sstables including 2ary indexes load from disk for (ColumnFamilyStore cfs : indexedCFS.concatWithIndexes()) clearAndLoad(cfs); // query using index to see if sstable for secondary index opens ReadCommand rc = Util.cmd(indexedCFS).fromKeyIncl("k1").toKeyIncl("k3") .columns("birthdate") .filterOn("birthdate", Operator.EQ, 1L) .build(); Index.Searcher searcher = indexedCFS.indexManager.getBestIndexFor(rc).searcherFor(rc); assertNotNull(searcher); try (ReadOrderGroup orderGroup = ReadOrderGroup.forCommand(rc)) { assertEquals(1, Util.size(UnfilteredPartitionIterators.filter(searcher.search(orderGroup), rc.nowInSec()))); } } private List<Range<Token>> makeRanges(Token left, Token right) { return Arrays.asList(new Range<>(left, right)); } private DecoratedKey k(int i) { return new BufferDecoratedKey(t(i), ByteBufferUtil.bytes(String.valueOf(i))); } }
/** */ package com.collins.trustedsystems.briefcase.json.json.impl; import com.collins.trustedsystems.briefcase.json.json.JsonAnnexElement; import com.collins.trustedsystems.briefcase.json.json.JsonAnnexMember; import com.collins.trustedsystems.briefcase.json.json.JsonAnnexString; import com.collins.trustedsystems.briefcase.json.json.JsonPackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Annex Member</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link com.collins.trustedsystems.briefcase.json.json.impl.JsonAnnexMemberImpl#getKey <em>Key</em>}</li> * <li>{@link com.collins.trustedsystems.briefcase.json.json.impl.JsonAnnexMemberImpl#getJsonAnnexElement <em>Json Annex Element</em>}</li> * </ul> * * @generated */ public class JsonAnnexMemberImpl extends MinimalEObjectImpl.Container implements JsonAnnexMember { /** * The cached value of the '{@link #getKey() <em>Key</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKey() * @generated * @ordered */ protected JsonAnnexString key; /** * The cached value of the '{@link #getJsonAnnexElement() <em>Json Annex Element</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getJsonAnnexElement() * @generated * @ordered */ protected JsonAnnexElement jsonAnnexElement; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected JsonAnnexMemberImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return JsonPackage.Literals.JSON_ANNEX_MEMBER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public JsonAnnexString getKey() { return key; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetKey(JsonAnnexString newKey, NotificationChain msgs) { JsonAnnexString oldKey = key; key = newKey; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, JsonPackage.JSON_ANNEX_MEMBER__KEY, oldKey, newKey); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setKey(JsonAnnexString newKey) { if (newKey != key) { NotificationChain msgs = null; if (key != null) msgs = ((InternalEObject)key).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - JsonPackage.JSON_ANNEX_MEMBER__KEY, null, msgs); if (newKey != null) msgs = ((InternalEObject)newKey).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - JsonPackage.JSON_ANNEX_MEMBER__KEY, null, msgs); msgs = basicSetKey(newKey, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JsonPackage.JSON_ANNEX_MEMBER__KEY, newKey, newKey)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public JsonAnnexElement getJsonAnnexElement() { return jsonAnnexElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetJsonAnnexElement(JsonAnnexElement newJsonAnnexElement, NotificationChain msgs) { JsonAnnexElement oldJsonAnnexElement = jsonAnnexElement; jsonAnnexElement = newJsonAnnexElement; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT, oldJsonAnnexElement, newJsonAnnexElement); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setJsonAnnexElement(JsonAnnexElement newJsonAnnexElement) { if (newJsonAnnexElement != jsonAnnexElement) { NotificationChain msgs = null; if (jsonAnnexElement != null) msgs = ((InternalEObject)jsonAnnexElement).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT, null, msgs); if (newJsonAnnexElement != null) msgs = ((InternalEObject)newJsonAnnexElement).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT, null, msgs); msgs = basicSetJsonAnnexElement(newJsonAnnexElement, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT, newJsonAnnexElement, newJsonAnnexElement)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case JsonPackage.JSON_ANNEX_MEMBER__KEY: return basicSetKey(null, msgs); case JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT: return basicSetJsonAnnexElement(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case JsonPackage.JSON_ANNEX_MEMBER__KEY: return getKey(); case JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT: return getJsonAnnexElement(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case JsonPackage.JSON_ANNEX_MEMBER__KEY: setKey((JsonAnnexString)newValue); return; case JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT: setJsonAnnexElement((JsonAnnexElement)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case JsonPackage.JSON_ANNEX_MEMBER__KEY: setKey((JsonAnnexString)null); return; case JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT: setJsonAnnexElement((JsonAnnexElement)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case JsonPackage.JSON_ANNEX_MEMBER__KEY: return key != null; case JsonPackage.JSON_ANNEX_MEMBER__JSON_ANNEX_ELEMENT: return jsonAnnexElement != null; } return super.eIsSet(featureID); } } //JsonAnnexMemberImpl
/* * Copyright 2008-2021 Async-IO.org * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.samples.chat; import com.fasterxml.jackson.databind.ObjectMapper; import org.atmosphere.config.managed.Encoder; import javax.enterprise.inject.Default; import java.io.IOException; /** * Encode a {@link Message} into a String */ @Default public class JacksonEncoder implements Encoder<Message, String> { private final ObjectMapper mapper = new ObjectMapper(); public JacksonEncoder(){} @Override public String encode(Message m) { try { return mapper.writeValueAsString(m); } catch (IOException e) { throw new RuntimeException(e); } } }
package thadome23.chatty.api.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; class InputThread extends Thread { private BufferedReader stream; private boolean test=true; private WindowPrinter output; private Socket s; public InputThread(Socket socket, WindowPrinter userOutput) throws IOException { this.stream=new BufferedReader(new InputStreamReader(socket.getInputStream())); this.output=userOutput; this.s = socket; } @Override public void run(){ while(test){ String text = null; try { text = stream.readLine(); } catch (IOException e) { if (e.getMessage().equals("Connection reset")){ close(); output.println("server closed",ContentType.Error); }else {e.printStackTrace();} e.printStackTrace(); } if (text != null) { String textReplaced = text.replaceAll("(?<!/)_", "\n"); String correctText = textReplaced.replaceAll("/_","_"); correctText = correctText.replaceAll("/<","<"); correctText = correctText.replaceAll("/>",">"); String[] arg, i; if(correctText.endsWith(">>") && correctText.startsWith("<<")) { correctText = correctText.replaceAll("<<",""); correctText = correctText.replaceAll(">>",""); arg = correctText.split("\\$"); i = arg[0].split(","); }else { break; } if(i[0].equals("msg")) { output.println(arg[1],ContentType.Chat_message); }else if(i[0].equals("info")){ output.println(arg[1],ContentType.Chat_info); }else if(i[0].equals("roomname")) { output.println(arg[1],ContentType.Room_name); } }else { output.println("Server closed ",ContentType.Error); close(); } } } void close(){ test=false; try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } }
/* * Copyright (c) 2016-2017, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * * 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 net.runelite.mixins; import net.runelite.api.NPCComposition; import net.runelite.api.events.NpcDespawned; import net.runelite.api.mixins.Copy; import net.runelite.api.mixins.FieldHook; import net.runelite.api.mixins.Inject; import net.runelite.api.mixins.Mixin; import net.runelite.api.mixins.Replace; import net.runelite.api.mixins.Shadow; import static net.runelite.client.callback.Hooks.eventBus; import net.runelite.rs.api.RSClient; import net.runelite.rs.api.RSModel; import net.runelite.rs.api.RSNPC; import net.runelite.rs.api.RSNPCComposition; @Mixin(RSNPC.class) public abstract class RSNPCMixin implements RSNPC { @Shadow("clientInstance") private static RSClient client; @Inject private int npcIndex; @Inject @Override public int getId() { RSNPCComposition composition = getComposition(); if (composition != null && composition.getConfigs() != null) { composition = composition.transform(); } return composition == null ? -1 : composition.getId(); } @Inject @Override public String getName() { RSNPCComposition composition = getComposition(); if (composition != null && composition.getConfigs() != null) { composition = composition.transform(); } return composition == null ? null : composition.getName().replace('\u00A0', ' '); } @Inject @Override public int getCombatLevel() { RSNPCComposition composition = getComposition(); if (composition != null && composition.getConfigs() != null) { composition = composition.transform(); } return composition == null ? -1 : composition.getCombatLevel(); } @Inject @Override public int getIndex() { return npcIndex; } @Inject @Override public void setIndex(int id) { npcIndex = id; } @FieldHook(value = "composition", before = true) @Inject public void onCompositionChanged(RSNPCComposition composition) { if (composition == null) { eventBus.post(new NpcDespawned(this)); } } @Copy("getModel") public abstract RSModel rs$getModel(); @Replace("getModel") public RSModel rl$getModel() { if (!client.isInterpolateNpcAnimations()) { return rs$getModel(); } int actionFrame = getActionFrame(); int poseFrame = getPoseFrame(); int spotAnimFrame = getSpotAnimFrame(); try { // combine the frames with the frame cycle so we can access this information in the sequence methods // without having to change method calls setActionFrame(Integer.MIN_VALUE | getActionFrameCycle() << 16 | actionFrame); setPoseFrame(Integer.MIN_VALUE | getPoseFrameCycle() << 16 | poseFrame); setSpotAnimFrame(Integer.MIN_VALUE | getSpotAnimFrameCycle() << 16 | spotAnimFrame); return rs$getModel(); } finally { // reset frames setActionFrame(actionFrame); setPoseFrame(poseFrame); setSpotAnimFrame(spotAnimFrame); } } @Inject @Override public NPCComposition getTransformedComposition() { RSNPCComposition composition = getComposition(); if (composition != null && composition.getConfigs() != null) { composition = composition.transform(); } return composition; } }
package cn.dhbin.minion.upms.service.impl; import cn.dhbin.minion.upms.model.dto.SysMenuDto; import cn.dhbin.minion.upms.service.SysMenuService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; /** * @author donghaibin * @date 2020/3/18 */ @SpringBootTest class SysMenuServiceImplTest { @Autowired private SysMenuService sysMenuService; @Test void getMenuByUserId() { List<SysMenuDto> sysMenuDtos = sysMenuService.getMenuTreeByUserId(1240192515995959297L, -1); System.out.println(sysMenuDtos); } }
/* * Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.internal.util; import com.hazelcast.internal.serialization.SerializationService; import com.hazelcast.internal.serialization.Data; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import static com.hazelcast.internal.util.Preconditions.checkNotNull; /** * Various collection utility methods. */ public final class CollectionUtil { private CollectionUtil() { } /** * Returns {@code true} if the given collection is {@code null} or empty, otherwise returns {@code false}. * * @param collection the given collection * @return {@code true} if collection is empty */ public static boolean isEmpty(Collection collection) { return collection == null || collection.isEmpty(); } /** * Returns {@code true} if the given collection is not {@code null} and not empty, otherwise returns {@code false}. * * @param collection the given collection * @return {@code true} if collection is not empty */ public static boolean isNotEmpty(Collection collection) { return !isEmpty(collection); } /** * Adds a value to a list of values in the map. * <p> * Creates a new list if no list is found for the key. * * @param map the given map of lists * @param key the key of the target list * @param value the value to add to the target list * @return the updated list of values */ public static <K, V> List<V> addToValueList(Map<K, List<V>> map, K key, V value) { List<V> valueList = map.get(key); if (valueList == null) { valueList = new ArrayList<V>(); map.put(key, valueList); } valueList.add(value); return valueList; } /** * Returns the n-th item or {@code null} if collection is smaller. * * @param collection the given collection * @param position position of the wanted item * @return the item on position or {@code null} if the given collection is too small * @throws NullPointerException if collection is {@code null} */ public static <T> T getItemAtPositionOrNull(Collection<T> collection, int position) { if (position >= collection.size()) { return null; } if (collection instanceof List) { return ((List<T>) collection).get(position); } Iterator<T> iterator = collection.iterator(); T item = null; for (int i = 0; i < position + 1; i++) { item = iterator.next(); } return item; } /** * Converts a collection of any type to a collection of {@link Data}. * * @param collection the given collection * @param serializationService will be used for converting object to {@link Data} * @return collection of data * @throws NullPointerException if collection is {@code null} or contains a {@code null} item */ public static <C> Collection<Data> objectToDataCollection(Collection<C> collection, SerializationService serializationService) { List<Data> dataCollection = new ArrayList<Data>(collection.size()); objectToDataCollection(collection, dataCollection, serializationService, null); return dataCollection; } /** * Converts a collection of any type to a collection of {@link Data}. * * @param objectCollection object items * @param dataCollection data items * @param serializationService will be used for converting object to {@link Data} * @param errorMessage the errorMessage when an item is null * @throws NullPointerException if collection is {@code null} or contains a {@code null} item */ public static <C> void objectToDataCollection(Collection<C> objectCollection, Collection<Data> dataCollection, SerializationService serializationService, String errorMessage) { for (C item : objectCollection) { checkNotNull(item, errorMessage); dataCollection.add(serializationService.toData(item)); } } /** * Converts a {@link Collection} of {@link Integer} to a primitive {@code int[]} array. * * @param collection the given collection * @return a primitive int[] array * @throws NullPointerException if collection is {@code null} */ public static int[] toIntArray(Collection<Integer> collection) { int[] collectionArray = new int[collection.size()]; int index = 0; for (Integer item : collection) { collectionArray[index++] = item; } return collectionArray; } /** * Converts a {@link Collection} of {@link Long} to a primitive {@code long[]} array. * * @param collection the given collection * @return a primitive long[] array * @throws NullPointerException if collection is {@code null} */ public static long[] toLongArray(Collection<Long> collection) { long[] collectionArray = new long[collection.size()]; int index = 0; for (Long item : collection) { collectionArray[index++] = item; } return collectionArray; } /** * Adapts an int array to an Integer {@link List}. * * @param array the array * @return the list * @throws NullPointerException if array is null. */ public static List<Integer> asIntegerList(int[] array) { checkNotNull(array, "null array"); return new AbstractList<Integer>() { @Override public Integer get(int index) { return array[index]; } @Override public int size() { return array.length; } }; } /** Returns an empty Collection if argument is null. **/ public static <T> Collection<T> nullToEmpty(Collection<T> collection) { return collection == null ? Collections.<T>emptyList() : collection; } }
/******************************************************************************* * Copyright (c) 2005, 2011 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.scripting; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.ltk.core.refactoring.Refactoring; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor; import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments; import org.eclipse.jdt.internal.corext.refactoring.code.InlineConstantRefactoring; /** * Refactoring contribution for the inline constant refactoring. * * @since 3.2 */ public final class InlineConstantRefactoringContribution extends JavaUIRefactoringContribution { @Override public final Refactoring createRefactoring(JavaRefactoringDescriptor descriptor, RefactoringStatus status) throws CoreException { JavaRefactoringArguments arguments = new JavaRefactoringArguments(descriptor.getProject(), retrieveArgumentMap(descriptor)); return new InlineConstantRefactoring(arguments, status); } @Override public RefactoringDescriptor createDescriptor() { return RefactoringSignatureDescriptorFactory.createInlineConstantDescriptor(); } @Override public RefactoringDescriptor createDescriptor(String id, String project, String description, String comment, Map<String, String> arguments, int flags) { return RefactoringSignatureDescriptorFactory.createInlineConstantDescriptor(project, description, comment, arguments, flags); } }
package ru.heroicrealm.scormbuilder.entities; import javax.persistence.*; /** * Created by kuran on 19.01.2019. */ @Entity @Table(name = "pres_page") public class PresentationPage implements Comparable<PresentationPage>{ @Id @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "pages_seq_gen" ) @SequenceGenerator(name = "pages_seq_gen",sequenceName = "page_seq",allocationSize = 50) @Column(name = "pageid") long pageId; @ManyToOne Presentation presentation; @Column(name = "pg_number") int pageNo; @Column(name="title") String title; @Lob @Column(name = "pg_content") String content; @Transient boolean selected; @Override public int compareTo(PresentationPage o) { return this.pageNo - o.pageNo; } public long getPageId() { return pageId; } public void setPageId(long pageId) { this.pageId = pageId; } public Presentation getPresentation() { return presentation; } public void setPresentation(Presentation presentation) { this.presentation = presentation; } public int getPageNo() { return pageNo; } public String getPageNos() { return String.valueOf(pageNo); } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public void setPageNos(String pageNo) { this.pageNo = Integer.parseInt(pageNo); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } }
package org.apache.airavata.pga.tests; import org.apache.airavata.pga.tests.utils.UserLogin; import org.apache.airavata.pga.tests.utils.ExpFileReadUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; import java.util.concurrent.TimeUnit; import static org.junit.Assert.fail; /* **********Executing Gaussian Application on Comet********** * Created by Eroma on 9/16/14. * The script generates NwChem application execution on Stampede * experiment-name and experiment-description are read from the exp.properties file * Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file * Updated to work with Latest PGA by Eroma 08/05/2015 */ public class GaussianKarst extends UserLogin { private WebDriver driver; private String baseUrl; private String subUrl; private boolean acceptNextAlert = true; private StringBuffer verificationErrors = new StringBuffer(); private String path = null; private String expName = null; @Before public void setUp() throws Exception { driver = new FirefoxDriver(); baseUrl = ExpFileReadUtils.readProperty("base.url"); subUrl = ExpFileReadUtils.readProperty("sub.url"); path = ExpFileReadUtils.readProperty("local.path"); expName = ExpFileReadUtils.readProperty("experiment.name"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testGaussianKarst() throws Exception { driver.get(baseUrl + subUrl); authenticate(driver); driver.findElement(By.linkText("Experiment")).click(); driver.findElement(By.cssSelector("li.dropdown.open > ul.dropdown-menu > li > #create")).click(); waitTime(200); driver.findElement(By.id("experiment-name")).sendKeys(expName + "Gaussian-Karst"); waitTime(200); driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment"); waitTime(200); new Select(driver.findElement(By.id("project"))).selectByVisibleText (ExpFileReadUtils.readProperty("project.name")); waitTime(200); new Select(driver.findElement(By.id("application"))).selectByVisibleText("Gaussian"); waitTime(200); driver.findElement(By.name("continue")).click(); waitTime(200); driver.findElement(By.id("Input-File")).sendKeys(ExpFileReadUtils.GAUSSIAN_INPUT3); waitTime(200); new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("karst.uits.iu.edu"); waitTime (200); new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("batch"); waitTime (200); driver.findElement(By.id("node-count")).clear(); driver.findElement(By.id("node-count")).sendKeys("1"); driver.findElement(By.id("cpu-count")).clear(); driver.findElement(By.id("cpu-count")).sendKeys("16"); driver.findElement(By.id("wall-time")).clear(); driver.findElement(By.id("wall-time")).sendKeys("30"); driver.findElement(By.id("memory-count")).clear(); driver.findElement(By.id("memory-count")).sendKeys("0"); driver.findElement(By.id("enableEmail")).click(); driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1")); driver.findElement(By.xpath("(//button[@type='button'])[3]")).click(); driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2")); waitTime (200); driver.findElement(By.id("expLaunch")).click(); } private void waitTime(int i) { try { Thread.sleep(i); } catch (InterruptedException e) { e.printStackTrace(); } } @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } private boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } } }
package com.practice.e2021.validate2log.filter.cached; public interface CachedStreamEntity { CachedStream getCachedStream(); void flushStream(); }
/** * 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.camel.component.irc; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.Processor; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.UnsafeUriCharactersEncoder; import org.schwering.irc.lib.IRCConnection; import org.schwering.irc.lib.IRCConstants; import org.schwering.irc.lib.IRCModeParser; import org.schwering.irc.lib.IRCUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The irc component implements an <a href="https://en.wikipedia.org/wiki/Internet_Relay_Chat">IRC</a> (Internet Relay Chat) transport. */ @UriEndpoint( firstVersion = "1.1.0", scheme = "irc", title = "IRC", syntax = "irc:hostname:port", alternativeSyntax = "irc:username:password@hostname:port", consumerClass = IrcConsumer.class, label = "chat") public class IrcEndpoint extends DefaultEndpoint { private static final Logger LOG = LoggerFactory.getLogger(IrcEndpoint.class); @UriParam private IrcConfiguration configuration; private IrcBinding binding; private IrcComponent component; public IrcEndpoint(String endpointUri, IrcComponent component, IrcConfiguration configuration) { super(UnsafeUriCharactersEncoder.encode(endpointUri), component); this.component = component; this.configuration = configuration; } public boolean isSingleton() { return true; } public Exchange createExchange(ExchangePattern pattern) { Exchange exchange = super.createExchange(pattern); exchange.setProperty(Exchange.BINDING, getBinding()); return exchange; } public Exchange createOnPrivmsgExchange(String target, IRCUser user, String msg) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("PRIVMSG", target, user, msg); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnNickExchange(IRCUser user, String newNick) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("NICK", user, newNick); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnQuitExchange(IRCUser user, String msg) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("QUIT", user, msg); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnJoinExchange(String channel, IRCUser user) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("JOIN", channel, user); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnKickExchange(String channel, IRCUser user, String whoWasKickedNick, String msg) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("KICK", channel, user, whoWasKickedNick, msg); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnModeExchange(String channel, IRCUser user, IRCModeParser modeParser) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("MODE", channel, user, modeParser.getLine()); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnPartExchange(String channel, IRCUser user, String msg) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("PART", channel, user, msg); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnReplyExchange(int num, String value, String msg) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("REPLY", num, value, msg); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public Exchange createOnTopicExchange(String channel, IRCUser user, String topic) { Exchange exchange = createExchange(); IrcMessage im = new IrcMessage("TOPIC", channel, user, topic); im.setExchange(exchange); im.setCamelContext(exchange.getContext()); exchange.setIn(im); return exchange; } public IrcProducer createProducer() throws Exception { return new IrcProducer(this, component.getIRCConnection(configuration)); } public IrcConsumer createConsumer(Processor processor) throws Exception { IrcConsumer answer = new IrcConsumer(this, processor, component.getIRCConnection(configuration)); configureConsumer(answer); return answer; } public IrcComponent getComponent() { return component; } public void setComponent(IrcComponent component) { this.component = component; } public IrcBinding getBinding() { if (binding == null) { binding = new IrcBinding(); } return binding; } public void setBinding(IrcBinding binding) { this.binding = binding; } public IrcConfiguration getConfiguration() { return configuration; } public void setConfiguration(IrcConfiguration configuration) { this.configuration = configuration; } public void handleIrcError(int num, String msg) { if (IRCConstants.ERR_NICKNAMEINUSE == num) { handleNickInUse(); } } private void handleNickInUse() { IRCConnection connection = component.getIRCConnection(configuration); String nick = connection.getNick() + "-"; // hackish but working approach to prevent an endless loop. Abort after 4 nick attempts. if (nick.endsWith("----")) { LOG.error("Unable to set nick: " + nick + " disconnecting"); } else { LOG.warn("Unable to set nick: " + nick + " Retrying with " + nick + "-"); connection.doNick(nick); // if the nick failure was doing startup channels weren't joined. So join // the channels now. It's a no-op if the channels are already joined. joinChannels(); } } public void joinChannels() { for (IrcChannel channel : configuration.getChannels()) { joinChannel(channel); } } public void joinChannel(String name) { joinChannel(configuration.findChannel(name)); } public void joinChannel(IrcChannel channel) { if (channel == null) { return; } IRCConnection connection = component.getIRCConnection(configuration); String chn = channel.getName(); String key = channel.getKey(); if (ObjectHelper.isNotEmpty(key)) { if (LOG.isDebugEnabled()) { LOG.debug("Joining: {} using {} with secret key", channel, connection.getClass().getName()); } connection.doJoin(chn, key); } else { if (LOG.isDebugEnabled()) { LOG.debug("Joining: {} using {}", channel, connection.getClass().getName()); } connection.doJoin(chn); } if (configuration.isNamesOnJoin()) { connection.doNames(chn); } } }
/** * Copyright &copy; 2017 <a href="www.wanhutong.com">wanhutong</a> All rights reserved. */ package com.wanhutong.backend.modules.biz.entity.product; import com.wanhutong.backend.modules.biz.entity.shelf.BizOpShelfInfo; import com.wanhutong.backend.modules.sys.entity.Office; import org.hibernate.validator.constraints.Length; import com.wanhutong.backend.modules.sys.entity.User; import javax.validation.constraints.NotNull; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.wanhutong.backend.common.persistence.DataEntity; /** * 产品查看日志Entity * @author zx * @version 2018-02-22 */ public class BizProdViewLog extends DataEntity<BizProdViewLog> { private static final long serialVersionUID = 1L; private BizOpShelfInfo opShelfInfo; // 货架ID private Office center; // 采购中心ID private BizProductInfo productInfo; // 产品ID private User user; // 用户ID //产品点击量 private Integer prodChick; private String prodChixkSource; private Integer orderCount; private String skuItemNo; public BizProdViewLog() { super(); } public BizProdViewLog(Integer id){ super(id); } public BizOpShelfInfo getOpShelfInfo() { return opShelfInfo; } public void setOpShelfInfo(BizOpShelfInfo opShelfInfo) { this.opShelfInfo = opShelfInfo; } public Office getCenter() { return center; } public void setCenter(Office center) { this.center = center; } public BizProductInfo getProductInfo() { return productInfo; } public void setProductInfo(BizProductInfo productInfo) { this.productInfo = productInfo; } @NotNull(message="用户ID不能为空") public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Integer getProdChick() { return prodChick; } public void setProdChick(Integer prodChick) { this.prodChick = prodChick; } public String getProdChixkSource() { return prodChixkSource; } public void setProdChixkSource(String prodChixkSource) { this.prodChixkSource = prodChixkSource; } public Integer getOrderCount() { return orderCount; } public void setOrderCount(Integer orderCount) { this.orderCount = orderCount; } public String getSkuItemNo() { return skuItemNo; } public void setSkuItemNo(String skuItemNo) { this.skuItemNo = skuItemNo; } }
/* * Copyright 2018 NEM * * 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.nem.sdk.model.transaction; import io.nem.sdk.model.account.Account; import io.nem.sdk.model.account.PublicAccount; import io.nem.sdk.model.blockchain.NetworkType; import org.bouncycastle.util.encoders.Hex; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class SecretProofTransactionTest { static Account account; @BeforeAll public static void setup() { account = new Account("787225aaff3d2c71f4ffa32d4f19ec4922f3cd869747f267378f81f8e3fcb12d", NetworkType.MIJIN_TEST); } @Test @DisplayName("Serialization") void serialization() { // Generated at nem2-library-js/test/transactions/SecretProofTransaction.spec.js byte[] expected = new byte[]{(byte)191,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,3,(byte)144,76,67,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(byte)183,120,(byte)163,(byte)154,54, 99,113,(byte)157,(byte)252,94,72,(byte)201,(byte)215,(byte)132,49,(byte)177,(byte)228,92,42,(byte)249, (byte)223,83,(byte)135,(byte)130,(byte)191,25,(byte)156,24,(byte)157,(byte)171,(byte)234,(byte)199,104, 10,(byte)218,87,(byte)220,(byte)236,(byte)142,(byte)238,(byte)145,(byte)196,(byte)227,(byte)191,59,(byte)250, (byte)154,(byte)246,(byte)255,(byte)222,(byte)144,(byte)205,29,36,(byte)157,28,97,33,(byte)215,(byte)183,89, (byte)160,1,(byte)177,4,0,(byte)154,73,54,100 }; String secret = "b778a39a3663719dfc5e48c9d78431b1e45c2af9df538782bf199c189dabeac7680ada57dcec8eee91c4e3bf3bfa9af6ffde90cd1d249d1c6121d7b759a001b1"; String secretSeed = "9a493664"; SecretProofTransaction secretProoftx = SecretProofTransaction.create( new FakeDeadline(), HashType.SHA3_512, secret, secretSeed, NetworkType.MIJIN_TEST ); byte[] actual = secretProoftx.generateBytes(); assertEquals(Hex.toHexString(expected), Hex.toHexString(actual)); } @Test @DisplayName("To aggregate") void toAggregate() { byte[] expected = new byte[]{(byte)111,0,0,0,-102,73,54,100,6,-84,-87,82,-72,-117,-83,-11,-15,-23,-66,108,-28,-106,-127, 65,3,90,96,-66,80,50,115,-22,101,69,107,36,3,(byte)144,76,67,0,(byte)183,120,(byte)163,(byte)154,54, 99,113,(byte)157,(byte)252,94,72,(byte)201,(byte)215,(byte)132,49,(byte)177,(byte)228,92,42,(byte)249, (byte)223,83,(byte)135,(byte)130,(byte)191,25,(byte)156,24,(byte)157,(byte)171,(byte)234,(byte)199,104, 10,(byte)218,87,(byte)220,(byte)236,(byte)142,(byte)238,(byte)145,(byte)196,(byte)227,(byte)191,59,(byte)250, (byte)154,(byte)246,(byte)255,(byte)222,(byte)144,(byte)205,29,36,(byte)157,28,97,33,(byte)215,(byte)183,89, (byte)160,1,(byte)177,4,0,(byte)154,73,54,100 }; String secret = "b778a39a3663719dfc5e48c9d78431b1e45c2af9df538782bf199c189dabeac7680ada57dcec8eee91c4e3bf3bfa9af6ffde90cd1d249d1c6121d7b759a001b1"; String secretSeed = "9a493664"; SecretProofTransaction secretProoftx = SecretProofTransaction.create( new FakeDeadline(), HashType.SHA3_512, secret, secretSeed, NetworkType.MIJIN_TEST ); byte[] actual = secretProoftx.toAggregate(new PublicAccount("9A49366406ACA952B88BADF5F1E9BE6CE4968141035A60BE503273EA65456B24", NetworkType.MIJIN_TEST)).toAggregateTransactionBytes(); assertArrayEquals(expected, actual); } @Test void serializeAndSignTransaction() { String secret = "b778a39a3663719dfc5e48c9d78431b1e45c2af9df538782bf199c189dabeac7680ada57dcec8eee91c4e3bf3bfa9af6ffde90cd1d249d1c6121d7b759a001b1"; String secretSeed = "9a493664"; SecretProofTransaction secretProoftx = SecretProofTransaction.create( new FakeDeadline(), HashType.SHA3_512, secret, secretSeed, NetworkType.MIJIN_TEST ); SignedTransaction signedTransaction = secretProoftx.signWith(account); assertEquals("BF000000147827E5FDAB2201ABD3663964B0493166DA7DD18497718F53DF09AAFC55271B57A9E81B4E2F627FD19E9E9B77283D1620FB8E9E32BAC5AC265EB0B43C75B4071026D70E1954775749C6811084D6450A3184D977383F0E4282CD47118AF3775503904C430000000000000000010000000000000000B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7680ADA57DCEC8EEE91C4E3BF3BFA9AF6FFDE90CD1D249D1C6121D7B759A001B104009A493664", signedTransaction.getPayload()); assertEquals("1169864A7290940854D87C8818625A7A498E6550D19F9BFAF5BA7BEFEB9206D0", signedTransaction.getHash()); } @Test void shouldThrowErrorWhenSecretIsNotValid() { String proof = "B778A39A3663719DFC5E48C9D78431B1E45C2AF9DF538782BF199C189DABEAC7680ADA57DCEC8EEE91" + "C4E3BF3BFA9AF6FFDE90CD1D249D1C6121D7B759A001B1"; assertThrows(IllegalArgumentException.class, ()-> { SecretProofTransaction secretProoftx = SecretProofTransaction.create( new FakeDeadline(), HashType.SHA3_512, "non valid hash", proof, NetworkType.MIJIN_TEST ); }, "not a valid secret"); } }
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.entitlement.cache; import java.io.Serializable; import java.security.Key; import java.util.Arrays; import java.util.Date; import java.util.Set; /** * Identity Cache entry which wraps the identity related cache entry values */ public class IdentityCacheEntry implements Serializable { private static final long serialVersionUID = 3746964700806693258L; private String cacheEntry; private Set<String> cacheEntrySet; private String[] cacheEntryArray; private int hashEntry; private long cacheInterval; private boolean cacheClearing; private Key secretKey; private Date date; public IdentityCacheEntry(String cacheEntry) { this.cacheEntry = cacheEntry; } public IdentityCacheEntry(int hashEntry) { this.hashEntry = hashEntry; } public IdentityCacheEntry(boolean cacheClearing) { this.cacheClearing = cacheClearing; } public IdentityCacheEntry(String cacheEntry, long cacheInterval) { this.cacheEntry = cacheEntry; this.cacheInterval = cacheInterval; } public IdentityCacheEntry(String[] cacheEntryArray) { this.cacheEntryArray = Arrays.copyOf(cacheEntryArray, cacheEntryArray.length); } public IdentityCacheEntry(Set<String> cacheEntrySet) { this.cacheEntrySet = cacheEntrySet; } public IdentityCacheEntry(String cacheEntry, Key secretKey, Date date) { this.cacheEntry = cacheEntry; this.secretKey = secretKey; this.date = new Date(date.getTime()); } public String getCacheEntry() { return cacheEntry; } public int getHashEntry() { return hashEntry; } public long getCacheInterval() { return cacheInterval; } public Set<String> getCacheEntrySet() { return cacheEntrySet; } public boolean isCacheClearing() { return cacheClearing; } public String[] getCacheEntryArray() { return Arrays.copyOf(cacheEntryArray, cacheEntryArray.length); } public Key getSecretKey() { return secretKey; } public Date getDate() { return new Date(date.getTime()); } }
/* KeyGenerator.java -- Interface to a symmetric key generator. Copyright (C) 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.crypto; import gnu.java.security.Engine; import java.lang.reflect.InvocationTargetException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.SecureRandom; import java.security.Security; import java.security.spec.AlgorithmParameterSpec; /** * A generic producer of keys for symmetric cryptography. The keys * returned may be simple wrappers around byte arrays, or, if the * target cipher requires them, more complex objects. * * @author Casey Marshall (csm@gnu.org) * @since 1.4 * @see Cipher * @see Mac */ public class KeyGenerator { // Constants and fields. // ------------------------------------------------------------------------ private static final String SERVICE = "KeyGenerator"; /** The underlying generator implementation. */ private KeyGeneratorSpi kgSpi; /** The provider of the implementation. */ private Provider provider; /** The name of the algorithm. */ private String algorithm; // Constructor. // ------------------------------------------------------------------------ /** * Create a new key generator. * * @param kgSpi The underlying generator. * @param provider The provider of this implementation. * @param algorithm The algorithm's name. */ protected KeyGenerator(KeyGeneratorSpi kgSpi, Provider provider, String algorithm) { this.kgSpi = kgSpi; this.provider = provider; this.algorithm = algorithm; } /** * Create a new key generator, returning the first available implementation. * * @param algorithm The generator algorithm name. * @throws NoSuchAlgorithmException If the specified algorithm does not exist. * @throws IllegalArgumentException if <code>algorithm</code> is * <code>null</code> or is an empty string. */ public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException { Provider[] p = Security.getProviders(); NoSuchAlgorithmException lastException = null; for (int i = 0; i < p.length; i++) try { return getInstance(algorithm, p[i]); } catch (NoSuchAlgorithmException x) { lastException = x; } if (lastException != null) throw lastException; throw new NoSuchAlgorithmException(algorithm); } /** * Create a new key generator from the named provider. * * @param algorithm The generator algorithm name. * @param provider The name of the provider to use. * @return An appropriate key generator, if found. * @throws NoSuchAlgorithmException If the specified algorithm is not * implemented by the named provider. * @throws NoSuchProviderException If the named provider does not exist. * @throws IllegalArgumentException if either <code>algorithm</code> or * <code>provider</code> is <code>null</code>, or if * <code>algorithm</code> is an empty string. */ public static final KeyGenerator getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { if (provider == null) throw new IllegalArgumentException("provider MUST NOT be null"); Provider p = Security.getProvider(provider); if (p == null) throw new NoSuchProviderException(provider); return getInstance(algorithm, p); } /** * Create a new key generator from the supplied provider. * * @param algorithm The generator algorithm name. * @param provider The provider to use. * @return An appropriate key generator, if found. * @throws NoSuchAlgorithmException If the specified algorithm is not * implemented by the provider. * @throws IllegalArgumentException if either <code>algorithm</code> or * <code>provider</code> is <code>null</code>, or if * <code>algorithm</code> is an empty string. */ public static final KeyGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException { StringBuilder sb = new StringBuilder("KeyGenerator algorithm [") .append(algorithm).append("] from provider[") .append(provider).append("] could not be created"); Throwable cause; try { Object spi = Engine.getInstance(SERVICE, algorithm, provider); KeyGenerator instance = new KeyGenerator((KeyGeneratorSpi) spi, provider, algorithm); instance.init(new SecureRandom()); return instance; } catch (InvocationTargetException x) { cause = x.getCause(); if (cause instanceof NoSuchAlgorithmException) throw (NoSuchAlgorithmException) cause; if (cause == null) cause = x; } catch (ClassCastException x) { cause = x; } NoSuchAlgorithmException x = new NoSuchAlgorithmException(sb.toString()); x.initCause(cause); throw x; } /** * Generate a key. * * @return The new key. */ public final SecretKey generateKey() { return kgSpi.engineGenerateKey(); } /** * Return the name of this key generator. * * @return The algorithm name. */ public final String getAlgorithm() { return algorithm; } /** * Return the provider of the underlying implementation. * * @return The provider. */ public final Provider getProvider() { return provider; } /** * Initialize this key generator with a set of parameters; the * highest-priority {@link java.security.SecureRandom} implementation * will be used. * * @param params The algorithm parameters. * @throws java.security.InvalidAlgorithmParameterException If the * supplied parameters are inapproprate. */ public final void init(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException { init(params, new SecureRandom()); } /** * Initialize this key generator with a set of parameters and a source * of randomness. * * @param params The algorithm parameters. * @param random The source of randomness. * @throws java.security.InvalidAlgorithmParameterException If the * supplied parameters are inapproprate. */ public final void init(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { kgSpi.engineInit(params, random); } /** * Initialize this key generator with a key size (in bits); the * highest-priority {@link java.security.SecureRandom} implementation * will be used. * * @param keySize The target key size, in bits. * @throws java.security.InvalidParameterException If the * key size is unsupported. */ public final void init(int keySize) { init(keySize, new SecureRandom()); } /** * Initialize this key generator with a key size (in bits) and a * source of randomness. * * @param keySize The target key size, in bits. * @param random The source of randomness. * @throws java.security.InvalidAlgorithmParameterException If the * key size is unsupported. */ public final void init(int keySize, SecureRandom random) { kgSpi.engineInit(keySize, random); } /** * Initialize this key generator with a source of randomness. The * implementation-specific default parameters (such as key size) will * be used. * * @param random The source of randomness. */ public final void init(SecureRandom random) { kgSpi.engineInit(random); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.milleni.dunning.datamodel.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author kemala */ @Entity @Table(name = "DUNNING_PROCESS_MASTER_HIST") @XmlRootElement @NamedQueries({ @NamedQuery(name = "DunningProcessMasterHist.findAll", query = "SELECT d FROM DunningProcessMasterHist d"), @NamedQuery(name = "DunningProcessMasterHist.findByHistId", query = "SELECT d FROM DunningProcessMasterHist d WHERE d.histId = :histId"), @NamedQuery(name = "DunningProcessMasterHist.findByStatus", query = "SELECT d FROM DunningProcessMasterHist d WHERE d.status = :status"), @NamedQuery(name = "DunningProcessMasterHist.findByStatusDate", query = "SELECT d FROM DunningProcessMasterHist d WHERE d.statusDate = :statusDate"), @NamedQuery(name = "DunningProcessMasterHist.findByCreateDate", query = "SELECT d FROM DunningProcessMasterHist d WHERE d.createDate = :createDate"), @NamedQuery(name = "DunningProcessMasterHist.findByCreateUser", query = "SELECT d FROM DunningProcessMasterHist d WHERE d.createUser = :createUser")}) public class DunningProcessMasterHist extends BaseModel implements Serializable { private static final long serialVersionUID = 1L; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Id @Basic(optional = false) @NotNull @Column(name = "HIST_ID") private Long histId; @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "STATUS") private String status; @Column(name = "STATUS_DATE") @Temporal(TemporalType.TIMESTAMP) private Date statusDate; @JoinColumn(name = "PROCESS_ID", referencedColumnName = "PROCESS_ID") @ManyToOne(optional = false,fetch=FetchType.LAZY) private DunningProcessMaster processId; public DunningProcessMasterHist() { } public DunningProcessMasterHist(Long histId) { this.histId = histId; } public DunningProcessMasterHist(Long histId, String status) { this.histId = histId; this.status = status; } public Long getHistId() { return histId; } public void setHistId(Long histId) { this.histId = histId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getStatusDate() { return statusDate; } public void setStatusDate(Date statusDate) { this.statusDate = statusDate; } public DunningProcessMaster getProcessId() { return processId; } public void setProcessId(DunningProcessMaster processId) { this.processId = processId; } @Override public int hashCode() { int hash = 0; hash += (histId != null ? histId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DunningProcessMasterHist)) { return false; } DunningProcessMasterHist other = (DunningProcessMasterHist) object; if ((this.histId == null && other.histId != null) || (this.histId != null && !this.histId.equals(other.histId))) { return false; } return true; } @Override public String toString() { return "org.milleni.dunning.datamodel.model.DunningProcessMasterHist[ histId=" + histId + " ]"; } }
/* * Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.ml.recommendation; public class ALSPartitionInfo { public int ratingsNum; public int csrRowNum; }
package io.github.donggi.jpa.entity; import javax.persistence.Entity; import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; @Entity @Table(name = "jpa_voice_with_actor2") @Data @EqualsAndHashCode(callSuper=true) @NoArgsConstructor @SuperBuilder public class VoiceWithActor2 extends Voice2 { private String voiceActor; }
/* * CophylogenyModel.java * * Cophy: Cophylogenetics for BEAST * * Copyright (c) 2015 Arman Bilge <armanbilge@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package cophy.model; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.Units; import dr.inference.model.AbstractModel; import dr.inference.model.Model; /** * * @author Arman D. Bilge <armanbilge@gmail.com> * */ public abstract class CophylogenyModel extends AbstractModel implements Units { private static final long serialVersionUID = -2874567072654237379L; protected final Tree hostTree; protected Units.Type units; public CophylogenyModel(final String name, final Tree hostTree, final Units.Type units) { super(name); this.hostTree = hostTree; if (hostTree instanceof Model) addModel((Model) hostTree); this.units = units; } public Tree getHostTree() { return hostTree; } @Override public Units.Type getUnits() { return units; } @Override public void setUnits(Units.Type units) { this.units = units; } public abstract double getOriginHeight(); public abstract double getBirthRate(); public abstract double getDeathRate(); public double getSamplingProbability(final NodeRef host) { return 1.0; } }
package io.renren.modules.cbs.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.renren.common.utils.BaseEntity; import io.renren.modules.cbs.vo.ContractVo; import io.swagger.annotations.ApiModelProperty; import lombok.*; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; /** * @author chenshun * @email sunlightcs@gmail.com * @date 2020-02-20 17:14:19 */ @EqualsAndHashCode(callSuper = true) @Data @Builder @AllArgsConstructor @NoArgsConstructor @TableName("cbs_purchase") public class CbsPurchaseEntity extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; /** * */ @TableId private Long id; /** * 关联合同cbs_contract */ private Long fkContractId; /** * 发票金额 */ private BigDecimal invoiceMoney; /** * 发票编号 */ private String invoiceCode; /** * 关联仓库名录表(cbs_directory_store)ID */ private Long fkStoreId; /** * 关联运输公司名录表(cbs_directory_transit_company)ID */ private Long fkTransitCompanyId; /** * 运输车牌号 */ private String wagonNumber; /** * 创建时间 */ private Date createTime; /** * 出发时间 */ private Date departTime; /** * 抵达时间 */ private Date arrivalTime; /** * 删除说明 */ private String deleteNote; /** * 审核时间 */ private Date examineTime; /** * 删除时间 */ private Date deleteTime; /** * 操作人 */ private Long operator; /** * 提货地址 */ private String startAddress; /** * 提货地址-联系人 */ private String startContact; /** * 提货地址-联系人-电话 */ private String startPhone; /** * 收货地址 */ private String endAddress; /** * 收货地址-联系人 */ private String endContact; /** * 收货地址-联系人-电话 */ private String endPhone; /** * 国内运费 */ private BigDecimal transFeeMoney; /** * 是否同步创建入库单 转化Boolean 需要在使用数据库加入&tinyInt1isBit=false */ private Boolean synStoreIn; /** * 1、编辑中 2、审核中 3、审核失败 4、审核通过 99、已删除 */ private Integer status; /** * saas业务分离,关联cbs_company_id */ private Long tenantId; @ApiModelProperty("如果所有进口单物料与合同物料吻合(>=),用户依然要创建进口单") @TableField(exist = false) private Boolean forceToCreate; @ApiModelProperty("合同实体") @TableField(exist = false) private CbsContractEntity contractEntity; @ApiModelProperty("商品实体列表") @TableField(exist = false) private List<CbsPurchaseGoodsEntity> purchaseGoodsList; @ApiModelProperty("仓库名录表") @TableField(exist = false) private CbsDirectoryStoreEntity storeEntity; @ApiModelProperty("国内运输公司名录表") @TableField(exist = false) private CbsDirectoryTransitCompanyEntity transitCompanyEntity; @ApiModelProperty("发票附件list") @TableField(exist = false) private List<CbsImgPurchaseInvoiceEntity> imgPurchaseInvoiceList; @ApiModelProperty("cbs_img_purchase_delivery_order") @TableField(exist = false) private List<CbsImgPurchaseDeliveryOrderEntity> imgPurchaseDeliveryOrderList; @ApiModelProperty("cbs_img_purchase_receipt") @TableField(exist = false) private List<CbsImgPurchaseReceiptEntity> imgPurchaseReceiptList; @ApiModelProperty("查询参数") @TableField(exist = false) private ContractVo searchForm; @ApiModelProperty("store_goods_in_id") @TableField(exist = false) private Long storeGoodsInId; @ApiModelProperty("store_goods_in_status") @TableField(exist = false) private Integer storeGoodsInStatus; }
package com.apps.www.grabilityapp; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; public class AboutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); if(getResources().getBoolean(R.bool.portrait_only)){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } setContentView(R.layout.activity_about); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); } @Override protected void onStop() { super.onStop(); finish(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: this.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
package net.minecraft.client.resources.data; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import net.minecraft.client.resources.data.BaseMetadataSectionSerializer; import net.minecraft.client.resources.data.PackMetadataSection; import net.minecraft.util.IChatComponent; import net.minecraft.util.JsonUtils; public class PackMetadataSectionSerializer extends BaseMetadataSectionSerializer<PackMetadataSection> implements JsonSerializer<PackMetadataSection> { public PackMetadataSection deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException { JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); IChatComponent ichatcomponent = (IChatComponent)p_deserialize_3_.deserialize(jsonobject.get("description"), IChatComponent.class); if(ichatcomponent == null) { throw new JsonParseException("Invalid/missing description!"); } else { int i = JsonUtils.func_151203_m(jsonobject, "pack_format"); return new PackMetadataSection(ichatcomponent, i); } } public JsonElement serialize(PackMetadataSection p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_) { JsonObject jsonobject = new JsonObject(); jsonobject.addProperty("pack_format", (Number)Integer.valueOf(p_serialize_1_.func_110462_b())); jsonobject.add("description", p_serialize_3_.serialize(p_serialize_1_.func_152805_a())); return jsonobject; } public String func_110483_a() { return "pack"; } }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.query; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ListenableFuture; import com.metamx.common.guava.Sequence; import com.metamx.common.guava.Sequences; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.CountAggregatorFactory; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Test; import java.util.Collections; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; public class AsyncQueryRunnerTest { private final static long TEST_TIMEOUT = 60000; private final ExecutorService executor; private final Query query; public AsyncQueryRunnerTest() { this.executor = Executors.newSingleThreadExecutor(); query = Druids.newTimeseriesQueryBuilder() .dataSource("test") .intervals("2014/2015") .aggregators(Lists.<AggregatorFactory>newArrayList(new CountAggregatorFactory("count"))) .build(); } @Test(timeout = TEST_TIMEOUT) public void testAsyncNature() throws Exception { final CountDownLatch latch = new CountDownLatch(1); QueryRunner baseRunner = new QueryRunner() { @Override public Sequence run(Query query, Map responseContext) { try { latch.await(); return Sequences.simple(Lists.newArrayList(1)); } catch(InterruptedException ex) { throw Throwables.propagate(ex); } } }; AsyncQueryRunner asyncRunner = new AsyncQueryRunner<>(baseRunner, executor, QueryRunnerTestHelper.NOOP_QUERYWATCHER); Sequence lazy = asyncRunner.run(query, Collections.EMPTY_MAP); latch.countDown(); Assert.assertEquals(Lists.newArrayList(1), Sequences.toList(lazy, Lists.newArrayList())); } @Test(timeout = TEST_TIMEOUT) public void testQueryTimeoutHonored() { QueryRunner baseRunner = new QueryRunner() { @Override public Sequence run(Query query, Map responseContext) { try { Thread.sleep(Long.MAX_VALUE); throw new RuntimeException("query should not have completed"); } catch(InterruptedException ex) { throw Throwables.propagate(ex); } } }; AsyncQueryRunner asyncRunner = new AsyncQueryRunner<>(baseRunner, executor, QueryRunnerTestHelper.NOOP_QUERYWATCHER); Sequence lazy = asyncRunner.run( query.withOverriddenContext(ImmutableMap.<String,Object>of(QueryContextKeys.TIMEOUT, 1)), Collections.EMPTY_MAP); try { Sequences.toList(lazy, Lists.newArrayList()); } catch(RuntimeException ex) { Assert.assertTrue(ex.getCause() instanceof TimeoutException); return; } Assert.fail(); } @Test public void testQueryRegistration() { QueryRunner baseRunner = new QueryRunner() { @Override public Sequence run(Query query, Map responseContext) { return null; } }; QueryWatcher mock = EasyMock.createMock(QueryWatcher.class); mock.registerQuery(EasyMock.eq(query), EasyMock.anyObject(ListenableFuture.class)); EasyMock.replay(mock); AsyncQueryRunner asyncRunner = new AsyncQueryRunner<>(baseRunner, executor, mock); asyncRunner.run(query, Collections.EMPTY_MAP); EasyMock.verify(mock); } }
package com.guiying.module.girls.main; import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.girls.data.bean.Movie; import java.util.List; /** * <p>类说明</p> * * @author yangfeihu 2017/2/22 20:33 * @version V1.2.0 * @name GirlsContract */ public interface MovieContract { interface View extends BaseView<Presenter> { /** * View 的存活状态 * * @return true or false */ boolean isActive(); void refresh(List<Movie> data); void load(List<Movie> data); void showError(); void showNormal(); } interface Presenter extends BasePresenter { void getGirls(int page, int size, boolean isRefresh); } }
package com.dianping.cat.alarm.spi.receiver; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.unidal.lookup.ContainerHolder; import org.unidal.lookup.annotation.Named; import com.dianping.cat.alarm.spi.AlertChannel; @Named public class ContactorManager extends ContainerHolder implements Initializable { private Map<String, Contactor> m_contactors = new HashMap<String, Contactor>(); @Override public void initialize() throws InitializationException { m_contactors = lookupMap(Contactor.class); } public List<String> queryReceivers(String group, AlertChannel channel, String type) { Contactor contactor = m_contactors.get(type); if (AlertChannel.MAIL == channel) { return contactor.queryEmailContactors(group); } else if (AlertChannel.SMS == channel) { return contactor.querySmsContactors(group); } else if (AlertChannel.WEIXIN == channel) { return contactor.queryWeiXinContactors(group); } else if (AlertChannel.DX == channel) { return contactor.queryDXContactors(group); } else { throw new RuntimeException("unsupported channnel"); } } }
/* * Copyright 2000-2009 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.patterns; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ProcessingContext; import dk.brics.automaton.Automaton; import dk.brics.automaton.DatatypesAutomatonProvider; import dk.brics.automaton.RegExp; import dk.brics.automaton.RunAutomaton; import org.jetbrains.annotations.NonNls; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.regex.Pattern; /** * @author peter */ public class StringPattern extends ObjectPattern<String, StringPattern> { private static final InitialPatternCondition<String> CONDITION = new InitialPatternCondition<String>(String.class) { @Override public boolean accepts(@Nullable final Object o, final ProcessingContext context) { return o instanceof String; } @Override public void append(@Nonnull @NonNls final StringBuilder builder, final String indent) { builder.append("string()"); } }; protected StringPattern() { super(CONDITION); } @Nonnull public StringPattern startsWith(@NonNls @Nonnull final String s) { return with(new PatternCondition<String>("startsWith") { @Override public boolean accepts(@Nonnull final String str, final ProcessingContext context) { return str.startsWith(s); } }); } @Nonnull public StringPattern endsWith(@NonNls @Nonnull final String s) { return with(new PatternCondition<String>("endsWith") { @Override public boolean accepts(@Nonnull final String str, final ProcessingContext context) { return str.endsWith(s); } }); } @Nonnull public StringPattern contains(@NonNls @Nonnull final String s) { return with(new PatternCondition<String>("contains") { @Override public boolean accepts(@Nonnull final String str, final ProcessingContext context) { return str.contains(s); } }); } @Nonnull public StringPattern containsChars(@NonNls @Nonnull final String s) { return with(new PatternCondition<String>("containsChars") { @Override public boolean accepts(@Nonnull final String str, final ProcessingContext context) { for (int i=0, len=s.length(); i<len; i++) { if (str.indexOf(s.charAt(i))>-1) return true; } return false; } }); } @Nonnull public StringPattern matches(@NonNls @Nonnull final String s) { final String escaped = StringUtil.escapeToRegexp(s); if (escaped.equals(s)) { return equalTo(s); } // may throw PatternSyntaxException here final Pattern pattern = Pattern.compile(s); return with(new ValuePatternCondition<String>("matches") { @Override public boolean accepts(@Nonnull final String str, final ProcessingContext context) { return pattern.matcher(newBombedCharSequence(str)).matches(); } @Override public Collection<String> getValues() { return Collections.singleton(s); } }); } @Nonnull public StringPattern matchesBrics(@NonNls @Nonnull final String s) { final String escaped = StringUtil.escapeToRegexp(s); if (escaped.equals(s)) { return equalTo(s); } StringBuilder sb = new StringBuilder(s.length()*5); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); if(c == ' ') { sb.append("<whitespace>"); } else //This is really stupid and inconvenient builder - it breaks any normal pattern with uppercase if(Character.isUpperCase(c)) { sb.append('[').append(Character.toUpperCase(c)).append(Character.toLowerCase(c)).append(']'); } else { sb.append(c); } } final RegExp regExp = new RegExp(sb.toString()); final Automaton automaton = regExp.toAutomaton(new DatatypesAutomatonProvider()); final RunAutomaton runAutomaton = new RunAutomaton(automaton, true); return with(new ValuePatternCondition<String>("matchesBrics") { @Override public boolean accepts(@Nonnull String str, final ProcessingContext context) { if (!str.isEmpty() && (str.charAt(0) == '"' || str.charAt(0) == '\'')) str = str.substring(1); return runAutomaton.run(str); } @Override public Collection<String> getValues() { return Collections.singleton(s); } }); } @Nonnull public StringPattern contains(@NonNls @Nonnull final ElementPattern<Character> pattern) { return with(new PatternCondition<String>("contains") { @Override public boolean accepts(@Nonnull final String str, final ProcessingContext context) { for (int i = 0; i < str.length(); i++) { if (pattern.accepts(str.charAt(i))) return true; } return false; } }); } public StringPattern longerThan(final int minLength) { return with(new PatternCondition<String>("longerThan") { @Override public boolean accepts(@Nonnull final String s, final ProcessingContext context) { return s.length() > minLength; } }); } public StringPattern shorterThan(final int maxLength) { return with(new PatternCondition<String>("shorterThan") { @Override public boolean accepts(@Nonnull final String s, final ProcessingContext context) { return s.length() < maxLength; } }); } public StringPattern withLength(final int length) { return with(new PatternCondition<String>("withLength") { @Override public boolean accepts(@Nonnull final String s, final ProcessingContext context) { return s.length() == length; } }); } @Override @Nonnull public StringPattern oneOf(@NonNls final String... values) { return super.oneOf(values); } @Nonnull public StringPattern oneOfIgnoreCase(@NonNls final String... values) { return with(new CaseInsensitiveValuePatternCondition("oneOfIgnoreCase", values)); } @Override @Nonnull public StringPattern oneOf(@NonNls final Collection<String> set) { return super.oneOf(set); } @Nonnull public static CharSequence newBombedCharSequence(@Nonnull CharSequence sequence) { return new StringUtil.BombedCharSequence(sequence) { @Override protected void checkCanceled() { ProgressManager.checkCanceled(); } }; } }
/** * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.sch.model; /** * Collection of work request errors. * * <br/> * Note: Objects should always be created or deserialized using the {@link Builder}. This model distinguishes fields * that are {@code null} because they are unset from fields that are explicitly set to {@code null}. This is done in * the setter methods of the {@link Builder}, which maintain a set of all explicitly set fields called * {@link #__explicitlySet__}. The {@link #hashCode()} and {@link #equals(Object)} methods are implemented to take * {@link #__explicitlySet__} into account. The constructor, on the other hand, does not set {@link #__explicitlySet__} * (since the constructor cannot distinguish explicit {@code null} from unset {@code null}). **/ @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20200909") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize( builder = WorkRequestErrorCollection.Builder.class ) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) @lombok.Builder(builderClassName = "Builder", toBuilder = true) public class WorkRequestErrorCollection { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("items") private java.util.List<WorkRequestError> items; public Builder items(java.util.List<WorkRequestError> items) { this.items = items; this.__explicitlySet__.add("items"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); public WorkRequestErrorCollection build() { WorkRequestErrorCollection __instance__ = new WorkRequestErrorCollection(items); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(WorkRequestErrorCollection o) { Builder copiedBuilder = items(o.getItems()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The list of items. * **/ @com.fasterxml.jackson.annotation.JsonProperty("items") java.util.List<WorkRequestError> items; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); }
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.elasticbeanstalk.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.elasticbeanstalk.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; /** * DescribeEnvironmentResourcesRequest Marshaller */ public class DescribeEnvironmentResourcesRequestMarshaller implements Marshaller<Request<DescribeEnvironmentResourcesRequest>, DescribeEnvironmentResourcesRequest> { public Request<DescribeEnvironmentResourcesRequest> marshall( DescribeEnvironmentResourcesRequest describeEnvironmentResourcesRequest) { if (describeEnvironmentResourcesRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<DescribeEnvironmentResourcesRequest> request = new DefaultRequest<DescribeEnvironmentResourcesRequest>( describeEnvironmentResourcesRequest, "AWSElasticBeanstalk"); request.addParameter("Action", "DescribeEnvironmentResources"); request.addParameter("Version", "2010-12-01"); request.setHttpMethod(HttpMethodName.POST); if (describeEnvironmentResourcesRequest.getEnvironmentId() != null) { request.addParameter("EnvironmentId", StringUtils .fromString(describeEnvironmentResourcesRequest .getEnvironmentId())); } if (describeEnvironmentResourcesRequest.getEnvironmentName() != null) { request.addParameter("EnvironmentName", StringUtils .fromString(describeEnvironmentResourcesRequest .getEnvironmentName())); } return request; } }
/* * 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.sysml.runtime.instructions.spark; import org.apache.spark.api.java.JavaPairRDD; import org.apache.sysml.lops.SortKeys; import org.apache.sysml.parser.Expression.DataType; import org.apache.sysml.parser.Expression.ValueType; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.DMLUnsupportedOperationException; import org.apache.sysml.runtime.controlprogram.context.ExecutionContext; import org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext; import org.apache.sysml.runtime.instructions.InstructionUtils; import org.apache.sysml.runtime.instructions.cp.CPOperand; import org.apache.sysml.runtime.instructions.spark.utils.RDDSortUtils; import org.apache.sysml.runtime.matrix.MatrixCharacteristics; import org.apache.sysml.runtime.matrix.data.MatrixBlock; import org.apache.sysml.runtime.matrix.data.MatrixIndexes; import org.apache.sysml.runtime.matrix.operators.Operator; import org.apache.sysml.runtime.matrix.operators.SimpleOperator; public class QuantileSortSPInstruction extends UnarySPInstruction { /* * This class supports two variants of sort operation on a 1-dimensional input matrix. * The two variants are <code> weighted </code> and <code> unweighted </code>. * Example instructions: * sort:mVar1:mVar2 (input=mVar1, output=mVar2) * sort:mVar1:mVar2:mVar3 (input=mVar1, weights=mVar2, output=mVar3) * */ public QuantileSortSPInstruction(Operator op, CPOperand in, CPOperand out, String opcode, String istr){ this(op, in, null, out, opcode, istr); } public QuantileSortSPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out, String opcode, String istr){ super(op, in1, in2, out, opcode, istr); _sptype = SPINSTRUCTION_TYPE.QSort; } public static QuantileSortSPInstruction parseInstruction ( String str ) throws DMLRuntimeException { CPOperand in1 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN); CPOperand in2 = null; CPOperand out = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN); String[] parts = InstructionUtils.getInstructionPartsWithValueType(str); String opcode = parts[0]; if ( opcode.equalsIgnoreCase(SortKeys.OPCODE) ) { if ( parts.length == 3 ) { // Example: sort:mVar1:mVar2 (input=mVar1, output=mVar2) parseUnaryInstruction(str, in1, out); return new QuantileSortSPInstruction(new SimpleOperator(null), in1, out, opcode, str); } else if ( parts.length == 4 ) { // Example: sort:mVar1:mVar2:mVar3 (input=mVar1, weights=mVar2, output=mVar3) in2 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN); parseUnaryInstruction(str, in1, in2, out); return new QuantileSortSPInstruction(new SimpleOperator(null), in1, in2, out, opcode, str); } else { throw new DMLRuntimeException("Invalid number of operands in instruction: " + str); } } else { throw new DMLRuntimeException("Unknown opcode while parsing a SortSPInstruction: " + str); } } @Override public void processInstruction(ExecutionContext ec) throws DMLUnsupportedOperationException, DMLRuntimeException { SparkExecutionContext sec = (SparkExecutionContext)ec; boolean weighted = (input2 != null); //get input rdds JavaPairRDD<MatrixIndexes,MatrixBlock> in = sec.getBinaryBlockRDDHandleForVariable( input1.getName() ); JavaPairRDD<MatrixIndexes,MatrixBlock> inW = weighted ? sec.getBinaryBlockRDDHandleForVariable( input2.getName() ) : null; MatrixCharacteristics mc = sec.getMatrixCharacteristics(input1.getName()); JavaPairRDD<MatrixIndexes,MatrixBlock> out = null; long clen = -1; if( !weighted ) { //W/O WEIGHTS (default) out = RDDSortUtils.sortByVal(in, mc.getRows(), mc.getRowsPerBlock()); clen = 1; } else { //W/ WEIGHTS out = RDDSortUtils.sortByVal(in, inW, mc.getRows(), mc.getRowsPerBlock()); clen = 2; } //put output RDD handle into symbol table sec.setRDDHandleForVariable(output.getName(), out); sec.addLineageRDD(output.getName(), input1.getName()); if( weighted ) sec.addLineageRDD(output.getName(), input2.getName()); //update output matrix characteristics MatrixCharacteristics mcOut = sec.getMatrixCharacteristics(output.getName()); mcOut.set(mc.getRows(), clen, mc.getRowsPerBlock(), mc.getColsPerBlock()); } }
package de.yard.threed.platform.webgl; import com.google.gwt.json.client.JSONString; import de.yard.threed.core.platform.NativeJsonString; public class WebGlJsonString extends WebGlJsonValue implements NativeJsonString { JSONString value; public WebGlJsonString(JSONString value) { this.value = value; s=true; } @Override public String stringValue() { return value.stringValue(); } }
package guru.springframework.spring5recipeapp.converters; import guru.springframework.spring5recipeapp.commands.CategoryCommand; import guru.springframework.spring5recipeapp.domain.Category; import lombok.Synchronized; import org.springframework.core.convert.converter.Converter; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; /** * Created by jt on 6/21/17. */ @Component public class CategoryToCategoryCommand implements Converter<Category, CategoryCommand> { @Synchronized @Nullable @Override public CategoryCommand convert(Category source) { if (source == null) { return null; } final CategoryCommand categoryCommand = new CategoryCommand(); categoryCommand.setId(source.getId()); categoryCommand.setDescription(source.getDescription()); return categoryCommand; } }
package org.wikipedia.feed.onthisday; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import androidx.core.app.ActivityOptionsCompat; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.RecyclerView; import org.apache.commons.lang3.StringUtils; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.dataclient.restbase.page.RbPageSummary; import org.wikipedia.history.HistoryEntry; import org.wikipedia.main.MainActivity; import org.wikipedia.page.PageActivity; import org.wikipedia.page.PageTitle; import org.wikipedia.util.ResourceUtil; import org.wikipedia.util.StringUtil; import org.wikipedia.views.FaceAndColorDetectImageView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnLongClick; import static org.wikipedia.page.PageActivity.ACTION_LOAD_IN_NEW_TAB; import static org.wikipedia.page.PageActivity.EXTRA_HISTORYENTRY; import static org.wikipedia.page.PageActivity.EXTRA_PAGETITLE; public class OnThisDayPagesViewHolder extends RecyclerView.ViewHolder { public interface ItemCallBack { void onActionLongClick(@NonNull HistoryEntry entry); } @BindView(R.id.page_list_item_title) TextView pageItemTitleTextView; @BindView(R.id.page_list_item_description) TextView pageItemDescTextView; @BindView(R.id.page_list_item_image) FaceAndColorDetectImageView pageItemImageView; @BindView(R.id.parent) View parent; @Nullable private ItemCallBack itemCallback; private WikiSite wiki; private Activity activity; private RbPageSummary selectedPage; private final boolean isSingleCard; OnThisDayPagesViewHolder(@NonNull Activity activity, @NonNull CardView v, @NonNull WikiSite wiki, boolean isSingleCard) { super(v); ButterKnife.bind(this, v); v.setCardBackgroundColor(ResourceUtil.getThemedColor(v.getContext(), R.attr.paper_color)); this.wiki = wiki; this.isSingleCard = isSingleCard; this.activity = activity; } public void setFields(@NonNull RbPageSummary page) { selectedPage = page; pageItemDescTextView.setText(StringUtils.capitalize(page.getDescription())); pageItemDescTextView.setVisibility(TextUtils.isEmpty(page.getDescription()) ? View.GONE : View.VISIBLE); pageItemTitleTextView.setMaxLines(TextUtils.isEmpty(page.getDescription()) ? 2 : 1); pageItemTitleTextView.setText(StringUtil.fromHtml(StringUtils.defaultString(page.getNormalizedTitle()))); setImage(page.getThumbnailUrl()); } private void setImage(@Nullable String url) { pageItemImageView.loadImage(url == null ? null : Uri.parse(url)); } @NonNull public OnThisDayPagesViewHolder setCallback(@Nullable ItemCallBack itemCallback) { this.itemCallback = itemCallback; return this; } @OnClick(R.id.parent) void onBaseViewClicked() { Context context = WikipediaApp.getInstance().getApplicationContext(); PageTitle pageTitle = new PageTitle(selectedPage.getTitle(), wiki); HistoryEntry entry = new HistoryEntry(pageTitle, isSingleCard ? HistoryEntry.SOURCE_ON_THIS_DAY_CARD : HistoryEntry.SOURCE_ON_THIS_DAY_ACTIVITY); Bundle bundle = null; if (activity instanceof MainActivity) { bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, ((MainActivity) activity) .getFloatingQueueImageView(), ViewCompat.getTransitionName(((MainActivity) activity) .getFloatingQueueImageView())).toBundle(); } Intent intent = new Intent(ACTION_LOAD_IN_NEW_TAB) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .setClass(activity, PageActivity.class) .putExtra(EXTRA_HISTORYENTRY, entry) .putExtra(EXTRA_PAGETITLE, pageTitle); activity.startActivity(intent, bundle); } @OnLongClick(R.id.parent) boolean showOverflowMenu(View anchorView) { PageTitle pageTitle = new PageTitle(selectedPage.getTitle(), wiki); HistoryEntry entry = new HistoryEntry(pageTitle, isSingleCard ? HistoryEntry.SOURCE_ON_THIS_DAY_CARD : HistoryEntry.SOURCE_ON_THIS_DAY_ACTIVITY); itemCallback.onActionLongClick(entry); return true; } }
package com.minminaya.aaudemo.activity; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.minminaya.aau.utils.ThreadPoolManagerUtils; import com.minminaya.aaudemo.R; public class HomeActivity extends AppCompatActivity { private static final String TAG = HomeActivity.class.getSimpleName(); @SuppressLint("ResourceType") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ThreadPoolManagerUtils.getsInstance() .setNewBuilder(new ThreadPoolManagerUtils.Builder()) .executeRunnableBySpeciallyPool("THREADPOOL-1", new Runnable() { @Override public void run() { for (int i = 0; i < 5; i++) { Log.d(TAG, "当前的i为:" + i); } } }); // BarsHelper.addGradientOrNormalStatusBarViewAtDecorView(this, false, R.drawable.gradient_1, -1, 1.0f); // BarsHelper.setStatusTransparentAndColor(this, getResources().getColor(R.color.colorPrimaryDark), 0.0f); } }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * 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. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.componentmodel.design; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.collections.ICollection; import system.collections.ICollectionImplementation; import system.componentmodel.design.SelectionTypes; import system.EventHandler; /** * The base .NET class managing System.ComponentModel.Design.ISelectionService, System.ComponentModel.TypeConverter, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.Design.ISelectionService" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.Design.ISelectionService</a> */ public class ISelectionServiceImplementation extends NetObject implements ISelectionService { /** * Fully assembly qualified name: System.ComponentModel.TypeConverter, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a */ public static final String assemblyFullName = "System.ComponentModel.TypeConverter, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; /** * Assembly name: System.ComponentModel.TypeConverter */ public static final String assemblyShortName = "System.ComponentModel.TypeConverter"; /** * Qualified class name: System.ComponentModel.Design.ISelectionService */ public static final String className = "System.ComponentModel.Design.ISelectionService"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public ISelectionServiceImplementation(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link ISelectionService}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link ISelectionService} instance * @throws java.lang.Throwable in case of error during cast operation */ public static ISelectionService ToISelectionService(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new ISelectionServiceImplementation(from.getJCOInstance()); } // Methods section public boolean GetComponentSelected(NetObject component) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Invoke("GetComponentSelected", component == null ? null : component.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public ICollection GetSelectedComponents() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetSelectedComponents = (JCObject)classInstance.Invoke("GetSelectedComponents"); return new ICollectionImplementation(objGetSelectedComponents); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void SetSelectedComponents(ICollection components) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("SetSelectedComponents", components == null ? null : components.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void SetSelectedComponents(ICollection components, SelectionTypes selectionType) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("SetSelectedComponents", components == null ? null : components.getJCOInstance(), selectionType == null ? null : selectionType.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section public int getSelectionCount() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("SelectionCount"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public NetObject getPrimarySelection() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("PrimarySelection"); return new NetObject(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section public void addSelectionChanged(EventHandler handler) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.RegisterEventListener("SelectionChanged", handler); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void removeSelectionChanged(EventHandler handler) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.UnregisterEventListener("SelectionChanged", handler); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void addSelectionChanging(EventHandler handler) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.RegisterEventListener("SelectionChanging", handler); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void removeSelectionChanging(EventHandler handler) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.UnregisterEventListener("SelectionChanging", handler); } catch (JCNativeException jcne) { throw translateException(jcne); } } }
package com.kang.novel.ui.home; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; import androidx.viewpager.widget.ViewPager; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.LoadAdError; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.material.tabs.TabLayout; import com.kang.novel.R; import com.kang.novel.common.APPCONST; import com.kang.novel.databinding.ActivityMainBinding; import com.kang.novel.util.SystemBarTintManager; import com.kang.novel.util.TextHelper; public class MainActivity extends FragmentActivity { private MainPrensenter mMainPrensenter; private ActivityMainBinding binding; AdView mAdView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!isTaskRoot()) { finish(); return; } binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setStatusBar(R.color.sys_line); mMainPrensenter = new MainPrensenter(this); mMainPrensenter.enable(); mAdView = findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); mAdView.setAdListener(new AdListener() { @Override public void onAdClicked() { super.onAdClicked(); Log.d("mAdView"," 广告 加载 onAdClicked"); } @Override public void onAdClosed() { super.onAdClosed(); Log.d("mAdView"," 广告 加载 onAdClosed"); } @Override public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) { super.onAdFailedToLoad(loadAdError); Log.d("mAdView"," 广告 加载 onAdFailedToLoad" + loadAdError.toString()); } @Override public void onAdImpression() { super.onAdImpression(); Log.d("mAdView"," 广告 加载 onAdImpression"); } @Override public void onAdLoaded() { super.onAdLoaded(); Log.d("mAdView"," 广告 加载 onAdLoaded"); } @Override public void onAdOpened() { super.onAdOpened(); Log.d("mAdView"," 广告 加载 onAdOpened"); } }); } // @Override // public void onBackPressed() { // if (System.currentTimeMillis() - APPCONST.exitTime > APPCONST.exitConfirmTime) { // TextHelper.showText("再按一次退出"); // APPCONST.exitTime = System.currentTimeMillis(); // } else { // finish(); // } // } public TabLayout getTlTabMenu() { return binding.tlTabMenu; } public ImageView getIvSearch() { return binding.ivSearch; } public ViewPager getVpContent() { return binding.vpContent; } public RelativeLayout getRlCommonTitle() { return binding.rlCommonTitle; } @TargetApi(19) protected void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } /** * 设置状态栏颜色 * * @param colorId */ public void setStatusBar(int colorId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); SystemBarTintManager tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintEnabled(true); tintManager.setStatusBarTintResource(colorId);//通知栏所需颜色ID } } }
/* * 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.johnzon.mapper.converter; import org.apache.johnzon.mapper.Converter; import java.util.HashMap; import java.util.Map; public class EnumConverter<T extends Enum<T>> implements Converter<T> { private final Map<String, T> values; public EnumConverter(final Class<T> aClass) { final T[] enumConstants = aClass.getEnumConstants(); values = new HashMap<String, T>(enumConstants.length); for (final T t : enumConstants) { values.put(t.name(), t); } } @Override // no need of cache here, it is already fast public String toString(final T instance) { return instance.name(); } @Override public T fromString(final String text) { return values.get(text); } }
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.testing; import com.google.javascript.jscomp.mozilla.rhino.ErrorReporter; import com.google.javascript.jscomp.mozilla.rhino.EvaluatorException; import junit.framework.Assert; /** * <p>An error reporter for testing that verifies that messages reported to the * reporter are expected.</p> * * <p>Sample use</p> * <pre> * TestErrorReporter e = * new TestErrorReporter(null, new String[] { "first warning" }); * ... * assertTrue(e.hasEncounteredAllWarnings()); * </pre> * */ public final class TestErrorReporter extends Assert implements ErrorReporter { private final String[] errors; private final String[] warnings; private int errorsIndex = 0; private int warningsIndex = 0; public TestErrorReporter(String[] errors, String[] warnings) { this.errors = errors; this.warnings = warnings; } public void error(String message, String sourceName, int line, String lineSource, int lineOffset) { if (errors != null && errorsIndex < errors.length) { assertEquals(errors[errorsIndex++], message); } else { fail("extra error: " + message); } } public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { if (warnings != null && warningsIndex < warnings.length) { assertEquals(warnings[warningsIndex++], message); } else { fail("extra warning: " + message); } } public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { return new EvaluatorException("JSCompiler test code: " + message); } /** * Returns whether all warnings were reported to this reporter. */ public boolean hasEncounteredAllWarnings() { return (warnings == null) ? warningsIndex == 0 : warnings.length == warningsIndex; } /** * Returns whether all errors were reported to this reporter. */ public boolean hasEncounteredAllErrors() { return (errors == null) ? errorsIndex == 0 : errors.length == errorsIndex; } }
/* * 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.iceberg.aws.s3; import software.amazon.awssdk.http.HttpStatusCode; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.model.S3Exception; abstract class BaseS3File { private final S3Client client; private final S3URI uri; private HeadObjectResponse metadata; BaseS3File(S3Client client, S3URI uri) { this.client = client; this.uri = uri; } public String location() { return uri.location(); } S3Client client() { return client; } S3URI uri() { return uri; } /** * Note: this may be stale if file was deleted since metadata is cached for size/existence checks. * * @return flag */ public boolean exists() { try { return getObjectMetadata() != null; } catch (S3Exception e) { if (e.statusCode() == HttpStatusCode.NOT_FOUND) { return false; } else { throw e; // return null if 404 Not Found, otherwise rethrow } } } protected HeadObjectResponse getObjectMetadata() throws S3Exception { if (metadata == null) { metadata = client().headObject(HeadObjectRequest.builder() .bucket(uri().bucket()) .key(uri().key()) .build()); } return metadata; } @Override public String toString() { return uri.toString(); } }
package com.taxation.dao; import com.taxation.bean.ChatMessageEntity; public interface ChatMessageDao { int insert(ChatMessageEntity record); int insertSelective(ChatMessageEntity record); }
/* * Copyright (c) 2016-2018 Zerocracy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to read * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.zerocracy.farm.sync; import com.jcabi.s3.Bucket; import com.jcabi.s3.fake.FkBucket; import com.zerocracy.Farm; import com.zerocracy.Item; import com.zerocracy.Project; import com.zerocracy.RunsInThreads; import com.zerocracy.farm.S3Farm; import com.zerocracy.farm.fake.FkFarm; import com.zerocracy.pm.scope.Wbs; import com.zerocracy.pm.staff.Roles; import com.zerocracy.pmo.People; import com.zerocracy.pmo.Pmo; import java.io.IOException; import java.nio.file.Files; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.cactoos.func.RunnableOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; /** * Test case for {@link SyncFarm}. * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @checkstyle ExecutableStatementCountCheck (500 lines) */ public final class SyncFarmTest { @Test public void makesProjectsThreadSafe() throws Exception { final Bucket bucket = new FkBucket( Files.createTempDirectory("").toFile(), "the-bucket" ); try (final Farm farm = new SyncFarm(new S3Farm(bucket))) { final Project project = farm.find("@id='ABCZZFE03'") .iterator().next(); final Roles roles = new Roles(project); final String role = "QA"; MatcherAssert.assertThat( inc -> { final String person = String.format( "jeff%d", inc.incrementAndGet() ); final String task = String.format( "gh:test/test#%d", inc.incrementAndGet() ); new Wbs(project).bootstrap().add(task); roles.bootstrap().assign(person, role); return roles.hasRole(person, role); }, new RunsInThreads<>(new AtomicInteger()) ); } } @Test public void interruptsTooLongThread() throws Exception { final Bucket bucket = new FkBucket( Files.createTempDirectory("").toFile(), "the-bucket-1" ); try (final Farm farm = new SyncFarm( new S3Farm(bucket), TimeUnit.SECONDS.toMillis(1L) )) { final Project pmo = new Pmo(farm); final CountDownLatch locked = new CountDownLatch(1); new Thread( new RunnableOf<Object>( input -> { try (final Item item = pmo.acq("expectedfailure.xml")) { MatcherAssert.assertThat( item.path(), Matchers.notNullValue() ); locked.countDown(); TimeUnit.MINUTES.sleep(1L); } } ) ).start(); locked.await(); try (final Item item = pmo.acq("a.xml")) { MatcherAssert.assertThat( item.path(), Matchers.notNullValue() ); } try (final Item item = pmo.acq("c.xml")) { MatcherAssert.assertThat( item.path(), Matchers.notNullValue() ); } } } /** * Shutdown test. * @throws Exception Expected * @todo #476:30min Method freeze should wait for all processed claims, * and stop giving new claims with IOException, * it should block all SyncProjects so they stops to * return SyncItems and wait for all current opened SyncItems to close. */ @Test(expected = IOException.class) @Ignore public void freezeAndBlockNewItems() throws Exception { final SyncFarm farm = new SyncFarm(new FkFarm()); farm.close(); new People(farm).bootstrap(); } }
// Copyright 2018 The Bazel Authors. 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.devtools.build.lib.query2.cquery; import static java.util.stream.Collectors.joining; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.DependencyKey; import com.google.devtools.build.lib.analysis.DependencyKind; import com.google.devtools.build.lib.analysis.DependencyKind.ToolchainDependencyKind; import com.google.devtools.build.lib.analysis.DependencyResolver; import com.google.devtools.build.lib.analysis.InconsistentAspectOrderException; import com.google.devtools.build.lib.analysis.TargetAndConfiguration; import com.google.devtools.build.lib.analysis.ToolchainCollection; import com.google.devtools.build.lib.analysis.ToolchainContext; import com.google.devtools.build.lib.analysis.config.BuildConfiguration; import com.google.devtools.build.lib.analysis.config.BuildOptions; import com.google.devtools.build.lib.analysis.config.BuildOptions.OptionsDiff; import com.google.devtools.build.lib.analysis.config.ConfigMatchingProvider; import com.google.devtools.build.lib.analysis.config.transitions.ConfigurationTransition; import com.google.devtools.build.lib.analysis.config.transitions.NoTransition; import com.google.devtools.build.lib.analysis.config.transitions.NullTransition; import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory; import com.google.devtools.build.lib.analysis.config.transitions.TransitionUtil; import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget; import com.google.devtools.build.lib.causes.Cause; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.ExtendedEventHandler; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.Target; import com.google.devtools.build.lib.query2.engine.QueryEnvironment.TargetAccessor; import com.google.devtools.build.lib.skyframe.SkyframeExecutor; import com.google.devtools.build.lib.util.OrderedSetMultimap; import java.io.OutputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; /** * Output formatter that prints {@link ConfigurationTransition} information for rule configured * targets in the results of a cquery call. */ class TransitionsOutputFormatterCallback extends CqueryThreadsafeCallback { protected final BuildConfiguration hostConfiguration; private final HashMap<Label, Target> partialResultMap; @Nullable private final TransitionFactory<Rule> trimmingTransitionFactory; @Override public String getName() { return "transitions"; } /** * @param accessor provider of query result configured targets. * @param hostConfiguration host configuration for this query. */ TransitionsOutputFormatterCallback( ExtendedEventHandler eventHandler, CqueryOptions options, OutputStream out, SkyframeExecutor skyframeExecutor, TargetAccessor<KeyedConfiguredTarget> accessor, BuildConfiguration hostConfiguration, @Nullable TransitionFactory<Rule> trimmingTransitionFactory) { super(eventHandler, options, out, skyframeExecutor, accessor); this.hostConfiguration = hostConfiguration; this.trimmingTransitionFactory = trimmingTransitionFactory; this.partialResultMap = Maps.newHashMap(); } @Override public void processOutput(Iterable<KeyedConfiguredTarget> partialResult) throws InterruptedException { CqueryOptions.Transitions verbosity = options.transitions; if (verbosity.equals(CqueryOptions.Transitions.NONE)) { eventHandler.handle( Event.error( "Instead of using --output=transitions, set the --transitions" + " flag explicitly to 'lite' or 'full'")); return; } partialResult.forEach(kct -> partialResultMap.put(kct.getLabel(), accessor.getTarget(kct))); for (KeyedConfiguredTarget keyedConfiguredTarget : partialResult) { Target target = partialResultMap.get(keyedConfiguredTarget.getLabel()); BuildConfiguration config = getConfiguration(keyedConfiguredTarget.getConfigurationKey()); addResult( getRuleClassTransition(keyedConfiguredTarget.getConfiguredTarget(), target) + String.format( "%s (%s)", keyedConfiguredTarget.getConfiguredTarget().getOriginalLabel(), shortId(config))); if (!(keyedConfiguredTarget.getConfiguredTarget() instanceof RuleConfiguredTarget)) { continue; } OrderedSetMultimap<DependencyKind, DependencyKey> deps; ImmutableMap<Label, ConfigMatchingProvider> configConditions = keyedConfiguredTarget.getConfigConditions(); // Get a ToolchainContext to use for dependency resolution. ToolchainCollection<ToolchainContext> toolchainContexts = accessor.getToolchainContexts(target, config); try { // We don't actually use fromOptions in our implementation of // DependencyResolver but passing to avoid passing a null and since we have the information // anyway. deps = new FormatterDependencyResolver() .dependentNodeMap( new TargetAndConfiguration(target, config), hostConfiguration, /*aspect=*/ null, configConditions, toolchainContexts, DependencyResolver.shouldUseToolchainTransition(config, target), trimmingTransitionFactory); } catch (DependencyResolver.Failure | InconsistentAspectOrderException e) { // This is an abuse of InterruptedException. throw new InterruptedException(e.getMessage()); } for (Map.Entry<DependencyKind, DependencyKey> attributeAndDep : deps.entries()) { if (attributeAndDep.getValue().getTransition() == NoTransition.INSTANCE || attributeAndDep.getValue().getTransition() == NullTransition.INSTANCE) { continue; } DependencyKey dep = attributeAndDep.getValue(); BuildOptions fromOptions = config.getOptions(); // TODO(bazel-team): support transitions on Starlark-defined build flags. These require // Skyframe loading to get flag default values. See ConfigurationResolver.applyTransition // for an example of the required logic. Collection<BuildOptions> toOptions = dep.getTransition() .apply(TransitionUtil.restrict(dep.getTransition(), fromOptions), eventHandler) .values(); String hostConfigurationChecksum = hostConfiguration.checksum(); String dependencyName; if (DependencyKind.isToolchain(attributeAndDep.getKey())) { ToolchainDependencyKind tdk = (ToolchainDependencyKind) attributeAndDep.getKey(); if (tdk.isDefaultExecGroup()) { dependencyName = "[toolchain dependency]"; } else { dependencyName = String.format("[toolchain dependency: %s]", tdk.getExecGroupName()); } } else { dependencyName = attributeAndDep.getKey().getAttribute().getName(); } addResult( " " .concat(dependencyName) .concat("#") .concat(dep.getLabel().toString()) .concat("#") .concat(dep.getTransition().getName()) .concat(" -> ") .concat( toOptions.stream() .map( options -> { String checksum = options.computeChecksum(); return checksum.equals(hostConfigurationChecksum) ? "HOST" : shortId(checksum); }) .collect(joining(", ")))); if (verbosity == CqueryOptions.Transitions.LITE) { continue; } OptionsDiff diff = new OptionsDiff(); for (BuildOptions options : toOptions) { diff = BuildOptions.diff(diff, fromOptions, options); } diff.getPrettyPrintList().forEach(singleDiff -> addResult(" " + singleDiff)); } } } private String getRuleClassTransition(ConfiguredTarget ct, Target target) { String output = ""; if (ct instanceof RuleConfiguredTarget) { TransitionFactory<Rule> factory = target.getAssociatedRule().getRuleClassObject().getTransitionFactory(); if (factory != null) { output = factory.create(target.getAssociatedRule()).getClass().getSimpleName().concat(" -> "); } } return output; } private class FormatterDependencyResolver extends DependencyResolver { @Override protected Map<Label, Target> getTargets( OrderedSetMultimap<DependencyKind, Label> labelMap, TargetAndConfiguration fromNode, NestedSetBuilder<Cause> rootCauses) { return labelMap.values().stream() .distinct() .filter(Objects::nonNull) .filter(partialResultMap::containsKey) .collect(Collectors.toMap(Function.identity(), partialResultMap::get)); } } }
package com.udacity.gradle.builditbigger.loader; import android.os.AsyncTask; import com.udacity.gradle.builditbigger.service.JokeEndpointManager; import com.udacity.gradle.joke.backend.myApi.model.MyBean; import java.io.IOException; /** * Created by elnoxvie on 16/9/15. */ public class JokeLoader extends AsyncTask<Void,Void,MyBean>{ public interface LoaderCallback{ public void onPreExecute(); public void onPostExecute(MyBean myBean); } private LoaderCallback mCallback; @Override protected void onPreExecute() { super.onPreExecute(); if (mCallback != null){ mCallback.onPreExecute(); } } public void setCallback(LoaderCallback callback){ mCallback = callback; } @Override protected MyBean doInBackground(Void... voids) { try { return JokeEndpointManager.getInstance().getJoke(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(MyBean myBean) { super.onPostExecute(myBean); if (mCallback != null){ mCallback.onPostExecute(myBean); } } }
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.data.slashinginterchange; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import java.util.Objects; import org.apache.tuweni.bytes.Bytes32; import tech.pegasys.teku.infrastructure.unsigned.UInt64; @JsonInclude(JsonInclude.Include.NON_NULL) public class SignedAttestation { public final UInt64 sourceEpoch; public final UInt64 targetEpoch; public final Bytes32 signingRoot; @JsonCreator public SignedAttestation( @JsonProperty("source_epoch") final UInt64 sourceEpoch, @JsonProperty("target_epoch") final UInt64 targetEpoch, @JsonProperty("signing_root") final Bytes32 signingRoot) { this.sourceEpoch = sourceEpoch; this.targetEpoch = targetEpoch; this.signingRoot = signingRoot; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final SignedAttestation that = (SignedAttestation) o; return Objects.equals(sourceEpoch, that.sourceEpoch) && Objects.equals(targetEpoch, that.targetEpoch) && Objects.equals(signingRoot, that.signingRoot); } public UInt64 getSourceEpoch() { return sourceEpoch; } public UInt64 getTargetEpoch() { return targetEpoch; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("sourceEpoch", sourceEpoch) .add("targetEpoch", targetEpoch) .add("signingRoot", signingRoot) .toString(); } @Override public int hashCode() { return Objects.hash(sourceEpoch, targetEpoch, signingRoot); } }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.grid.node.local; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Ticker; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.NoSuchSessionException; import org.openqa.selenium.PersistentCapabilities; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.concurrent.Regularly; import org.openqa.selenium.events.EventBus; import org.openqa.selenium.grid.data.CreateSessionRequest; import org.openqa.selenium.grid.data.CreateSessionResponse; import org.openqa.selenium.grid.data.NodeDrainComplete; import org.openqa.selenium.grid.data.NodeDrainStarted; import org.openqa.selenium.grid.data.NodeId; import org.openqa.selenium.grid.data.NodeStatus; import org.openqa.selenium.grid.data.Session; import org.openqa.selenium.grid.data.SessionClosedEvent; import org.openqa.selenium.grid.data.Slot; import org.openqa.selenium.grid.data.SlotId; import org.openqa.selenium.grid.node.ActiveSession; import org.openqa.selenium.grid.node.HealthCheck; import org.openqa.selenium.grid.node.Node; import org.openqa.selenium.grid.node.SessionFactory; import org.openqa.selenium.grid.security.Secret; import org.openqa.selenium.internal.Require; import org.openqa.selenium.io.TemporaryFilesystem; import org.openqa.selenium.io.Zip; import org.openqa.selenium.json.Json; import org.openqa.selenium.remote.SessionId; import org.openqa.selenium.remote.http.HttpRequest; import org.openqa.selenium.remote.http.HttpResponse; import org.openqa.selenium.remote.tracing.AttributeKey; import org.openqa.selenium.remote.tracing.EventAttribute; import org.openqa.selenium.remote.tracing.EventAttributeValue; import org.openqa.selenium.remote.tracing.Span; import org.openqa.selenium.remote.tracing.Status; import org.openqa.selenium.remote.tracing.Tracer; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.net.URISyntaxException; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Logger; import java.util.stream.Collectors; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static org.openqa.selenium.grid.data.Availability.DRAINING; import static org.openqa.selenium.grid.data.Availability.UP; import static org.openqa.selenium.grid.node.CapabilityResponseEncoder.getEncoder; import static org.openqa.selenium.remote.HttpSessionId.getSessionId; import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES; import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES_EVENT; import static org.openqa.selenium.remote.RemoteTags.SESSION_ID; import static org.openqa.selenium.remote.RemoteTags.SESSION_ID_EVENT; import static org.openqa.selenium.remote.http.Contents.asJson; import static org.openqa.selenium.remote.http.Contents.string; import static org.openqa.selenium.remote.http.HttpMethod.DELETE; public class LocalNode extends Node { private static final Json JSON = new Json(); private static final Logger LOG = Logger.getLogger(LocalNode.class.getName()); private final EventBus bus; private final URI externalUri; private final URI gridUri; private final HealthCheck healthCheck; private final int maxSessionCount; private final List<SessionSlot> factories; private final Cache<SessionId, SessionSlot> currentSessions; private final Cache<SessionId, TemporaryFilesystem> tempFileSystems; private final Regularly regularly; private final Secret registrationSecret; private AtomicInteger pendingSessions = new AtomicInteger(); private LocalNode( Tracer tracer, EventBus bus, URI uri, URI gridUri, HealthCheck healthCheck, int maxSessionCount, Ticker ticker, Duration sessionTimeout, List<SessionSlot> factories, Secret registrationSecret) { super(tracer, new NodeId(UUID.randomUUID()), uri, registrationSecret); this.bus = Require.nonNull("Event bus", bus); this.externalUri = Require.nonNull("Remote node URI", uri); this.gridUri = Require.nonNull("Grid URI", gridUri); this.maxSessionCount = Math.min(Require.positive("Max session count", maxSessionCount), factories.size()); this.factories = ImmutableList.copyOf(factories); this.registrationSecret = registrationSecret; this.healthCheck = healthCheck == null ? () -> new HealthCheck.Result( isDraining() ? DRAINING : UP, String.format("%s is %s", uri, isDraining() ? "draining" : "up")) : healthCheck; this.currentSessions = CacheBuilder.newBuilder() .expireAfterAccess(sessionTimeout) .ticker(ticker) .removalListener((RemovalListener<SessionId, SessionSlot>) notification -> { // If we were invoked explicitly, then return: we know what we're doing. if (!notification.wasEvicted()) { return; } killSession(notification.getValue()); }) .build(); this.tempFileSystems = CacheBuilder.newBuilder() .expireAfterAccess(sessionTimeout) .ticker(ticker) .removalListener((RemovalListener<SessionId, TemporaryFilesystem>) notification -> { TemporaryFilesystem tempFS = notification.getValue(); tempFS.deleteTemporaryFiles(); tempFS.deleteBaseDir(); }) .build(); this.regularly = new Regularly("Local Node: " + externalUri); regularly.submit(currentSessions::cleanUp, Duration.ofSeconds(30), Duration.ofSeconds(30)); regularly.submit(tempFileSystems::cleanUp, Duration.ofSeconds(30), Duration.ofSeconds(30)); bus.addListener(SessionClosedEvent.listener(id -> { try { this.stop(id); } catch (NoSuchSessionException ignore) { } if (this.isDraining()) { int done = pendingSessions.decrementAndGet(); if (done <= 0) { LOG.info("Firing node drain complete message"); bus.fire(new NodeDrainComplete(this.getId())); } } })); } @Override public boolean isReady() { return bus.isReady(); } @VisibleForTesting public int getCurrentSessionCount() { // It seems wildly unlikely we'll overflow an int return Math.toIntExact(currentSessions.size()); } @Override public boolean isSupporting(Capabilities capabilities) { return factories.parallelStream().anyMatch(factory -> factory.test(capabilities)); } @Override public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) { Require.nonNull("Session request", sessionRequest); try (Span span = tracer.getCurrentContext().createSpan("node.new_session")) { Map<String, EventAttributeValue> attributeMap = new HashMap<>(); attributeMap .put(AttributeKey.LOGGER_CLASS.getKey(), EventAttribute.setValue(getClass().getName())); LOG.fine("Creating new session using span: " + span); attributeMap.put("session.request.capabilities", EventAttribute.setValue(sessionRequest.getCapabilities().toString())); attributeMap.put("session.request.downstreamdialect", EventAttribute.setValue(sessionRequest.getDownstreamDialects().toString())); int currentSessionCount = getCurrentSessionCount(); span.setAttribute("current.session.count", currentSessionCount); attributeMap.put("current.session.count", EventAttribute.setValue(currentSessionCount)); if (getCurrentSessionCount() >= maxSessionCount) { span.setAttribute("error", true); span.setStatus(Status.RESOURCE_EXHAUSTED); attributeMap.put("max.session.count", EventAttribute.setValue(maxSessionCount)); span.addEvent("Max session count reached", attributeMap); return Optional.empty(); } if (isDraining()) { span.setStatus(Status.UNAVAILABLE.withDescription("The node is draining. Cannot accept new sessions.")); return Optional.empty(); } // Identify possible slots to use as quickly as possible to enable concurrent session starting SessionSlot slotToUse = null; synchronized(factories) { for (SessionSlot factory : factories) { if (!factory.isAvailable() || !factory.test(sessionRequest.getCapabilities())) { continue; } factory.reserve(); slotToUse = factory; break; } } if (slotToUse == null) { span.setAttribute("error", true); span.setStatus(Status.NOT_FOUND); span.addEvent("No slot matched capabilities ", attributeMap); return Optional.empty(); } Optional<ActiveSession> possibleSession = slotToUse.apply(sessionRequest); if (!possibleSession.isPresent()) { slotToUse.release(); span.setAttribute("error", true); span.setStatus(Status.NOT_FOUND); span.addEvent("No slots available for capabilities ", attributeMap); return Optional.empty(); } ActiveSession session = possibleSession.get(); currentSessions.put(session.getId(), slotToUse); SessionId sessionId = session.getId(); Capabilities caps = session.getCapabilities(); SESSION_ID.accept(span, sessionId); CAPABILITIES.accept(span, caps); String downstream = session.getDownstreamDialect().toString(); String upstream = session.getUpstreamDialect().toString(); String sessionUri = session.getUri().toString(); span.setAttribute(AttributeKey.DOWNSTREAM_DIALECT.getKey(), downstream); span.setAttribute(AttributeKey.UPSTREAM_DIALECT.getKey(), upstream); span.setAttribute(AttributeKey.SESSION_URI.getKey(), sessionUri); // The session we return has to look like it came from the node, since we might be dealing // with a webdriver implementation that only accepts connections from localhost Session externalSession = createExternalSession(session, externalUri); return Optional.of(new CreateSessionResponse( externalSession, getEncoder(session.getDownstreamDialect()).apply(externalSession))); } } @Override public boolean isSessionOwner(SessionId id) { Require.nonNull("Session ID", id); return currentSessions.getIfPresent(id) != null; } @Override public Session getSession(SessionId id) throws NoSuchSessionException { Require.nonNull("Session ID", id); SessionSlot slot = currentSessions.getIfPresent(id); if (slot == null) { throw new NoSuchSessionException("Cannot find session with id: " + id); } return createExternalSession(slot.getSession(), externalUri); } @Override public TemporaryFilesystem getTemporaryFilesystem(SessionId id) throws IOException { try { return tempFileSystems.get(id, () -> TemporaryFilesystem.getTmpFsBasedOn( TemporaryFilesystem.getDefaultTmpFS().createTempDir("session", id.toString()))); } catch (ExecutionException e) { throw new IOException(e); } } @Override public HttpResponse executeWebDriverCommand(HttpRequest req) { // True enough to be good enough SessionId id = getSessionId(req.getUri()).map(SessionId::new) .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req)); SessionSlot slot = currentSessions.getIfPresent(id); if (slot == null) { throw new NoSuchSessionException("Cannot find session with id: " + id); } HttpResponse toReturn = slot.execute(req); if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) { stop(id); } return toReturn; } @Override public HttpResponse uploadFile(HttpRequest req, SessionId id) { Map<String, Object> incoming = JSON.toType(string(req), Json.MAP_TYPE); File tempDir; try { TemporaryFilesystem tempfs = getTemporaryFilesystem(id); tempDir = tempfs.createTempDir("upload", "file"); Zip.unzip((String) incoming.get("file"), tempDir); } catch (IOException e) { throw new UncheckedIOException(e); } // Select the first file File[] allFiles = tempDir.listFiles(); if (allFiles == null) { throw new WebDriverException( String.format("Cannot access temporary directory for uploaded files %s", tempDir)); } if (allFiles.length != 1) { throw new WebDriverException( String.format("Expected there to be only 1 file. There were: %s", allFiles.length)); } ImmutableMap<String, Object> result = ImmutableMap.of( "value", allFiles[0].getAbsolutePath()); return new HttpResponse().setContent(asJson(result)); } @Override public void stop(SessionId id) throws NoSuchSessionException { Require.nonNull("Session ID", id); SessionSlot slot = currentSessions.getIfPresent(id); if (slot == null) { throw new NoSuchSessionException("Cannot find session with id: " + id); } killSession(slot); tempFileSystems.invalidate(id); } private Session createExternalSession(ActiveSession other, URI externalUri) { Capabilities toUse = ImmutableCapabilities.copyOf(other.getCapabilities()); // Rewrite the se:options if necessary Object rawSeleniumOptions = other.getCapabilities().getCapability("se:options"); if (rawSeleniumOptions instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> original = (Map<String, Object>) rawSeleniumOptions; Map<String, Object> updated = new TreeMap<>(original); String cdpPath = String.format("/session/%s/se/cdp", other.getId()); updated.put("cdp", rewrite(cdpPath)); toUse = new PersistentCapabilities(toUse).setCapability("se:options", updated); } return new Session(other.getId(), externalUri, other.getStereotype(), toUse, Instant.now()); } private URI rewrite(String path) { try { return new URI( gridUri.getScheme(), gridUri.getUserInfo(), gridUri.getHost(), gridUri.getPort(), path, null, null); } catch (URISyntaxException e) { throw new RuntimeException(e); } } private void killSession(SessionSlot slot) { currentSessions.invalidate(slot.getSession().getId()); // Attempt to stop the session if (!slot.isAvailable()) { slot.stop(); } } @Override public NodeStatus getStatus() { Set<Slot> slots = factories.stream() .map(slot -> { Optional<Session> session = Optional.empty(); if (!slot.isAvailable()) { ActiveSession activeSession = slot.getSession(); session = Optional.of( new Session( activeSession.getId(), activeSession.getUri(), slot.getStereotype(), activeSession.getCapabilities(), activeSession.getStartTime())); } return new Slot( new SlotId(getId(), slot.getId()), slot.getStereotype(), Instant.EPOCH, session); }) .collect(toImmutableSet()); return new NodeStatus( getId(), externalUri, maxSessionCount, slots, isDraining() ? DRAINING : UP, registrationSecret); } @Override public HealthCheck getHealthCheck() { return healthCheck; } @Override public void drain() { bus.fire(new NodeDrainStarted(getId())); draining = true; int currentSessionCount = getCurrentSessionCount(); if (currentSessionCount == 0) { LOG.info("Firing node drain complete message"); bus.fire(new NodeDrainComplete(getId())); } else { pendingSessions.set(currentSessionCount); } } private Map<String, Object> toJson() { return ImmutableMap.of( "id", getId(), "uri", externalUri, "maxSessions", maxSessionCount, "draining", isDraining(), "capabilities", factories.stream() .map(SessionSlot::getStereotype) .collect(Collectors.toSet())); } public static Builder builder( Tracer tracer, EventBus bus, URI uri, URI gridUri, Secret registrationSecret) { return new Builder(tracer, bus, uri, gridUri, registrationSecret); } public static class Builder { private final Tracer tracer; private final EventBus bus; private final URI uri; private final URI gridUri; private final Secret registrationSecret; private final ImmutableList.Builder<SessionSlot> factories; private int maxCount = Runtime.getRuntime().availableProcessors() * 5; private Ticker ticker = Ticker.systemTicker(); private Duration sessionTimeout = Duration.ofMinutes(5); private HealthCheck healthCheck; public Builder( Tracer tracer, EventBus bus, URI uri, URI gridUri, Secret registrationSecret) { this.tracer = Require.nonNull("Tracer", tracer); this.bus = Require.nonNull("Event bus", bus); this.uri = Require.nonNull("Remote node URI", uri); this.gridUri = Require.nonNull("Grid URI", gridUri); this.registrationSecret = registrationSecret; this.factories = ImmutableList.builder(); } public Builder add(Capabilities stereotype, SessionFactory factory) { Require.nonNull("Capabilities", stereotype); Require.nonNull("Session factory", factory); factories.add(new SessionSlot(bus, stereotype, factory)); return this; } public Builder maximumConcurrentSessions(int maxCount) { this.maxCount = Require.positive("Max session count", maxCount); return this; } public Builder sessionTimeout(Duration timeout) { sessionTimeout = timeout; return this; } public LocalNode build() { return new LocalNode( tracer, bus, uri, gridUri, healthCheck, maxCount, ticker, sessionTimeout, factories.build(), registrationSecret); } public Advanced advanced() { return new Advanced(); } public class Advanced { public Advanced clock(Clock clock) { ticker = new Ticker() { @Override public long read() { return clock.instant().toEpochMilli() * Duration.ofMillis(1).toNanos(); } }; return this; } public Advanced healthCheck(HealthCheck healthCheck) { Builder.this.healthCheck = Require.nonNull("Health check", healthCheck); return this; } public Node build() { return Builder.this.build(); } } } }
package org.siouan.frontendgradleplugin.infrastructure.gradle; import javax.annotation.Nonnull; import org.gradle.api.provider.Provider; import org.gradle.api.provider.ProviderFactory; import org.siouan.frontendgradleplugin.FrontendGradlePlugin; import org.siouan.frontendgradleplugin.domain.model.SystemProperty; /** * Extension providing system settings. * * @since 5.2.0 */ public class SystemExtension { /** * Proxy host used to download resources with HTTP protocol. */ private final Provider<String> httpProxyHost; /** * Proxy port used to download resources with HTTP protocol. */ private final Provider<String> httpProxyPort; /** * Proxy host used to download resources with HTTPS protocol. */ private final Provider<String> httpsProxyHost; /** * Proxy port used to download resources with HTTPS protocol. */ private final Provider<String> httpsProxyPort; private final Provider<String> nonProxyHosts; private final Provider<String> jvmArch; private final Provider<String> osName; private final Provider<String> nodejsHomePath; public SystemExtension(@Nonnull final ProviderFactory providerFactory) { this.httpProxyHost = providerFactory.systemProperty(SystemProperty.HTTP_PROXY_HOST); this.httpProxyPort = providerFactory.systemProperty(SystemProperty.HTTP_PROXY_PORT); this.httpsProxyHost = providerFactory.systemProperty(SystemProperty.HTTPS_PROXY_HOST); this.httpsProxyPort = providerFactory.systemProperty(SystemProperty.HTTPS_PROXY_PORT); this.nonProxyHosts = providerFactory.systemProperty(SystemProperty.NON_PROXY_HOSTS); this.jvmArch = providerFactory.systemProperty(SystemProperty.JVM_ARCH_PROPERTY); this.osName = providerFactory.systemProperty(SystemProperty.OS_NAME_PROPERTY); this.nodejsHomePath = providerFactory.environmentVariable(FrontendGradlePlugin.NODEJS_HOME_ENV_VAR); } public Provider<String> getHttpProxyHost() { return httpProxyHost; } public Provider<String> getHttpProxyPort() { return httpProxyPort; } public Provider<String> getHttpsProxyHost() { return httpsProxyHost; } public Provider<String> getHttpsProxyPort() { return httpsProxyPort; } public Provider<String> getNonProxyHosts() { return nonProxyHosts; } public Provider<String> getJvmArch() { return jvmArch; } public Provider<String> getOsName() { return osName; } public Provider<String> getNodejsHomePath() { return nodejsHomePath; } }
package com.salesmanager.shop.store.api.v1.shoppingCart; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import java.security.Principal; import java.util.Arrays; import java.util.Optional; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.salesmanager.core.business.services.customer.CustomerService; import com.salesmanager.core.model.customer.Customer; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.model.shoppingcart.PersistableShoppingCartItem; import com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart; import com.salesmanager.shop.store.api.exception.OperationNotAllowedException; import com.salesmanager.shop.store.api.exception.ResourceNotFoundException; import com.salesmanager.shop.store.api.exception.ServiceRuntimeException; import com.salesmanager.shop.store.controller.customer.facade.v1.CustomerFacade; import com.salesmanager.shop.store.controller.shoppingCart.facade.ShoppingCartFacade; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import springfox.documentation.annotations.ApiIgnore; @Controller @RequestMapping("/api/v1") @Api(tags = { "Shopping cart api" }) @SwaggerDefinition(tags = { @Tag(name = "Shopping cart resource", description = "Add, remove and retrieve shopping carts") }) @SuppressWarnings("unused") public class ShoppingCartApi { @Inject private ShoppingCartFacade shoppingCartFacade; @Inject private com.salesmanager.shop.store.controller.shoppingCart.facade.v1.ShoppingCartFacade shoppingCartFacadev1; @Inject private CustomerService customerService; @Autowired private CustomerFacade customerFacadev1; @Autowired private com.salesmanager.shop.store.controller.customer.facade.CustomerFacade customerFacade; private static final Logger LOGGER = LoggerFactory.getLogger(ShoppingCartApi.class); @ResponseStatus(HttpStatus.CREATED) @PostMapping(value = "/cart") @ApiOperation(httpMethod = "POST", value = "Add product to shopping cart when no cart exists, this will create a new cart id", notes = "No customer ID in scope. Add to cart for non authenticated users, as simple as {\"product\":1232,\"quantity\":1}", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableShoppingCart addToCart( @Valid @RequestBody PersistableShoppingCartItem shoppingCartItem, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { return shoppingCartFacade.addToCart(shoppingCartItem, merchantStore, language); } @PutMapping(value = "/cart/{code}") @ApiOperation(httpMethod = "PUT", value = "Add to an existing shopping cart or modify an item quantity", notes = "No customer ID in scope. Modify cart for non authenticated users, as simple as {\"product\":1232,\"quantity\":0} for instance will remove item 1234 from cart", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ResponseEntity<ReadableShoppingCart> modifyCart( @PathVariable String code, @Valid @RequestBody PersistableShoppingCartItem shoppingCartItem, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) { try { ReadableShoppingCart cart = shoppingCartFacade.modifyCart(code, shoppingCartItem, merchantStore, language); if (cart == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(cart, HttpStatus.CREATED); } catch (Exception e) { if(e instanceof ResourceNotFoundException) { throw (ResourceNotFoundException)e; } else { throw new ServiceRuntimeException(e); } } } @PostMapping(value = "/cart/{code}/promo/{promo}") @ApiOperation(httpMethod = "POST", value = "Add promo / coupon to an existing cart", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ResponseEntity<ReadableShoppingCart> modifyCart( @PathVariable String code, @PathVariable String promo, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) { try { ReadableShoppingCart cart = shoppingCartFacade.modifyCart(code, promo, merchantStore, language); if (cart == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(cart, HttpStatus.CREATED); } catch (Exception e) { if(e instanceof ResourceNotFoundException) { throw (ResourceNotFoundException)e; } else { throw new ServiceRuntimeException(e); } } } @PostMapping(value = "/cart/{code}/multi", consumes = { "application/json" }, produces = { "application/json" }) @ApiOperation(httpMethod = "POST", value = "Add to an existing shopping cart or modify an item quantity", notes = "No customer ID in scope. Modify cart for non authenticated users, as simple as {\"product\":1232,\"quantity\":0} for instance will remove item 1234 from cart", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ResponseEntity<ReadableShoppingCart> modifyCart(@PathVariable String code, @Valid @RequestBody PersistableShoppingCartItem[] shoppingCartItems, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { try { ReadableShoppingCart cart = shoppingCartFacade.modifyCartMulti(code, Arrays.asList(shoppingCartItems), merchantStore, language); return new ResponseEntity<>(cart, HttpStatus.CREATED); } catch (Exception e) { if(e instanceof ResourceNotFoundException) { throw (ResourceNotFoundException)e; } else { throw new ServiceRuntimeException(e); } } } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/cart/{code}", method = RequestMethod.GET) @ApiOperation(httpMethod = "GET", value = "Get a chopping cart by code", notes = "", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableShoppingCart getByCode(@PathVariable String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) { try { ReadableShoppingCart cart = shoppingCartFacade.getByCode(code, merchantStore, language); if (cart == null) { response.sendError(404, "No ShoppingCart found for customer code : " + code); return null; } return cart; } catch (Exception e) { if(e instanceof ResourceNotFoundException) { throw (ResourceNotFoundException)e; } else { throw new ServiceRuntimeException(e); } } } @Deprecated @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = "/customers/{id}/cart", method = RequestMethod.POST) @ApiOperation(httpMethod = "POST", value = "Add product to a specific customer shopping cart", notes = "", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableShoppingCart addToCart(@PathVariable Long id, @Valid @RequestBody PersistableShoppingCartItem shoppingCartItem, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) { throw new OperationNotAllowedException("API is no more supported. Authenticate customer first then get customer cart"); } @Deprecated @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/auth/customer/{id}/cart", method = RequestMethod.GET) @ApiOperation(httpMethod = "GET", value = "Get a shopping cart by customer id. Customer must be authenticated", notes = "", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableShoppingCart getByCustomer(@PathVariable Long id, // customer // id @RequestParam Optional<String> cart, // cart code @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) { Principal principal = request.getUserPrincipal(); // lookup customer Customer customer = customerService.getById(id); if (customer == null) { throw new ResourceNotFoundException("No Customer found for id [" + id + "]"); } customerFacadev1.authorize(customer, principal); ReadableShoppingCart readableCart = shoppingCartFacadev1.get(cart, id, merchantStore, language); if (readableCart == null) { throw new ResourceNotFoundException("No cart found for customerid [" + id + "]"); } return readableCart; } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/auth/customer/cart", method = RequestMethod.GET) @ApiOperation(httpMethod = "GET", value = "Get a shopping cart by authenticated customer", notes = "", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableShoppingCart getByCustomer( @RequestParam Optional<String> cart, // cart code @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) { Principal principal = request.getUserPrincipal(); Customer customer = null; try { customer = customerFacade.getCustomerByUserName(principal.getName(), merchantStore); } catch (Exception e) { throw new ServiceRuntimeException("Exception while getting customer [ " + principal.getName() + "]"); } if (customer == null) { throw new ResourceNotFoundException("No Customer found for principal[" + principal.getName() + "]"); } customerFacadev1.authorize(customer, principal); ReadableShoppingCart readableCart = shoppingCartFacadev1.get(cart, customer.getId(), merchantStore, language); if (readableCart == null) { throw new ResourceNotFoundException("No cart found for customer [" + principal.getName() + "]"); } return readableCart; } @DeleteMapping(value = "/cart/{code}/product/{id}", produces = { APPLICATION_JSON_VALUE }) @ApiOperation(httpMethod = "DELETE", value = "Remove a product from a specific cart", notes = "If body set to true returns remaining cart in body, empty cart gives empty body. If body set to false no body ", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en"), @ApiImplicitParam(name = "body", dataType = "boolean", defaultValue = "false"), }) public ResponseEntity<ReadableShoppingCart> deleteCartItem(@PathVariable("code") String cartCode, @PathVariable("id") Long itemId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, @RequestParam(defaultValue = "false") boolean body) throws Exception { ReadableShoppingCart updatedCart = shoppingCartFacade.removeShoppingCartItem(cartCode, itemId, merchantStore, language, body); if (body) { return new ResponseEntity<>(updatedCart, HttpStatus.OK); } return new ResponseEntity<>(updatedCart, HttpStatus.NO_CONTENT); } }
package org.lumongo.ui.client.charting.options; import com.google.gwt.core.client.JavaScriptObject; public class SubtitleOptions extends JavaScriptObject { public static SubtitleOptions create() { return createObject().cast(); } protected SubtitleOptions() { } public final SubtitleOptions setAlign(AlignType alignType) { return setAlign(alignType.getName()); } protected final native SubtitleOptions setAlign(String align) /*-{ this.align = align; return this; }-*/; public final native SubtitleOptions setFloating(boolean floating) /*-{ this.floating = floating; return this; }-*/; public final native SubtitleOptions setStyle(String style) /*-{ this.style = style; return this; }-*/; public final native SubtitleOptions setText(String text) /*-{ this.text = text; return this; }-*/; public final native SubtitleOptions setUseHTML(boolean useHTML) /*-{ this.useHTML = useHTML; return this; }-*/; public final SubtitleOptions setVerticalAlign(VerticalAlignType verticalAlignType) { return setAlign(verticalAlignType.getName()); } protected final native SubtitleOptions setVerticalAlign(String verticalAlign) /*-{ this.verticalAlign = verticalAlign; return this; }-*/; public final native SubtitleOptions setX(int x) /*-{ this.x = x; return this; }-*/; public final native SubtitleOptions setY(int y) /*-{ this.y = y; return this; }-*/; }
/* ** Copyright [2012-2013] [Megam Systems] ** ** 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.megam.chef.parser; import org.megam.chef.core.Condition; import org.megam.chef.core.ScriptFeeder; import org.megam.chef.shell.MultiCommands; import org.megam.chef.shell.SingleShell; /** * @author rajthilak * */ abstract class ProvisionerInfo implements DataMap, ScriptFeeder, Condition { private String prov; /** * * @param prov */ ProvisionerInfo(String prov) { this.prov = prov; } /** * <p>getName.</p> * * @return a {@link java.lang.String} object. */ public String getName() { return prov; } }
package ffb.analyzer.models.espn.deserializers; import java.io.IOException; import java.time.LocalDate; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import ffb.analyzer.core.utilities.DateUtils; /** * Deserializes an ISO 8601 date formatted as 2019-08-19T07:41:09.149+0000. */ public class IsoDateWithOffsetDeserializer extends BaseObjectDeserializer<Map<LocalDate, Integer>> { private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; @Override public Map<LocalDate, Integer> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { Map<LocalDate, Integer> localDates = new HashMap<>(); JsonNode node = jsonParser.getCodec().readTree(jsonParser); Iterator<Entry<String, JsonNode>> fields = node.fields(); fields.forEachRemaining(field -> { localDates.put( DateUtils.fromString(field.getKey(), DATE_FORMAT), field.getValue().intValue() ); }); return localDates; } }
package net.minecraft.crash; import com.google.common.collect.Lists; import java.util.List; import java.util.concurrent.Callable; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; public class CrashReportCategory { private final CrashReport crashReport; private final String name; private final List<CrashReportCategory.Entry> children = Lists.newArrayList(); private StackTraceElement[] stackTrace = new StackTraceElement[0]; public CrashReportCategory(CrashReport report, String name) { this.crashReport = report; this.name = name; } public static String getCoordinateInfo(double x, double y, double z) { return String.format("%.2f,%.2f,%.2f - %s", x, y, z, getCoordinateInfo(new BlockPos(x, y, z))); } public static String getCoordinateInfo(BlockPos pos) { int i = pos.getX(); int j = pos.getY(); int k = pos.getZ(); StringBuilder stringbuilder = new StringBuilder(); try { stringbuilder.append(String.format("World: (%d,%d,%d)", i, j, k)); } catch (Throwable var17) { stringbuilder.append("(Error finding world loc)"); } stringbuilder.append(", "); try { int l = i >> 4; int i1 = k >> 4; int j1 = i & 15; int k1 = j >> 4; int l1 = k & 15; int i2 = l << 4; int j2 = i1 << 4; int k2 = (l + 1 << 4) - 1; int l2 = (i1 + 1 << 4) - 1; stringbuilder.append(String.format("Chunk: (at %d,%d,%d in %d,%d; contains blocks %d,0,%d to %d,255,%d)", j1, k1, l1, l, i1, i2, j2, k2, l2)); } catch (Throwable var16) { stringbuilder.append("(Error finding chunk loc)"); } stringbuilder.append(", "); try { int j3 = i >> 9; int k3 = k >> 9; int l3 = j3 << 5; int i4 = k3 << 5; int j4 = (j3 + 1 << 5) - 1; int k4 = (k3 + 1 << 5) - 1; int l4 = j3 << 9; int i5 = k3 << 9; int j5 = (j3 + 1 << 9) - 1; int i3 = (k3 + 1 << 9) - 1; stringbuilder.append(String.format("Region: (%d,%d; contains chunks %d,%d to %d,%d, blocks %d,0,%d to %d,255,%d)", j3, k3, l3, i4, j4, k4, l4, i5, j5, i3)); } catch (Throwable var15) { stringbuilder.append("(Error finding world loc)"); } return stringbuilder.toString(); } /** * Adds a Crashreport section with the given name with the value set to the result of the given Callable; */ public void addCrashSectionCallable(String sectionName, Callable<String> callable) { try { this.addCrashSection(sectionName, callable.call()); } catch (Throwable throwable) { this.addCrashSectionThrowable(sectionName, throwable); } } /** * Adds a Crashreport section with the given name with the given value (convered .toString()) */ public void addCrashSection(String sectionName, Object value) { this.children.add(new CrashReportCategory.Entry(sectionName, value)); } /** * Adds a Crashreport section with the given name with the given Throwable */ public void addCrashSectionThrowable(String sectionName, Throwable throwable) { this.addCrashSection(sectionName, throwable); } /** * Resets our stack trace according to the current trace, pruning the deepest 3 entries. The parameter indicates * how many additional deepest entries to prune. Returns the number of entries in the resulting pruned stack trace. */ public int getPrunedStackTrace(int size) { StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace(); if (astacktraceelement.length <= 0) { return 0; } else { this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - size]; System.arraycopy(astacktraceelement, 3 + size, this.stackTrace, 0, this.stackTrace.length); return this.stackTrace.length; } } /** * Do the deepest two elements of our saved stack trace match the given elements, in order from the deepest? */ public boolean firstTwoElementsOfStackTraceMatch(StackTraceElement s1, StackTraceElement s2) { if (this.stackTrace.length != 0 && s1 != null) { StackTraceElement stacktraceelement = this.stackTrace[0]; if (stacktraceelement.isNativeMethod() == s1.isNativeMethod() && stacktraceelement.getClassName().equals(s1.getClassName()) && stacktraceelement.getFileName().equals(s1.getFileName()) && stacktraceelement.getMethodName().equals(s1.getMethodName())) { if (s2 != null != this.stackTrace.length > 1) { return false; } else if (s2 != null && !this.stackTrace[1].equals(s2)) { return false; } else { this.stackTrace[0] = s1; return true; } } else { return false; } } else { return false; } } /** * Removes the given number entries from the bottom of the stack trace. */ public void trimStackTraceEntriesFromBottom(int amount) { StackTraceElement[] astacktraceelement = new StackTraceElement[this.stackTrace.length - amount]; System.arraycopy(this.stackTrace, 0, astacktraceelement, 0, astacktraceelement.length); this.stackTrace = astacktraceelement; } public void appendToStringBuilder(StringBuilder builder) { builder.append("-- ").append(this.name).append(" --\n"); builder.append("Details:"); for (CrashReportCategory.Entry crashreportcategory$entry : this.children) { builder.append("\n\t"); builder.append(crashreportcategory$entry.getKey()); builder.append(": "); builder.append(crashreportcategory$entry.getValue()); } if (this.stackTrace != null && this.stackTrace.length > 0) { builder.append("\nStacktrace:"); for (StackTraceElement stacktraceelement : this.stackTrace) { builder.append("\n\tat "); builder.append(stacktraceelement.toString()); } } } public StackTraceElement[] getStackTrace() { return this.stackTrace; } public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final Block blockIn, final int blockData) { final int i = Block.getIdFromBlock(blockIn); category.addCrashSectionCallable("Block type", new Callable<String>() { public String call() throws Exception { try { return String.format("ID #%d (%s // %s)", i, blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName()); } catch (Throwable var2) { return "ID #" + i; } } }); category.addCrashSectionCallable("Block data value", new Callable<String>() { public String call() throws Exception { if (blockData < 0) { return "Unknown? (Got " + blockData + ")"; } else { String s = String.format("%4s", Integer.toBinaryString(blockData)).replace(" ", "0"); return String.format("%1$d / 0x%1$X / 0b%2$s", blockData, s); } } }); category.addCrashSectionCallable("Block location", new Callable<String>() { public String call() throws Exception { return CrashReportCategory.getCoordinateInfo(pos); } }); } public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final IBlockState state) { category.addCrashSectionCallable("Block", new Callable<String>() { public String call() throws Exception { return state.toString(); } }); category.addCrashSectionCallable("Block location", new Callable<String>() { public String call() throws Exception { return CrashReportCategory.getCoordinateInfo(pos); } }); } static class Entry { private final String key; private final String value; public Entry(String key, Object value) { this.key = key; if (value == null) { this.value = "~~NULL~~"; } else if (value instanceof Throwable) { Throwable throwable = (Throwable)value; this.value = "~~ERROR~~ " + throwable.getClass().getSimpleName() + ": " + throwable.getMessage(); } else { this.value = value.toString(); } } public String getKey() { return this.key; } public String getValue() { return this.value; } } }
/* * Copyright (c) 2017 VEERA SYSTEM * * 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.veerasystem.crust.login; import dagger.Module; import dagger.Provides; @Module public class LoginPresenterModule { private final LoginContract.View mView; public LoginPresenterModule(LoginContract.View view) { mView = view; } @Provides LoginContract.View provideLoginContractView() { return mView; } }
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.profiler.modifier.connector.httpclient4; import java.security.ProtectionDomain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.navercorp.pinpoint.bootstrap.Agent; import com.navercorp.pinpoint.bootstrap.instrument.ByteCodeInstrumentor; import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass; import com.navercorp.pinpoint.bootstrap.instrument.InstrumentException; import com.navercorp.pinpoint.bootstrap.interceptor.Interceptor; import com.navercorp.pinpoint.profiler.modifier.AbstractModifier; /** * * @author netspider * */ @Deprecated public class InternalHttpAsyncClientModifier extends AbstractModifier { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public InternalHttpAsyncClientModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) { super(byteCodeInstrumentor, agent); } @Override public String getTargetClass() { return "org/apache/http/impl/nio/client/InternalHttpAsyncClient"; } @Override public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) { if (logger.isInfoEnabled()) { logger.info("Modifing. {} @ {}", javassistClassName, classLoader); } try { InstrumentClass aClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer); Interceptor internalExecuteInterceptor = byteCodeInstrumentor.newInterceptor(classLoader, protectedDomain, "com.navercorp.pinpoint.profiler.modifier.connector.httpclient4.interceptor.AsyncInternalClientExecuteInterceptor"); String[] internalExecuteParams = new String[] { "org.apache.http.nio.protocol.HttpAsyncRequestProducer", "org.apache.http.nio.protocol.HttpAsyncResponseConsumer", "org.apache.http.protocol.HttpContext", "org.apache.http.concurrent.FutureCallback" }; aClass.addInterceptor("execute", internalExecuteParams, internalExecuteInterceptor); return aClass.toBytecode(); } catch (InstrumentException e) { logger.info("modify fail. Cause:{}", e.getMessage(), e); return null; } } }
package Lexers;/* The following code was generated by JFlex 1.6.1 */ import com.intellij.openapi.options.SchemeImportException; import java.awt.*; /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.6.1 * from the specification file <tt>resources/configlexer.flex</tt> */ public class ConfigColorsLexer implements ColorsLexer { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; public static final int COLORS = 2; public static final int READINGMODE = 4; public static final int CURSORMODE = 6; public static final int BGMODE = 8; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\6\1\5\1\0\1\6\1\4\22\0\1\16\1\0\1\10"+ "\1\7\14\0\12\3\1\36\2\0\1\17\35\0\1\1\1\0\1\2"+ "\1\0\1\31\1\0\1\12\1\20\1\21\1\30\1\14\1\32\1\23"+ "\1\0\1\34\1\0\1\22\1\13\1\35\1\27\1\25\1\11\1\0"+ "\1\24\1\33\1\15\1\26\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uff9a\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\5\0\2\1\2\2\4\1\1\3\1\1\1\4\1\5"+ "\17\0\1\2\20\0\1\6\12\0\1\7\10\0\1\10"+ "\25\0\1\11\10\0\1\12\1\0\1\13\1\14"; private static int [] zzUnpackAction() { int [] result = new int[104]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\37\0\76\0\135\0\174\0\233\0\272\0\331"+ "\0\233\0\370\0\u0117\0\u0136\0\u0155\0\233\0\u0174\0\233"+ "\0\233\0\u0193\0\u01b2\0\u01d1\0\u01f0\0\u020f\0\u022e\0\u024d"+ "\0\u026c\0\u028b\0\u02aa\0\u02c9\0\u02e8\0\u0307\0\u0326\0\u0345"+ "\0\u0364\0\u0383\0\u03a2\0\u03c1\0\u03e0\0\u03ff\0\u041e\0\u043d"+ "\0\u045c\0\u047b\0\u049a\0\u04b9\0\u04d8\0\u04f7\0\u0516\0\u0535"+ "\0\u0554\0\233\0\u0573\0\u0592\0\u05b1\0\u05d0\0\u05ef\0\u060e"+ "\0\u062d\0\u064c\0\u066b\0\u068a\0\233\0\u06a9\0\u06c8\0\u06e7"+ "\0\u0706\0\u0725\0\u0744\0\u0763\0\u0782\0\233\0\u07a1\0\u07c0"+ "\0\u07df\0\u07fe\0\u081d\0\u083c\0\u085b\0\u087a\0\u0899\0\u08b8"+ "\0\u08d7\0\u08f6\0\u0915\0\u0934\0\u0953\0\u0972\0\u0991\0\u09b0"+ "\0\u09cf\0\u09ee\0\u0a0d\0\233\0\u0a2c\0\u0a4b\0\u0a6a\0\u0a89"+ "\0\u0aa8\0\u0ac7\0\u0ae6\0\u0b05\0\233\0\u0b24\0\233\0\233"; private static int [] zzUnpackRowMap() { int [] result = new int[104]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\6\1\7\2\6\1\10\2\11\2\6\1\12\4\6"+ "\1\11\1\6\1\13\1\14\10\6\1\15\4\6\7\0"+ "\1\16\27\0\3\6\1\17\4\6\1\20\1\6\1\17"+ "\1\6\1\17\3\6\2\17\6\6\1\17\1\6\1\17"+ "\3\6\1\21\7\0\1\22\27\0\4\11\1\10\32\11"+ "\40\0\1\23\42\0\1\11\43\0\1\24\36\0\1\25"+ "\52\0\1\26\35\0\1\27\14\0\1\30\6\0\1\30"+ "\1\0\1\30\3\0\2\30\6\0\1\30\1\0\1\30"+ "\7\0\1\31\6\0\1\31\1\0\1\31\3\0\2\31"+ "\6\0\1\31\1\0\1\31\4\0\2\23\1\32\34\23"+ "\13\0\1\33\44\0\1\34\41\0\1\35\36\0\1\36"+ "\15\0\1\37\6\0\1\37\1\0\1\37\3\0\2\37"+ "\6\0\1\37\1\0\1\37\7\0\1\40\6\0\1\40"+ "\1\0\1\40\3\0\2\40\6\0\1\40\1\0\1\40"+ "\4\0\2\23\1\41\34\23\14\0\1\42\44\0\1\43"+ "\47\0\1\44\17\0\1\45\25\0\1\46\6\0\1\46"+ "\1\0\1\46\3\0\2\46\6\0\1\46\1\0\1\46"+ "\7\0\1\47\6\0\1\47\1\0\1\47\3\0\2\47"+ "\6\0\1\47\1\0\1\47\6\0\1\11\51\0\1\50"+ "\44\0\1\51\40\0\1\52\34\0\1\53\16\0\1\54"+ "\6\0\1\54\1\0\1\54\3\0\2\54\6\0\1\54"+ "\1\0\1\54\7\0\1\55\6\0\1\55\1\0\1\55"+ "\3\0\2\55\6\0\1\55\1\0\1\55\21\0\1\56"+ "\45\0\1\57\36\0\1\60\36\0\1\61\15\0\1\62"+ "\6\0\1\62\1\0\1\62\3\0\2\62\6\0\1\62"+ "\1\0\1\62\7\0\1\63\6\0\1\63\1\0\1\63"+ "\3\0\2\63\6\0\1\63\1\0\1\63\20\0\1\64"+ "\47\0\1\65\42\0\1\66\32\0\1\67\14\0\1\70"+ "\6\0\1\70\1\0\1\70\3\0\2\70\6\0\1\70"+ "\1\0\1\70\22\0\1\71\46\0\1\72\31\0\1\73"+ "\43\0\1\74\20\0\1\75\45\0\1\76\46\0\1\77"+ "\34\0\1\100\40\0\1\101\25\0\1\102\50\0\1\103"+ "\21\0\1\104\53\0\1\105\16\0\1\106\57\0\1\107"+ "\32\0\1\110\42\0\1\111\26\0\1\112\12\0\1\113"+ "\26\0\1\114\33\0\1\115\42\0\1\116\46\0\1\117"+ "\17\0\1\120\45\0\1\121\24\0\1\122\35\0\1\123"+ "\43\0\1\124\32\0\1\125\50\0\1\126\34\0\1\127"+ "\31\0\1\130\45\0\1\131\35\0\1\132\26\0\1\133"+ "\32\0\1\134\52\0\1\135\30\0\1\136\36\0\1\137"+ "\36\0\1\140\37\0\1\141\36\0\1\142\36\0\1\143"+ "\35\0\1\144\36\0\1\145\36\0\1\146\30\0\1\147"+ "\36\0\1\150\26\0"; private static int [] zzUnpackTrans() { int [] result = new int[2883]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unknown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\5\0\1\11\2\1\1\11\4\1\1\11\1\1\2\11"+ "\17\0\1\1\20\0\1\11\12\0\1\11\10\0\1\11"+ "\25\0\1\11\10\0\1\11\1\0\2\11"; private static int [] zzUnpackAttribute() { int [] result = new int[104]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** number of newlines encountered up to the start of the matched text */ private int yyline; /** the number of characters up to the start of the matched text */ private int yychar; /** * the number of characters from the last newline up to the start of the * matched text */ private int yycolumn; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /** * The number of occupied positions in zzBuffer beyond zzEndRead. * When a lead/high surrogate has been read from the input stream * into the final zzBuffer position, this will have a value of 1; * otherwise, it will have a value of 0. */ private int zzFinalHighSurrogate = 0; /* user code: */ String colorString; int color; String colorIdentifier = null; boolean hexFound = false; int ansiAmount = 0; boolean ansiFound = false; boolean backgroundFound = false; boolean foregroundFound = false; /** * Creates a new scanner * * @param in the java.io.Reader to read input from. */ public ConfigColorsLexer(java.io.Reader in) { this.zzReader = in; } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x110000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 122) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { zzEndRead += zzFinalHighSurrogate; zzFinalHighSurrogate = 0; System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) { /* if not: blow it up */ char newBuffer[] = new char[zzBuffer.length*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; zzEndRead += zzFinalHighSurrogate; zzFinalHighSurrogate = 0; } /* fill the buffer with new input */ int requested = zzBuffer.length - zzEndRead; int numRead = zzReader.read(zzBuffer, zzEndRead, requested); /* not supposed to occur according to specification of java.io.Reader */ if (numRead == 0) { throw new java.io.IOException("Reader returned 0 characters. See JFlex examples for workaround."); } if (numRead > 0) { zzEndRead += numRead; /* If numRead == requested, we might have requested to few chars to encode a full Unicode character. We assume that a Reader would otherwise never return half characters. */ if (numRead == requested) { if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) { --zzEndRead; zzFinalHighSurrogate = 1; } } /* potentially more input available */ return false; } /* numRead < 0 ==> end of stream */ return true; } /** * Closes the input stream. */ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ if (zzReader != null) zzReader.close(); } /** * Resets the scanner to read from a new input stream. * Does not close the old reader. * * All internal variables are reset, the old input stream * <b>cannot</b> be reused (internal buffer is discarded and lost). * Lexical state is set to <tt>ZZ_INITIAL</tt>. * * Internal scan buffer is resized down to its initial length, if it has grown. * * @param reader the new input stream */ public final void yyreset(java.io.Reader reader) { zzReader = reader; zzAtBOL = true; zzAtEOF = false; zzEOFDone = false; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; zzFinalHighSurrogate = 0; yyline = yychar = yycolumn = 0; zzLexicalState = YYINITIAL; if (zzBuffer.length > ZZ_BUFFERSIZE) zzBuffer = new char[ZZ_BUFFERSIZE]; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final String yytext() { return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer[zzStartRead+pos]; } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public ColorType yylex() throws java.io.IOException, SchemeImportException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; // set up zzAction for empty match case: int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; } zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) { zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL); zzCurrentPosL += Character.charCount(zzInput); } else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL); zzCurrentPosL += Character.charCount(zzInput); } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; switch (zzLexicalState) { case YYINITIAL: { if (!ansiFound || !backgroundFound || !foregroundFound) throw new SchemeImportException("Scheme is not valid"); return null; } case 105: break; case BGMODE: { if (!ansiFound || !backgroundFound || !foregroundFound) throw new SchemeImportException("Scheme is not valid"); return null; } case 106: break; default: return null; } } else { switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 1: { throw new SchemeImportException("Scheme is not valid"); } case 13: break; case 2: { /* ignore */ } case 14: break; case 3: { yybegin(READINGMODE); } case 15: break; case 4: { if (!hexFound) {throw new SchemeImportException("Scheme is not valid");} if (colorIdentifier == "ANSI" && ansiAmount == 15) {ansiFound = true; colorString = ColorType.ANSI[ansiAmount];} else if (colorIdentifier == "BACKGROUND") {backgroundFound = true; colorString = ColorType.BACKGROUND;} else if (colorIdentifier == "FOREGROUND") {foregroundFound = true; colorString = ColorType.FOREGROUND;} else throw new SchemeImportException("Scheme is not valid"); colorIdentifier = null; hexFound = false; yybegin(YYINITIAL); return new ColorType(colorString, new Color(color)); } case 16: break; case 5: { if (!hexFound) {throw new SchemeImportException("Scheme is not valid");} yybegin(COLORS); if (colorIdentifier == "ANSI") { colorString = ColorType.ANSI[ansiAmount]; ansiAmount++; } else throw new SchemeImportException("Scheme is not valid"); hexFound = false; return new ColorType(colorString, new Color(color)); } case 17: break; case 6: { if (!hexFound) { color = Integer.parseInt(yytext().toString(),16); hexFound = true; } else throw new SchemeImportException("Scheme is not valid"); } case 18: break; case 7: { yybegin(YYINITIAL); } case 19: break; case 8: { colorIdentifier = "ANSI"; yybegin(COLORS); } case 20: break; case 9: { yybegin(CURSORMODE); } case 21: break; case 10: { yybegin(BGMODE); } case 22: break; case 11: { colorIdentifier = "BACKGROUND"; yybegin(COLORS); } case 23: break; case 12: { colorIdentifier = "FOREGROUND"; yybegin(COLORS); } case 24: break; default: zzScanError(ZZ_NO_MATCH); } } } } }
/* * Copyright © 2004-2010 Ralf Sippl <ralf.sippl@gmail.com> * Copyright © 2008-2010 Ben Stock <bs.stock+jswiff@gmail.com> * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "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 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of the copyright holders. * */ package com.jswiff.swfrecords; import com.jswiff.io.OutputBitStream; import java.io.IOException; import java.io.Serializable; /** * Base class for colors. * * @see RGB * @see RGBA */ public abstract class Color implements Serializable { /** * Writes the instance to a bit stream. * * @param stream target bit stream * * @throws IOException if an I/O error has occured */ public abstract void write(OutputBitStream stream) throws IOException; }
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package io.ballerina.messaging.broker.core.rest.model; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.validation.Valid; import javax.validation.constraints.NotNull; public class ScopeUpdateRequest { private @Valid List<String> userGroups = new ArrayList<String>(); /** * Set of user groups for a scope **/ public ScopeUpdateRequest userGroups(List<String> userGroups) { this.userGroups = userGroups; return this; } @ApiModelProperty(required = true, value = "Set of user groups for a scope") @JsonProperty("userGroups") @NotNull public List<String> getUserGroups() { return userGroups; } public void setUserGroups(List<String> userGroups) { this.userGroups = userGroups; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScopeUpdateRequest scopeUpdateRequest = (ScopeUpdateRequest) o; return Objects.equals(userGroups, scopeUpdateRequest.userGroups); } @Override public int hashCode() { return Objects.hash(userGroups); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ScopeUpdateRequest {\n"); sb.append(" userGroups: ").append(toIndentedString(userGroups)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/*---------------------------------------------------------------- * Copyright (c) ThoughtWorks, Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE.txt in the project root for license information. *----------------------------------------------------------------*/ package com.thoughtworks.gauge; import gauge.messages.Spec; import java.util.ArrayList; import java.util.List; import static com.thoughtworks.gauge.Gauge.getScreenshots; public class ScreenshotCollector { public Spec.ProtoExecutionResult addPendingScreenshotTo(Spec.ProtoExecutionResult result) { ArrayList<String> screenshots = getAllPendingScreenshots(); return addPendingScreenshot(result, screenshots); } Spec.ProtoExecutionResult addPendingScreenshot(Spec.ProtoExecutionResult result, List<String> screenshotsFileName) { Spec.ProtoExecutionResult.Builder builder = Spec.ProtoExecutionResult.newBuilder(result); builder.addAllScreenshotFiles(screenshotsFileName); return builder.build(); } private ArrayList<String> getAllPendingScreenshots() { ArrayList<String> pendingScreenshots = new ArrayList<>(getScreenshots()); clear(); return pendingScreenshots; } private void clear() { getScreenshots().clear(); } }
package com.subrosa.api.actions.list; /** * Interface for a class that takes query criteria and produces a runnable query. * * @param <T> type of model object for which query is searching * @param <Q> type of query */ public interface QueryBuilder<T, Q, C> { /** * Generate a query for the given criteria. * * @param criteria query criteria * @return runnable query */ Q getQuery(QueryCriteria<T> criteria); /** * Generate a query for counting total resulst matching criteria. * @param criteria query criteria * @return runnable query */ C countQuery(QueryCriteria<T> criteria); }
package org.sunbird.graph.service.operation; import com.mashape.unirest.http.JsonNode; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.sunbird.common.dto.Request; import org.sunbird.common.exception.ClientException; import org.sunbird.common.exception.ResourceNotFoundException; import org.sunbird.common.exception.ServerException; import org.sunbird.graph.dac.model.Node; import org.sunbird.test.BaseTest; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionException; public class NodeAsyncOperationsTest extends BaseTest { @BeforeClass public static void setUp() { graphDb.execute("UNWIND [{nodeId:'do_000000123', name: 'Test Node'}] as row with row.nodeId as Id CREATE (n:domain{IL_UNIQUE_ID:Id});"); } @Test public void testSetPrimitiveData() throws Exception { Method method = NodeAsyncOperations.class.getDeclaredMethod("setPrimitiveData", Map.class); method.setAccessible(true); Map<String, Object> metadata = new HashMap<String, Object>() {{ put("testMap", new HashMap<String, Object>() {{ put("name", "test"); put("identifier", "123"); }}); put("list", new ArrayList<Map<String, Object>>() {{ add(new HashMap<String, Object>(){{ put("identifier","123"); }}); add(new HashMap<String, Object>(){{ put("identifier","234"); }}); }}); }}; Map<String, Object> result = (Map<String, Object>) method.invoke(NodeAsyncOperations.class, metadata); Assert.assertNotNull(result); Assert.assertEquals("{\"identifier\":\"123\",\"name\":\"test\"}", result.get("testMap")); } @Test public void testUpdateNodes() throws Exception { createBulkNodes(); List<String> ids = Arrays.asList("do_0000123", "do_0000234"); Map<String, Object> data = new HashMap<String, Object>() {{ put("status", "Review"); }}; Future<Map<String, Node>> resultFuture = NodeAsyncOperations.updateNodes("domain",ids, data); Map<String, Node> result = Await.result(resultFuture, Duration.apply("30s")); Assert.assertTrue(result.size()==2); } @Test(expected = ClientException.class) public void testUpdateNodesWithEmptyGraphId() throws Exception { List<String> ids = Arrays.asList("do_0000123", "do_0000234"); Map<String, Object> data = new HashMap<String, Object>() {{ put("status", "Review"); }}; Future<Map<String, Node>> resultFuture = NodeAsyncOperations.updateNodes(null,ids, data); Map<String, Node> result = Await.result(resultFuture, Duration.apply("30s")); } @Test(expected = ClientException.class) public void testUpdateNodesWithEmptyIdentifiers() throws Exception { Map<String, Object> data = new HashMap<String, Object>() {{ put("status", "Review"); }}; Future<Map<String, Node>> resultFuture = NodeAsyncOperations.updateNodes("domain", new ArrayList<String>(), data); Map<String, Node> result = Await.result(resultFuture, Duration.apply("30s")); } @Test(expected = ClientException.class) public void testUpdateNodesWithEmptyMetadata() throws Exception { List<String> ids = Arrays.asList("do_0000123", "do_0000234"); Future<Map<String, Node>> resultFuture = NodeAsyncOperations.updateNodes("domain", ids, new HashMap<String, Object>()); Map<String, Node> result = Await.result(resultFuture, Duration.apply("30s")); } @Test public void testAddNode() throws Exception { Node node = new Node("domain","DATA_NODE","Content"); node.setIdentifier("do_000000111"); node.setMetadata(new HashMap<String, Object>(){{put("status","Draft");}}); Future<Node> resultFuture = NodeAsyncOperations.addNode("graphId",node); Node result = Await.result(resultFuture, Duration.apply("30s")); Assert.assertTrue(null!=node); Assert.assertEquals("do_000000111",result.getIdentifier()); } @Test(expected = ClientException.class) public void testAddNodeWithEmptyGrpahId() throws Exception { Node node = new Node("domain","DATA_NODE","Content"); node.setIdentifier("do_000000112"); node.setMetadata(new HashMap<String, Object>(){{put("status","Draft");}}); Future<Node> resultFuture = NodeAsyncOperations.addNode(null, node); Node result = Await.result(resultFuture, Duration.apply("30s")); } @Test(expected = ClientException.class) public void testAddNodeWithNullNode() throws Exception { Future<Node> resultFuture = NodeAsyncOperations.addNode("domain", null); Node result = Await.result(resultFuture, Duration.apply("30s")); } @Test public void testUpsertRootNode() throws Exception { Future<Node> resultFuture = NodeAsyncOperations.upsertRootNode("domain", new Request()); Node result = Await.result(resultFuture, Duration.apply("30s")); Assert.assertNotNull(result.getIdentifier()); Assert.assertEquals("do_ROOT_NODE", result.getIdentifier()); Assert.assertEquals("ROOT_NODE", result.getNodeType()); } @Test public void testDeleteWithValidID() throws Exception { Future<Boolean> resultFuture2 = NodeAsyncOperations.deleteNode("domain", "do_000000123", new Request()); Assert.assertTrue(Await.result(resultFuture2, Duration.apply("30s"))); } @Test public void testDeleteWithInvalidId() throws Exception { Future<Boolean> resultFuture2 = NodeAsyncOperations.deleteNode("domain", "do_000000123_invalid", new Request()); try { Await.result(resultFuture2, Duration.apply("30s")); } catch (CompletionException e) { Assert.assertTrue(e.getCause() instanceof ResourceNotFoundException); } } @Test(expected = ClientException.class) public void testDeleteWithEmptyId() throws Exception { Future<Boolean> resultFuture2 = NodeAsyncOperations.deleteNode("domain", " ", new Request()); Await.result(resultFuture2, Duration.apply("30s")); } @Test(expected = ClientException.class) public void testDeleteWithEmptyGraphId() throws Exception { Future<Boolean> resultFuture2 = NodeAsyncOperations.deleteNode("", "do_1234 ", new Request()); Await.result(resultFuture2, Duration.apply("30s")); } @Test(expected = ServerException.class ) public void testAddNodeNeo4jException() throws Exception { Node node = getNode(); node.getMetadata().put("originData", new JsonNode("{\n" + " \"name\": \"TB-001\",\n" + " \"copyType\": \"deep\",\n" + " \"license\": \"CC BY-NC 4.0\",\n" + " \"author\": \"b00bc992ef25f1a9a8d63291e20efc8d\"\n" + " }")); Future<Node> resultFuture = NodeAsyncOperations.addNode("graphId", node); Await.result(resultFuture, Duration.apply("30s")); } @Test(expected = ServerException.class ) public void testUpsertNodeNeo4jException() throws Exception { Node node = getNode(); node.getMetadata().put("originData", new JsonNode("{\n" + " \"name\": \"TB-001\",\n" + " \"copyType\": \"deep\",\n" + " \"license\": \"CC BY-NC 4.0\",\n" + " \"author\": \"b00bc992ef25f1a9a8d63291e20efc8d\"\n" + " }")); Future<Node> resultFuture = NodeAsyncOperations.upsertNode("graphId", node, new Request()); Await.result(resultFuture, Duration.apply("30s")); } private Node getNode() throws Exception { Node node = new Node("domain", "DATA_NODE", "Content"); node.setIdentifier("do_000000123"); node.setMetadata(new HashMap<String, Object>() {{ put("status", "Draft"); put("name", "Test Node"); put("identifier", "do_000000123"); }}); return node; } }
package abi14_0_0.host.exp.exponent.modules.api.components; import abi14_0_0.com.facebook.react.bridge.ReadableMap; import abi14_0_0.com.facebook.react.common.MapBuilder; import abi14_0_0.com.facebook.react.uimanager.annotations.ReactProp; import abi14_0_0.com.facebook.react.uimanager.SimpleViewManager; import abi14_0_0.com.facebook.react.uimanager.ThemedReactContext; import com.yqritc.scalablevideoview.ScalableType; import abi14_0_0.host.exp.exponent.modules.api.components.VideoView.Events; import javax.annotation.Nullable; import java.util.Map; public class VideoViewManager extends SimpleViewManager<VideoView> { public static final String REACT_CLASS = "ExponentVideo"; public static final String PROP_SRC = "src"; public static final String PROP_SRC_URI = "uri"; public static final String PROP_SRC_TYPE = "type"; public static final String PROP_SRC_IS_NETWORK = "isNetwork"; public static final String PROP_SRC_IS_ASSET = "isAsset"; public static final String PROP_RESIZE_MODE = "resizeMode"; public static final String PROP_REPEAT = "repeat"; public static final String PROP_PAUSED = "paused"; public static final String PROP_MUTED = "muted"; public static final String PROP_VOLUME = "volume"; public static final String PROP_SEEK = "seek"; public static final String PROP_RATE = "rate"; @Override public String getName() { return REACT_CLASS; } @Override protected VideoView createViewInstance(ThemedReactContext themedReactContext) { return new VideoView(themedReactContext); } @Override @Nullable public Map getExportedCustomDirectEventTypeConstants() { MapBuilder.Builder builder = MapBuilder.builder(); for (Events event : Events.values()) { builder.put(event.toString(), MapBuilder.of("registrationName", event.toString())); } return builder.build(); } @Override @Nullable public Map getExportedViewConstants() { return MapBuilder.of( "ScaleNone", Integer.toString(ScalableType.LEFT_TOP.ordinal()), "ScaleToFill", Integer.toString(ScalableType.FIT_XY.ordinal()), "ScaleAspectFit", Integer.toString(ScalableType.FIT_CENTER.ordinal()), "ScaleAspectFill", Integer.toString(ScalableType.CENTER_CROP.ordinal()) ); } @ReactProp(name = PROP_SRC) public void setSrc(final VideoView videoView, @Nullable ReadableMap src) { videoView.setSrc( src.getString(PROP_SRC_URI), src.getString(PROP_SRC_TYPE), src.getBoolean(PROP_SRC_IS_NETWORK), src.getBoolean(PROP_SRC_IS_ASSET) ); } @ReactProp(name = PROP_RESIZE_MODE) public void setResizeMode(final VideoView videoView, final String resizeModeOrdinalString) { videoView.setResizeModeModifier(ScalableType.values()[Integer.parseInt(resizeModeOrdinalString)]); } @ReactProp(name = PROP_REPEAT, defaultBoolean = false) public void setRepeat(final VideoView videoView, final boolean repeat) { videoView.setRepeatModifier(repeat); } @ReactProp(name = PROP_PAUSED, defaultBoolean = false) public void setPaused(final VideoView videoView, final boolean paused) { videoView.setPausedModifier(paused); } @ReactProp(name = PROP_MUTED, defaultBoolean = false) public void setMuted(final VideoView videoView, final boolean muted) { videoView.setMutedModifier(muted); } @ReactProp(name = PROP_VOLUME, defaultFloat = 1.0f) public void setVolume(final VideoView videoView, final float volume) { videoView.setVolumeModifier(volume); } @ReactProp(name = PROP_SEEK) public void setSeek(final VideoView videoView, final float seek) { videoView.seekTo(Math.round(seek * 1000.0f)); } @ReactProp(name = PROP_RATE) public void setRate(final VideoView videoView, final float rate) { videoView.setRateModifier(rate); } }
package com.hz.design.nullobject.test; import com.hz.design.nullobject.AbstractCustomer; import com.hz.design.nullobject.CustomerFactory; /** * 测试 空对象模式 * * Created by hezhao on 2018-08-08 16:01 */ public class TestNullObject { public static void main(String[] args) { AbstractCustomer customer1 = CustomerFactory.getCustomer("Rob"); AbstractCustomer customer2 = CustomerFactory.getCustomer("Bob"); AbstractCustomer customer3 = CustomerFactory.getCustomer("Julie"); AbstractCustomer customer4 = CustomerFactory.getCustomer("Laura"); System.out.println("================Customers================"); System.out.println(customer1.getName() + " : " + customer1.isNil()); System.out.println(customer2.getName() + " : " + customer2.isNil()); System.out.println(customer3.getName() + " : " + customer3.isNil()); System.out.println(customer4.getName() + " : " + customer4.isNil()); } }
package edu.gemini.auxfile.server.file; import java.io.File; import java.io.IOException; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.logging.Level; import java.util.logging.Logger; import edu.gemini.auxfile.api.AuxFileException; import edu.gemini.shared.util.immutable.ImOption; import edu.gemini.shared.util.immutable.Option; import edu.gemini.spModel.core.SPProgramID; import edu.gemini.spModel.pio.ParamSet; import edu.gemini.spModel.pio.Pio; import edu.gemini.spModel.pio.PioFactory; import edu.gemini.spModel.pio.xml.PioXmlException; import edu.gemini.spModel.pio.xml.PioXmlFactory; import edu.gemini.spModel.pio.xml.PioXmlUtil; public class MetaData { private static final Logger LOGGER = Logger.getLogger(MetaData.class.getName()); private static final String PROP_ROOT = "meta"; private static final String PROP_DESCRIPTION = "description"; private static final String PROP_CHECKED = "checked"; private static final String PROP_LAST_EMAILED = "lastEmailed"; private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ISO_INSTANT; private final File xml; private String description; private boolean checked; private Option<Instant> lastEmailed; @SuppressWarnings("deprecation") public static MetaData forFile(SPProgramID progId, String fileName) throws IOException, AuxFileException { // Make sure the dirs exist. FileManager.instance().initProgramDir(progId); final File xml = FileManager.instance().getMetaFile(progId, fileName); final MetaData md = new MetaData(xml); // If this is a new MetaData for this auxfile, copy the legacy description if // there is one, and delete the legacy description dir/file. Do this here since // we don't pass the progId/fileName info to the ctor. if (!xml.exists()) { // Previous versions had the description in its own file. final String DESC_DIR = "desc"; final String DESC_SUFFIX = ".desc"; final FileManager r = FileManager.instance(); final File ddir = new File(r.getProgramDir(progId), DESC_DIR); final File dfile = new File(ddir, fileName + DESC_SUFFIX); if (dfile.exists()) { LOGGER.info("Migrating legacy description file for " + fileName + " (" + progId + ")"); md.setDescription(FileUtil.readString(dfile)); dfile.delete(); // do this last in case the md update fails } } return md; } private MetaData(File xml) throws IOException { this.xml = xml; this.description = ""; this.checked = false; this.lastEmailed = ImOption.empty(); read(); } public boolean isChecked() { return checked; } public void setChecked(boolean checked) throws IOException { this.checked = checked; store(); } public Option<Instant> getLastEmailed() { return lastEmailed; } public void setLastEmailed(Option<Instant> lastEmailed) throws IOException { this.lastEmailed = lastEmailed; store(); } public String getDescription() { return description; } public void setDescription(String description) throws IOException { this.description = description; store(); } private void store() throws IOException { // Create the PIO XML document. final PioFactory factory = new PioXmlFactory(); final ParamSet node = factory.createParamSet(PROP_ROOT); // Set the metadata properties Pio.addBooleanParam(factory, node, PROP_CHECKED, checked); Pio.addParam(factory, node, PROP_DESCRIPTION, description); lastEmailed.foreach(t -> Pio.addParam(factory, node, PROP_LAST_EMAILED, TIME_FORMAT.format(t))); // And write out the file. try { PioXmlUtil.write(node, xml); } catch (PioXmlException pxe) { LOGGER.log(Level.SEVERE, "Trouble storing meta", pxe); IOException ioe = new IOException(pxe.getMessage()); ioe.initCause(pxe); throw ioe; } } private void read() throws IOException { if (!xml.exists()) return; try { // Read the PIO XML document. ParamSet node = (ParamSet) PioXmlUtil.read(xml); // Get the metadata properties checked = Pio.getBooleanValue(node, PROP_CHECKED, false); description = Pio.getValue(node, PROP_DESCRIPTION, null); lastEmailed = ImOption.apply(Pio.getValue(node, PROP_LAST_EMAILED, null)).map(s -> TIME_FORMAT.parse(s, Instant::from) ); } catch (PioXmlException pxe) { LOGGER.log(Level.SEVERE, "Trouble reading meta", pxe); IOException ioe = new IOException(pxe.getMessage()); ioe.initCause(pxe); throw ioe; } catch (DateTimeParseException dtpe) { LOGGER.log(Level.SEVERE, "Trouble reading meta", dtpe); IOException ioe = new IOException("Couldn't parse timestamp"); ioe.initCause(dtpe); throw ioe; } } }
package de.tum.in.www1.artemis.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.persistence.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * A ProgrammingSubmission. */ @Entity @DiscriminatorValue(value = "P") public class ProgrammingSubmission extends Submission implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "commit_hash") private String commitHash; @Column(name = "build_failed") private boolean buildFailed; @Column(name = "build_artifact") private boolean buildArtifact; // Only present if buildFailed == true @OneToMany(mappedBy = "programmingSubmission", cascade = CascadeType.ALL, orphanRemoval = true) @OrderColumn @JsonIgnoreProperties(value = "programmingSubmission", allowSetters = true) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private List<BuildLogEntry> buildLogEntries = new ArrayList<>(); // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public String getCommitHash() { return commitHash; } public ProgrammingSubmission commitHash(String commitHash) { this.commitHash = commitHash; return this; } public void setCommitHash(String commitHash) { this.commitHash = commitHash; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove public boolean isBuildFailed() { return buildFailed; } public void setBuildFailed(boolean buildFailed) { this.buildFailed = buildFailed; } public boolean isBuildArtifact() { return buildArtifact; } public void setBuildArtifact(boolean buildArtifact) { this.buildArtifact = buildArtifact; } public List<BuildLogEntry> getBuildLogEntries() { return buildLogEntries; } public void setBuildLogEntries(List<BuildLogEntry> buildLogEntries) { this.buildLogEntries = buildLogEntries; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ProgrammingSubmission)) return false; if (!super.equals(o)) return false; ProgrammingSubmission that = (ProgrammingSubmission) o; return buildFailed == that.buildFailed && buildArtifact == that.buildArtifact && Objects.equals(commitHash, that.commitHash); } @Override public int hashCode() { return Objects.hash(super.hashCode(), commitHash, buildFailed, buildArtifact); } @Override public String toString() { return "ProgrammingSubmission{" + "commitHash='" + commitHash + '\'' + ", buildFailed=" + buildFailed + ", buildArtifact=" + buildArtifact + '}'; } }
package mage.cards.d; import java.util.UUID; import mage.ObjectColor; import mage.abilities.effects.common.DestroyTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.ColorPredicate; import mage.target.common.TargetCreaturePermanent; /** * * @author BetaSteward_at_googlemail.com */ public final class Deathmark extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("green or white creature"); static { filter.add(Predicates.or( new ColorPredicate(ObjectColor.GREEN), new ColorPredicate(ObjectColor.WHITE))); } public Deathmark(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{B}"); this.getSpellAbility().addTarget(new TargetCreaturePermanent(filter)); this.getSpellAbility().addEffect(new DestroyTargetEffect()); } public Deathmark(final Deathmark card) { super(card); } @Override public Deathmark copy() { return new Deathmark(this); } }
package com.centreon.injector.configuration; import static com.centreon.injector.configuration.EnvParams.INSERTION_ERROR_FILE; import static com.centreon.injector.configuration.EnvParams.INSERTION_ERROR_FILE_DEFAULT; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import com.centreon.injector.error_handling.ErrorFileLogger; /** * Configuration bean for the injector itself */ @Configuration public class InjectorConfiguration { static final private Logger LOGGER = LoggerFactory.getLogger(InjectorConfiguration.class); private final Environment env; public InjectorConfiguration(@Autowired Environment env) { this.env = env; } /** * * Build the {@link com.centreon.injector.error_handling.ErrorFileLogger} singleton. * <br/> * <br/> * Parameters used to build this singleton: * * <ul> * <li>dse.input_error_file</li> * </ul> */ @Bean(destroyMethod = "close") public ErrorFileLogger getErrorFileLogger() { LOGGER.info("Initializing error file"); String errorFile = env.getProperty(INSERTION_ERROR_FILE, INSERTION_ERROR_FILE_DEFAULT); try { return new ErrorFileLogger(errorFile); } catch (IOException e) { LOGGER.error(String.format("Cannot create error file %s", errorFile), e); throw new RuntimeException(e); } } }
package com.cheng.common.enums; /** * 操作人类别 * * @author ruoyi */ public enum OperatorType { /** * 其它 */ OTHER, /** * 后台用户 */ MANAGE, /** * 手机端用户 */ MOBILE }
/* * Copyright 2020 Horstexplorer @ https://www.netbeacon.de * * 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.netbeacon.xenia.backend.client.objects.internal.exceptions; public class CacheException extends RuntimeException{ private final Type type; private Exception exception; public CacheException(Type type, String message){ super(message); this.type = type; } public CacheException(Type type, String message, Exception exception){ super(message, exception); this.type = type; } @Override public String getMessage(){ return "Type: " + type + " Message: " + super.getMessage(); } public Type getType(){ return type; } public Exception getSubException(){ return exception; } public enum Type{ UNKNOWN, NOT_FOUND, ALREADY_EXISTS, IS_FULL } }
package james.medianotification.activities; import android.animation.ArgbEvaluator; import android.animation.ValueAnimator; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.TabLayout; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.AccelerateInterpolator; import james.medianotification.MediaNotification; import james.medianotification.R; import james.medianotification.adapters.SimplePagerAdapter; import james.medianotification.dialogs.AboutDialog; import james.medianotification.fragments.AppsFragment; import james.medianotification.fragments.HelpFragment; import james.medianotification.fragments.SettingsFragment; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = findViewById(R.id.toolbar); tabLayout = findViewById(R.id.tabLayout); viewPager = findViewById(R.id.viewPager); setSupportActionBar(toolbar); tabLayout.setupWithViewPager(viewPager); viewPager.setAdapter(new SimplePagerAdapter(this, viewPager, getSupportFragmentManager(), new SettingsFragment(), new AppsFragment(), new HelpFragment())); new Handler().postDelayed(new Runnable() { @Override public void run() { findViewById(R.id.icon).setVisibility(View.GONE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ValueAnimator animator = ValueAnimator.ofObject(new ArgbEvaluator(), getWindow().getStatusBarColor(), ContextCompat.getColor(MainActivity.this, R.color.colorPrimaryDark)); animator.setInterpolator(new AccelerateInterpolator()); animator.setDuration(500); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) getWindow().setStatusBarColor((int) valueAnimator.getAnimatedValue()); } }); animator.start(); } } }, 3000); } @Override protected void onResume() { super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_github: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/TheAndroidMaster/MediaNotification"))); break; case R.id.action_tutorial: ((MediaNotification) getApplicationContext()).showTutorial(); break; case R.id.action_about: new AboutDialog(this).show(); break; } return super.onOptionsItemSelected(item); } }
package com.example.trainticket_01.presenter; import com.example.cookie_library.interfaces.CallBack; import com.example.trainticket_01.model.bean.UserBean; import com.example.trainticket_01.model.biz.LoginBiz; import com.example.trainticket_01.view.interfaces.ILoginView; /** * Created by maomao on 2019/4/3. * <p> * 登录Presenter */ public class LoginPresenter { private LoginBiz loginBiz; private ILoginView iLoginView; public LoginPresenter(ILoginView iLoginView) { loginBiz = new LoginBiz(); this.iLoginView = iLoginView; } public void doLogin(final UserBean userBean) { loginBiz.doLogin(userBean, new CallBack() { @Override public void onSuccess(Object result) { iLoginView.loginSuccess((UserBean) result); } @Override public void onFailed(Object msg) { iLoginView.loginFailed((String) msg); } }); } }
package com.alipay.rdf.file.type; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.alipay.rdf.file.exception.RdfErrorEnum; import com.alipay.rdf.file.exception.RdfFileException; import com.alipay.rdf.file.meta.FileColumnMeta; import com.alipay.rdf.file.spi.RdfFileColumnTypeSpi; /** * Copyright (C) 2013-2018 Ant Financial Services Group * * 由数字组成的字符串 * * @author hongwei.quhw * @version $Id: DigitalCharType.java, v 0.1 2017年8月19日 下午3:31:17 hongwei.quhw Exp $ */ public class DigitalCharType extends AbstractColumnTypeCodec<String> { private static final Pattern DIGITAL_REG = Pattern.compile("^[0-9]*$"); @Override protected String doDeserialize(String field, FileColumnMeta columnMeta) { check(field, columnMeta); return field; } /** * @see RdfFileColumnTypeSpi.quhw.file.type.ColumnTypeCodec#serialize(java.lang.Object, hongwei.quhw.file.meta.FileColumnMeta) */ @Override public String serialize(String field, FileColumnMeta columnMeta) { String value = super.serialize(field, columnMeta); check(value, columnMeta); return value; } private void check(String field, FileColumnMeta columnMeta) { Matcher match = DIGITAL_REG.matcher(field); if (!match.matches()) { throw new RdfFileException( "rdf-fiel#字段" + columnMeta.getDesc() + "只能是数字字符类型, 实际是" + field, RdfErrorEnum.VALIDATE_ERROR); } } }
package seedu.address.logic.commands; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.logic.commands.CommandTestUtil.showSourceAtIndex; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_SOURCE; import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND_SOURCE; import static seedu.address.testutil.TypicalIndexes.INDEX_THIRD_SOURCE; import static seedu.address.testutil.TypicalSources.getTypicalSourceManager; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.CommandHistory; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; /** * Contains integration tests (interaction with the Model) for {@code SelectCommand}. */ public class SelectCommandTest { private Model model = new ModelManager(getTypicalSourceManager(), new UserPrefs()); private Model expectedModel = new ModelManager(getTypicalSourceManager(), new UserPrefs()); private CommandHistory commandHistory = new CommandHistory(); @Test public void execute_validIndexUnfilteredList_success() { Index lastSourceIndex = Index.fromOneBased(model.getFilteredSourceList().size()); assertExecutionSuccess(INDEX_FIRST_SOURCE); assertExecutionSuccess(INDEX_THIRD_SOURCE); assertExecutionSuccess(lastSourceIndex); } @Test public void execute_invalidIndexUnfilteredList_failure() { Index outOfBoundsIndex = Index.fromOneBased(model.getFilteredSourceList().size() + 1); assertExecutionFailure(outOfBoundsIndex, Messages.MESSAGE_INVALID_SOURCE_DISPLAYED_INDEX); } @Test public void execute_validIndexFilteredList_success() { showSourceAtIndex(model, INDEX_FIRST_SOURCE); showSourceAtIndex(expectedModel, INDEX_FIRST_SOURCE); assertExecutionSuccess(INDEX_FIRST_SOURCE); } @Test public void execute_invalidIndexFilteredList_failure() { showSourceAtIndex(model, INDEX_FIRST_SOURCE); showSourceAtIndex(expectedModel, INDEX_FIRST_SOURCE); Index outOfBoundsIndex = INDEX_SECOND_SOURCE; // ensures that outOfBoundIndex is still in bounds of source manager list assertTrue(outOfBoundsIndex.getZeroBased() < model.getSourceManager().getSourceList().size()); assertExecutionFailure(outOfBoundsIndex, Messages.MESSAGE_INVALID_SOURCE_DISPLAYED_INDEX); } @Test public void equals() { SelectCommand selectFirstCommand = new SelectCommand(INDEX_FIRST_SOURCE); SelectCommand selectSecondCommand = new SelectCommand(INDEX_SECOND_SOURCE); // same object -> returns true assertTrue(selectFirstCommand.equals(selectFirstCommand)); // same values -> returns true SelectCommand selectFirstCommandCopy = new SelectCommand(INDEX_FIRST_SOURCE); assertTrue(selectFirstCommand.equals(selectFirstCommandCopy)); // different types -> returns false assertFalse(selectFirstCommand.equals(1)); // null -> returns false assertFalse(selectFirstCommand.equals(null)); // different source -> returns false assertFalse(selectFirstCommand.equals(selectSecondCommand)); } /** * Executes a {@code SelectCommand} with the given {@code index}, * and checks that the model's selected source is set to the source at {@code index} in the filtered source list. */ private void assertExecutionSuccess(Index index) { SelectCommand selectCommand = new SelectCommand(index); String expectedMessage = String.format(SelectCommand.MESSAGE_SELECT_SOURCE_SUCCESS, index.getOneBased()); expectedModel.setSelectedSource(model.getFilteredSourceList().get(index.getZeroBased())); assertCommandSuccess(selectCommand, model, commandHistory, expectedMessage, expectedModel); } /** * Executes a {@code SelectCommand} with the given {@code index}, and checks that a {@code CommandException} * is thrown with the {@code expectedMessage}. */ private void assertExecutionFailure(Index index, String expectedMessage) { SelectCommand selectCommand = new SelectCommand(index); assertCommandFailure(selectCommand, model, commandHistory, expectedMessage); } }
package it.nextworks.nfvmano.libs.common.enums; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Specifies the scope of the affinity or anti-affinity relationship e.g. a NFVI node, an NFVI PoP, etc. */ public enum ScopeEnum { NFVI_NODE("nfvi-node"), ZONE_GROUP("zone-group"), ZONE("zone"), NFVI_POP("nfvi-pop"); private String value; ScopeEnum(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static ScopeEnum fromValue(String text) { for (ScopeEnum b : ScopeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } }
package com.bkb.metalmusicreviews.backend.api; import com.bkb.metalmusicreviews.backend.dto.AlbumDTO; import com.bkb.metalmusicreviews.backend.entity.Album; import java.util.Base64; import com.bkb.metalmusicreviews.backend.service.interfaces.AlbumServiceInterface; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.List; @RestController @RequestMapping("/api/v1/albums") @CrossOrigin("*") public class AlbumController { private final AlbumServiceInterface albumService; @Autowired public AlbumController(@Qualifier("jpaServiceAlbum") AlbumServiceInterface albumService) { this.albumService = albumService; } @GetMapping("/get_albums_by_username") @PreAuthorize("hasAuthority('review:read')") public List<Album> getAlbumsByUsername(@RequestParam(name = "username") String username){ return albumService.getAlbumsByUsername(username); } @GetMapping("/get_albums_by_band_id_and_username") @PreAuthorize("hasAuthority('review:read')") public List<Album> getAlbumsByBandIdAndUsername( @RequestParam(name = "username") String username, @RequestParam(name = "band_id") int bandId){ return albumService.getAlbumsByBandIdAndUsername(username, bandId); } @GetMapping(path = "/download_album_image") @PreAuthorize("hasAuthority('review:read')") public byte[] downloadAlbumImage(@RequestParam(name = "album_id") int albumId){ byte[] arrayBase64 = Base64.getEncoder().encode(albumService.downloadAlbumImage(albumId)); return arrayBase64; } @PostMapping( path="/upload_album_with_image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) @PreAuthorize("hasAuthority('review:write')") public int uploadAlbum(@RequestPart("album_dto") AlbumDTO albumDTO, @RequestPart("multipart_file") MultipartFile file){ Album album = albumService.findAlbumByAlbumSpotifyId(albumDTO.getAlbumSpotifyId()); if(album == null){ album = albumService.uploadAlbumFile(albumDTO, file); } albumService.addAlbumForThisUser(albumDTO.getUserId(), album.getAlbumId()); return album.getAlbumId(); } //orElse yerine 404 fırtlatman mantıklı olabilir bunu dene. @GetMapping(path = "/get_album_by_album_id") @PreAuthorize("hasAuthority('review:read')") public Album getAlbumById(@RequestParam(name = "album_id") int albumId){ return albumService.getAlbumById(albumId).orElse(null); } @DeleteMapping(path = "/delete_album_by_album_id_for_user") @PreAuthorize("hasAuthority('review:write')") public int deleteAlbumByIdAndUserId(@RequestParam(name = "album_id") int albumId, @RequestParam(name = "user_id") int userId){ return albumService.deleteAlbumByIdAndUserId(albumId, userId); } @GetMapping("/get_album_count_by_username") @PreAuthorize("hasAuthority('review:read')") public int getAlbumCountByUserId(@RequestParam(name = "username") String username){ return albumService.getAlbumCountByUsername(username); } }
/** * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package com.dangdang.ddframe.job.plugin.job.type.dataflow; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.quartz.JobExecutionException; import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext; import com.dangdang.ddframe.job.internal.config.ConfigurationService; import com.dangdang.ddframe.job.internal.execution.ExecutionContextService; import com.dangdang.ddframe.job.internal.execution.ExecutionService; import com.dangdang.ddframe.job.internal.failover.FailoverService; import com.dangdang.ddframe.job.internal.offset.OffsetService; import com.dangdang.ddframe.job.internal.sharding.ShardingService; import com.dangdang.ddframe.job.internal.statistics.ProcessCountStatistics; import com.dangdang.ddframe.job.plugin.job.type.ElasticJobAssert; import com.dangdang.ddframe.job.plugin.job.type.fixture.FooUnstreamingBatchSequenceDataFlowElasticJob; import com.dangdang.ddframe.job.plugin.job.type.fixture.JobCaller; public final class UnstreamingBatchSequenceDataFlowElasticJobTest { @Mock private JobCaller jobCaller; @Mock private ConfigurationService configService; @Mock private ShardingService shardingService; @Mock private ExecutionContextService executionContextService; @Mock private ExecutionService executionService; @Mock private FailoverService failoverService; @Mock private OffsetService offsetService; private FooUnstreamingBatchSequenceDataFlowElasticJob unstreamingBatchSequenceDataFlowElasticJob; private JobExecutionMultipleShardingContext shardingContext; @Before public void setUp() throws NoSuchFieldException { MockitoAnnotations.initMocks(this); when(configService.getJobName()).thenReturn("testJob"); unstreamingBatchSequenceDataFlowElasticJob = new FooUnstreamingBatchSequenceDataFlowElasticJob(jobCaller); unstreamingBatchSequenceDataFlowElasticJob.setConfigService(configService); unstreamingBatchSequenceDataFlowElasticJob.setShardingService(shardingService); unstreamingBatchSequenceDataFlowElasticJob.setExecutionContextService(executionContextService); unstreamingBatchSequenceDataFlowElasticJob.setExecutionService(executionService); unstreamingBatchSequenceDataFlowElasticJob.setFailoverService(failoverService); unstreamingBatchSequenceDataFlowElasticJob.setOffsetService(offsetService); shardingContext = ElasticJobAssert.getShardingContext(); ElasticJobAssert.prepareForIsNotMisfireAndIsNotFailover(configService, executionContextService, executionService, shardingContext); } @After public void tearDown() throws NoSuchFieldException { ProcessCountStatistics.reset(ElasticJobAssert.JOB_NAME); } @Test public void assertExecuteWhenFetchDataIsNullAndEmpty() throws JobExecutionException { when(jobCaller.fetchData(0)).thenReturn(null); when(jobCaller.fetchData(1)).thenReturn(Collections.emptyList()); unstreamingBatchSequenceDataFlowElasticJob.execute(null); verify(jobCaller).fetchData(0); verify(jobCaller).fetchData(1); verify(jobCaller, times(0)).processData(any()); ElasticJobAssert.verifyForIsNotMisfireAndIsNotFailover(configService, shardingService, executionContextService, executionService, failoverService, shardingContext); ElasticJobAssert.assertProcessCountStatistics(0, 0); } @Test public void assertExecuteWhenFetchDataIsNotEmpty() throws JobExecutionException { when(jobCaller.fetchData(0)).thenReturn(Arrays.<Object>asList(1, 2)); when(jobCaller.fetchData(1)).thenReturn(Arrays.<Object>asList(3, 4)); when(jobCaller.processData(1)).thenReturn(true); when(jobCaller.processData(2)).thenReturn(true); when(jobCaller.processData(3)).thenReturn(false); when(jobCaller.processData(4)).thenThrow(new NullPointerException()); unstreamingBatchSequenceDataFlowElasticJob.execute(null); verify(jobCaller).fetchData(0); verify(jobCaller).fetchData(1); verify(jobCaller).processData(1); verify(jobCaller).processData(2); verify(jobCaller).processData(3); verify(jobCaller).processData(4); ElasticJobAssert.verifyForIsNotMisfireAndIsNotFailover(configService, shardingService, executionContextService, executionService, failoverService, shardingContext); ElasticJobAssert.assertProcessCountStatistics(2, 2); } }
package org.apollo.game.message.handler; import org.apollo.game.message.impl.PlayerDesignMessage; import org.apollo.game.model.Appearance; import org.apollo.game.model.World; import org.apollo.game.model.entity.Player; import org.apollo.game.model.entity.setting.Gender; /** * A {@link MessageHandler} that verifies {@link PlayerDesignMessage}s. * * @author Graham */ public final class PlayerDesignVerificationHandler extends MessageHandler<PlayerDesignMessage> { /** * Creates the PlayerDesignVerificationHandler. * * @param world The {@link World} the {@link PlayerDesignMessage} occurred in. */ public PlayerDesignVerificationHandler(World world) { super(world); } @Override public void handle(Player player, PlayerDesignMessage message) { if (!valid(message.getAppearance())) { message.terminate(); } } /** * Checks if an appearance combination is valid. * * @param appearance The appearance combination. * @return {@code true} if so, {@code false} if not. */ private boolean valid(Appearance appearance) { int[] colors = appearance.getColors(); int[] maxColors = new int[]{11, 15, 15, 5, 7}; for (int i = 0; i < colors.length; i++) { if (colors[i] < 0 || colors[i] > maxColors[i]) { return false; } } switch (appearance.getGender()) { case FEMALE: return validFemaleStyle(appearance); case MALE: return validMaleStyle(appearance); } throw new IllegalArgumentException("Player can only be either male or female."); } /** * Checks if a {@link Gender#FEMALE} style combination is valid. * * @param appearance The appearance combination. * @return {@code true} if so, {@code false} if not. */ private boolean validFemaleStyle(Appearance appearance) { int[] styles = appearance.getStyle(); int[] minStyles = new int[]{45, 255, 56, 61, 67, 70, 79}; int[] maxStyles = new int[]{54, 255, 60, 65, 68, 77, 80}; for (int i = 0; i < styles.length; i++) { if (styles[i] < minStyles[i] || styles[i] > maxStyles[i]) { return false; } } return true; } /** * Checks if a {@link Gender#MALE} style combination is valid. * * @param appearance The appearance combination. * @return {@code true} if so, {@code false} if not. */ private boolean validMaleStyle(Appearance appearance) { int[] styles = appearance.getStyle(); int[] minStyles = new int[]{0, 10, 18, 26, 33, 36, 42}; int[] maxStyles = new int[]{8, 17, 25, 31, 34, 40, 43}; for (int i = 0; i < styles.length; i++) { if (styles[i] < minStyles[i] || styles[i] > maxStyles[i]) { return false; } } return true; } }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 商户报名查询 * * @author auto create * @since 1.0, 2017-10-27 18:12:30 */ public class AlipayInsSceneSellerActivityQueryModel extends AlipayObject { private static final long serialVersionUID = 5119877318373581425L; /** * 渠道账号对应的uid,如果证据类型字段没填则必填 */ @ApiField("channel_account_id") private String channelAccountId; /** * 渠道账号类型,如果证据类型字段没填则必填1:支付宝账号 2:淘宝账号 */ @ApiField("channel_account_type") private Long channelAccountType; /** * 签约的标准产品码 */ @ApiField("sp_code") private String spCode; public String getChannelAccountId() { return this.channelAccountId; } public void setChannelAccountId(String channelAccountId) { this.channelAccountId = channelAccountId; } public Long getChannelAccountType() { return this.channelAccountType; } public void setChannelAccountType(Long channelAccountType) { this.channelAccountType = channelAccountType; } public String getSpCode() { return this.spCode; } public void setSpCode(String spCode) { this.spCode = spCode; } }
package de.moonset.engine.lib.night.hawk.lang.util; import java.util.Collection; import java.util.function.IntFunction; /** * Created by pitt on 11.02.17. */ @Utility public final class Collections { private Collections() { throw new UnsupportedOperationException();} public static <T> T[] toArray(Collection<T> items, IntFunction<T[]> generator) { final T[] result = generator.apply(items.size()); int i = 0; for (T item : items) { result[i++] = item; } return result; } }
/* * #%L * Protempa Framework * %% * Copyright (C) 2012 - 2013 Emory University * %% * 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.protempa.proposition; import org.protempa.proposition.interval.AbstractIntervalUtilTestBase; import org.protempa.proposition.value.AbsoluteTimeUnit; /** * * @author Andrew Post */ public class PropositionUtilTest extends AbstractIntervalUtilTestBase { @Override protected long distanceBetween(AbsoluteTimeUnit absoluteTimeUnit) { return PropositionUtil.distanceBetween(tp1(), tp2(), absoluteTimeUnit); } @Override protected String distanceBetweenFormattedShort() { return PropositionUtil.distanceBetweenFormattedShort(tp1(), tp2()); } @Override protected String distanceBetweenFormattedShort( AbsoluteTimeUnit absoluteTimeUnit) { return PropositionUtil.distanceBetweenFormattedShort(tp1(), tp2(), absoluteTimeUnit); } @Override protected String distanceBetweenFormattedMedium() { return PropositionUtil.distanceBetweenFormattedMedium(tp1(), tp2()); } @Override protected String distanceBetweenFormattedMedium( AbsoluteTimeUnit absoluteTimeUnit) { return PropositionUtil.distanceBetweenFormattedMedium(tp1(), tp2(), absoluteTimeUnit); } @Override protected String distanceBetweenFormattedLong() { return PropositionUtil.distanceBetweenFormattedLong(tp1(), tp2()); } @Override protected String distanceBetweenFormattedLong( AbsoluteTimeUnit absoluteTimeUnit) { return PropositionUtil.distanceBetweenFormattedLong(tp1(), tp2(), absoluteTimeUnit); } private TemporalProposition tp1() { TemporalProposition tp1 = new Event("foo", getUid()); tp1.setInterval(ival1()); return tp1; } private TemporalProposition tp2() { TemporalProposition tp2 = new Event("foo", getUid()); tp2.setInterval(ival2()); return tp2; } }
package mage.cards.d; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.BlocksOrBecomesBlockedSourceTriggeredAbility; import mage.abilities.effects.common.PhaseOutSourceEffect; import mage.abilities.effects.common.PhaseOutTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.StaticFilters; import java.util.UUID; /** * @author TheElk801 */ public final class DreamFighter extends CardImpl { public DreamFighter(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SOLDIER); this.power = new MageInt(1); this.toughness = new MageInt(1); // Whenever Dream Fighter blocks or becomes blocked by a creature, Dream Fighter and that creature phase out. Ability ability = new BlocksOrBecomesBlockedSourceTriggeredAbility( new PhaseOutSourceEffect(), StaticFilters.FILTER_PERMANENT_CREATURE, false, "Whenever {this} blocks or becomes blocked by a creature, " + "{this} and that creature phase out.", true ); ability.addEffect(new PhaseOutTargetEffect()); this.addAbility(ability); } private DreamFighter(final DreamFighter card) { super(card); } @Override public DreamFighter copy() { return new DreamFighter(this); } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.mps.v20190612.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ExecuteFunctionResponse extends AbstractModel{ /** * 处理结果打包后的字符串,具体与后台一同协调。 */ @SerializedName("Result") @Expose private String Result; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 处理结果打包后的字符串,具体与后台一同协调。 * @return Result 处理结果打包后的字符串,具体与后台一同协调。 */ public String getResult() { return this.Result; } /** * Set 处理结果打包后的字符串,具体与后台一同协调。 * @param Result 处理结果打包后的字符串,具体与后台一同协调。 */ public void setResult(String Result) { this.Result = Result; } /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public ExecuteFunctionResponse() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public ExecuteFunctionResponse(ExecuteFunctionResponse source) { if (source.Result != null) { this.Result = new String(source.Result); } if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Result", this.Result); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
package com.xhe; import com.xhe.datasources.DynamicDataSourceConfig; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Import; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) @Import({DynamicDataSourceConfig.class}) @MapperScan(basePackages = {"com.xhe.modules.dao"}) //@EnableScheduling //启用定时任务 public class FastDevApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(FastDevApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(FastDevApplication.class); } }
/* * 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.netbeans.modules.websvc.wsitmodelext.security.parameters; import org.netbeans.modules.xml.wsdl.model.ExtensibilityElement; /** * * @author Martin Grebac */ public interface MustSupportRefIssuerSerial extends ExtensibilityElement { }
package net.oschina.app.improve.detail.v2; import android.annotation.SuppressLint; import android.text.TextUtils; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import net.oschina.app.AppContext; import net.oschina.app.R; import net.oschina.app.api.remote.OSChinaApi; import net.oschina.app.improve.account.AccountHelper; import net.oschina.app.improve.account.activity.LoginActivity; import net.oschina.app.improve.base.activities.BaseBackActivity; import net.oschina.app.improve.bean.News; import net.oschina.app.improve.bean.SubBean; import net.oschina.app.improve.bean.comment.Comment; import net.oschina.app.improve.bean.simple.About; import net.oschina.app.improve.behavior.CommentBar; import net.oschina.app.improve.comment.CommentsActivity; import net.oschina.app.improve.comment.OnCommentClickListener; import net.oschina.app.improve.dialog.ShareDialog; import net.oschina.app.improve.tweet.service.TweetPublishService; import net.oschina.app.improve.user.activities.UserSelectFriendsActivity; import net.oschina.app.improve.widget.adapter.OnKeyArrivedListenerAdapter; import net.oschina.app.ui.empty.EmptyLayout; import net.oschina.app.util.HTMLUtil; import net.oschina.app.util.StringUtils; import net.oschina.app.util.TDevice; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 新版本详情页实现 * Created by haibin * on 2016/11/30. */ public abstract class DetailActivity extends BaseBackActivity implements DetailContract.EmptyView, Runnable, OnCommentClickListener { protected String mCommentHint; protected DetailPresenter mPresenter; protected EmptyLayout mEmptyLayout; protected DetailFragment mDetailFragment; protected ShareDialog mAlertDialog; protected TextView mCommentCountView; protected CommentBar mDelegation; protected SubBean mBean; protected String mIdent; protected long mCommentId; protected long mCommentAuthorId; protected boolean mInputDoubleEmpty = false; @Override protected int getContentView() { return R.layout.activity_detail_v2; } @Override protected void initWidget() { super.initWidget(); if (!TDevice.hasWebView(this)) { finish(); return; } if (TextUtils.isEmpty(mCommentHint)) mCommentHint = getString(R.string.pub_comment_hint); LinearLayout layComment = (LinearLayout) findViewById(R.id.ll_comment); mEmptyLayout = (EmptyLayout) findViewById(R.id.lay_error); mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mEmptyLayout.getErrorState() != EmptyLayout.NETWORK_LOADING) { mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING); mPresenter.getDetail(); } } }); mBean = (SubBean) getIntent().getSerializableExtra("sub_bean"); mIdent = getIntent().getStringExtra("ident"); mDetailFragment = getDetailFragment(); addFragment(R.id.lay_container, mDetailFragment); mPresenter = new DetailPresenter(mDetailFragment, this, mBean, mIdent); if (!mPresenter.isHideCommentBar()) { mDelegation = CommentBar.delegation(this, layComment); mDelegation.setCommentHint(mCommentHint); mDelegation.getBottomSheet().getEditText().setHint(mCommentHint); mDelegation.setFavDrawable(mBean.isFavorite() ? R.drawable.ic_faved : R.drawable.ic_fav); mDelegation.setFavListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!AccountHelper.isLogin()) { LoginActivity.show(DetailActivity.this); return; } mPresenter.favReverse(); } }); mDelegation.getBottomSheet().setMentionListener(new View.OnClickListener() { @Override public void onClick(View v) { if ((AccountHelper.isLogin())) { UserSelectFriendsActivity.show(DetailActivity.this, mDelegation.getBottomSheet().getEditText()); } else { LoginActivity.show(DetailActivity.this, 1); } } }); mDelegation.setShareListener(new View.OnClickListener() { @Override public void onClick(View v) { toShare(mBean.getTitle(), mBean.getBody(), mBean.getHref()); } }); mDelegation.getBottomSheet().getEditText().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL) { handleKeyDel(); } return false; } }); mDelegation.getBottomSheet().setCommitListener(new View.OnClickListener() { @Override public void onClick(View v) { // showDialog("正在提交评论..."); if (mDelegation == null) return; mDelegation.getBottomSheet().dismiss(); mDelegation.setCommitButtonEnable(false); mPresenter.addComment(mBean.getId(), mBean.getType(), mDelegation.getBottomSheet().getCommentText(), 0, mCommentId, mCommentAuthorId); } }); mDelegation.getBottomSheet().getEditText().setOnKeyArrivedListener(new OnKeyArrivedListenerAdapter(this)); } mEmptyLayout.post(new Runnable() { @Override public void run() { mPresenter.getCache(); mPresenter.getDetail(); } }); } @Override public void hideEmptyLayout() { mEmptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT); if (mCommentCountView != null) { mCommentCountView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommentsActivity.show(DetailActivity.this, mBean.getId(), mBean.getType(), OSChinaApi.COMMENT_NEW_ORDER); } }); } } @Override public void showErrorLayout(int errorType) { mEmptyLayout.setErrorType(errorType); } @Override public void showGetDetailSuccess(SubBean bean) { this.mBean = bean; if (mDelegation != null) mDelegation.setFavDrawable(mBean.isFavorite() ? R.drawable.ic_faved : R.drawable.ic_fav); if (mCommentCountView != null && mBean.getStatistics() != null) { mCommentCountView.setText(String.valueOf(mBean.getStatistics().getComment())); } } @Override public void run() { hideEmptyLayout(); mDetailFragment.onPageFinished(); } @Override public void showFavReverseSuccess(boolean isFav, int favCount, int strId) { if (mDelegation != null) { mDelegation.setFavDrawable(isFav ? R.drawable.ic_faved : R.drawable.ic_fav); } } @Override public void showCommentSuccess(Comment comment) { //hideDialog(); if (mDelegation == null) return; if (mDelegation.getBottomSheet().isSyncToTweet()) { TweetPublishService.startActionPublish(this, mDelegation.getBottomSheet().getCommentText(), null, About.buildShare(mBean.getId(), mBean.getType())); } mDelegation.getBottomSheet().dismiss(); mDelegation.setCommitButtonEnable(true); AppContext.showToastShort(R.string.pub_comment_success); mDelegation.getCommentText().setHint(mCommentHint); mDelegation.getBottomSheet().getEditText().setText(""); mDelegation.getBottomSheet().getEditText().setHint(mCommentHint); mDelegation.getBottomSheet().dismiss(); } @Override public void showCommentError(String message) { //hideDialog(); AppContext.showToastShort(R.string.pub_comment_failed); mDelegation.setCommitButtonEnable(true); } @SuppressLint("SetTextI18n") @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_detail, menu); MenuItem item = menu.findItem(R.id.menu_scroll_comment); if (item != null) { View action = item.getActionView(); if (action != null) { View tv = action.findViewById(R.id.tv_comment_count); if (tv != null) { mCommentCountView = (TextView) tv; if (mBean.getStatistics() != null) mCommentCountView.setText(mBean.getStatistics().getComment() + ""); } } } return true; } @SuppressWarnings({"LoopStatementThatDoesntLoop", "SuspiciousMethodCalls"}) protected boolean toShare(String title, String content, String url) { if (TextUtils.isEmpty(title) || TextUtils.isEmpty(url) || mBean == null) return false; String imageUrl = null; List<SubBean.Image> images = mBean.getImages(); switch (mBean.getType()) { case News.TYPE_EVENT: if (images != null && images.size() > 0) { imageUrl = images.get(0).getHref(); } break; case News.TYPE_SOFTWARE: if (images != null && images.size() > 0) { imageUrl = images.get(0).getThumb(); if (imageUrl != null && imageUrl.contains("logo/default.png")) { imageUrl = null; } break; } default: String regex = "<img src=\"([^\"]+)\""; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); while (matcher.find()) { imageUrl = matcher.group(1); break; } break; } content = content.trim(); if (content.length() > 55) { content = HTMLUtil.delHTMLTag(content); if (content.length() > 55) content = StringUtils.getSubString(0, 55, content); } else { content = HTMLUtil.delHTMLTag(content); } if (TextUtils.isEmpty(content)) content = ""; // 分享 if (mAlertDialog == null) { mAlertDialog = new ShareDialog(this, mBean.getId()) .type(mBean.getType()) .title(title) .content(content) .imageUrl(imageUrl)//如果没有图片,即url为null,直接加入app默认分享icon .url(url).with(); } mAlertDialog.show(); return true; } @Override public void onClick(View view, Comment comment) { mCommentId = comment.getId(); mCommentAuthorId = comment.getAuthor().getId(); mDelegation.getCommentText().setHint(String.format("%s %s", getResources().getString(R.string.reply_hint), comment.getAuthor().getName())); mDelegation.getBottomSheet().show(String.format("%s %s", getResources().getString(R.string.reply_hint), comment.getAuthor().getName())); } protected void handleKeyDel() { if (mCommentId != mBean.getId()) { if (TextUtils.isEmpty(mDelegation.getBottomSheet().getCommentText())) { if (mInputDoubleEmpty) { mCommentId = mBean.getId(); mCommentAuthorId = 0; mDelegation.setCommentHint(mCommentHint); mDelegation.getBottomSheet().getEditText().setHint(mCommentHint); } else { mInputDoubleEmpty = true; } } else { mInputDoubleEmpty = false; } } } protected int getExtraInt(Object object) { return object == null ? 0 : Double.valueOf(object.toString()).intValue(); } protected abstract DetailFragment getDetailFragment(); @Override public void finish() { if (mEmptyLayout.getErrorState() == EmptyLayout.HIDE_LAYOUT) DetailCache.addCache(mBean); super.finish(); } @Override protected void onResume() { super.onResume(); if (mAlertDialog == null) return; mAlertDialog.hideProgressDialog(); } }
/* * 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.hop.databases.sybase; import org.apache.hop.core.Const; import org.apache.hop.core.database.BaseDatabaseMeta; import org.apache.hop.core.database.DatabaseMeta; import org.apache.hop.core.database.DatabaseMetaPlugin; import org.apache.hop.core.database.IDatabase; import org.apache.hop.core.gui.plugin.GuiPlugin; import org.apache.hop.core.row.IValueMeta; /** * Contains Sybase specific information through static final members */ @DatabaseMetaPlugin(type = "SYBASE", typeDescription = "Sybase", documentationUrl = "/database/databases/sybase.html") @GuiPlugin(id = "GUI-SybaseDatabaseMeta") public class SybaseDatabaseMeta extends BaseDatabaseMeta implements IDatabase { @Override public int[] getAccessTypeList() { return new int[] {DatabaseMeta.TYPE_ACCESS_NATIVE}; } @Override public int getDefaultDatabasePort() { if (getAccessType() == DatabaseMeta.TYPE_ACCESS_NATIVE) { return 5001; } return -1; } /** @see IDatabase#getNotFoundTK(boolean) */ @Override public int getNotFoundTK(boolean useAutoinc) { if (supportsAutoInc() && useAutoinc) { return 1; } return super.getNotFoundTK(useAutoinc); } @Override public String getDriverClass() { return "net.sourceforge.jtds.jdbc.Driver"; } @Override public String getURL(String hostname, String port, String databaseName) { // jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]] return "jdbc:jtds:sybase://" + hostname + ":" + port + "/" + databaseName; } /** @see IDatabase#getSchemaTableCombination(String, String) */ @Override public String getSchemaTableCombination(String schemaName, String tablePart) { return tablePart; } /** * @return true if this database needs a transaction to perform a query (auto-commit turned off). */ @Override public boolean isRequiringTransactionsOnQueries() { return false; } /** * Generates the SQL statement to add a column to the specified table * * @param tableName The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param useAutoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to add a column to the specified table */ @Override public String getAddColumnStatement( String tableName, IValueMeta v, String tk, boolean useAutoinc, String pk, boolean semicolon) { return "ALTER TABLE " + tableName + " ADD " + getFieldDefinition(v, tk, pk, useAutoinc, true, false); } /** * Generates the SQL statement to modify a column in the specified table * * @param tableName The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param useAutoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to modify a column in the specified table */ @Override public String getModifyColumnStatement( String tableName, IValueMeta v, String tk, boolean useAutoinc, String pk, boolean semicolon) { return "ALTER TABLE " + tableName + " MODIFY " + getFieldDefinition(v, tk, pk, useAutoinc, true, false); } @Override public String getFieldDefinition( IValueMeta v, String tk, String pk, boolean useAutoinc, boolean addFieldName, boolean addCr) { String retval = ""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); if (addFieldName) { retval += fieldname + " "; } int type = v.getType(); switch (type) { case IValueMeta.TYPE_TIMESTAMP: case IValueMeta.TYPE_DATE: retval += "DATETIME NULL"; break; case IValueMeta.TYPE_BOOLEAN: if (supportsBooleanDataType()) { retval += "BOOLEAN"; } else { retval += "CHAR(1)"; } break; case IValueMeta.TYPE_NUMBER: case IValueMeta.TYPE_INTEGER: case IValueMeta.TYPE_BIGNUMBER: if (fieldname.equalsIgnoreCase(tk) || // Technical key: auto increment field! fieldname.equalsIgnoreCase(pk) // Primary key ) { if (useAutoinc) { retval += "INTEGER IDENTITY NOT NULL"; } else { retval += "INTEGER NOT NULL PRIMARY KEY"; } } else { if (precision != 0 || (precision == 0 && length > 9)) { if (precision > 0 && length > 0) { retval += "DECIMAL(" + length + ", " + precision + ") NULL"; } else { retval += "DOUBLE PRECISION NULL"; } } else { // Precision == 0 && length<=9 if (length < 3) { retval += "TINYINT NULL"; } else if (length < 5) { retval += "SMALLINT NULL"; } else { retval += "INTEGER NULL"; } } } break; case IValueMeta.TYPE_STRING: if (length >= 2048) { retval += "TEXT NULL"; } else { retval += "VARCHAR"; if (length > 0) { retval += "(" + length + ")"; } retval += " NULL"; } break; default: retval += " UNKNOWN"; break; } if (addCr) { retval += Const.CR; } return retval; } @Override public String getExtraOptionsHelpText() { return "http://jtds.sourceforge.net/faq.html#urlFormat"; } /** * Get the SQL to insert a new empty unknown record in a dimension. * * @param schemaTable the schema-table name to insert into * @param keyField The key field * @param versionField the version field * @return the SQL to insert the unknown record into the SCD. */ @Override public String getSqlInsertAutoIncUnknownDimensionRow( String schemaTable, String keyField, String versionField) { return "insert into " + schemaTable + "(" + versionField + ") values (1)"; } /** * @param string * @return A string that is properly quoted for use in a SQL statement (insert, update, delete, * etc) */ @Override public String quoteSqlString(String string) { string = string.replace("'", "''"); string = string.replace("\\n", "\\0xd"); string = string.replace("\\r", "\\0xa"); return "'" + string + "'"; } @Override public boolean isSybaseVariant() { return true; } }