repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
JockiHendry/simple-jpa
src/main/simplejpa/artifact/repository/RepositoryManager.java
271
package simplejpa.artifact.repository; import java.util.Map; public interface RepositoryManager { public Object findRepository(String name); public Object doInstantiate(String name, boolean triggerEvent); public Map<String, Object> getRepositories(); }
apache-2.0
ahgittin/license-audit-maven-plugin
src/test/java/org/heneveld/maven/license_audit/util/LicenseCodeTest.java
3560
package org.heneveld.maven.license_audit.util; import org.apache.maven.model.License; import junit.framework.TestCase; public class LicenseCodeTest extends TestCase { public void testGetCodesFromRegex() { assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("Eclipse Public License, Version 1.0")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("\nEclipse Public License, Version 1.0 ")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("Eclipse Public License (EPL), v 1 (EPL-1.0)")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("Eclipse Public License - v 1.0")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("Eclipse Public License 1 (EPL-1.0.0)")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("Eclipse Public License 1 - EPL")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("Eclipse Public License 1 - EPL-1.0")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("EPL v.1.0")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("EPL-1.0")); assertEquals("EPL-2.0", LicenseCodes.getLicenseCode("Eclipse Public - v2.0")); assertEquals("EPL-2.0", LicenseCodes.getLicenseCode("Eclipse Public License")); assertEquals("EDL-1.0", LicenseCodes.getLicenseCode("Eclipse Distribution License v1 - EDL-1.0")); assertNull(LicenseCodes.getLicenseCode("Eclipse Public License 1 - EPL - 1 - fail")); assertNull(LicenseCodes.getLicenseCode("Eclipse Public License 0.9")); assertEquals("EPL-2.0", LicenseCodes.getLicenseCode("Eclipse Public License (EPL)")); assertEquals("EPL-1.0", LicenseCodes.getLicenseCode("EPL-1.0")); assertEquals("Apache-2.0", LicenseCodes.getLicenseCode("Apache 2")); assertEquals("Apache-2.0", LicenseCodes.getLicenseCode("Apache License v2.0")); assertEquals("Apache-2.0", LicenseCodes.getLicenseCode("ASL, version 2")); assertEquals("Apache-2.0", LicenseCodes.getLicenseCode("ASL")); assertEquals("GPL-3.0", LicenseCodes.getLicenseCode("GNU license (gpl)")); assertEquals("LGPL-3.0", LicenseCodes.getLicenseCode("GNU lesser license (lgpl3) 3")); assertEquals("LGPL-2.1", LicenseCodes.getLicenseCode("LGPL, version 2.1")); assertNull(LicenseCodes.getLicenseCode("lesser GNU license (gpl3) 3")); assertEquals("CDDL-1.1", LicenseCodes.getLicenseCode("\nCDDL 1.1 ")); assertEquals("BSD-2-Clause", LicenseCodes.getLicenseCode("simplified (freebsd) bsd 2 clause license")); assertEquals("Public-Domain", LicenseCodes.getLicenseCode("Public domain")); assertEquals("Public-Domain", LicenseCodes.getLicenseCode("Public Domain")); } public void testGetCodesFromRegexLookupKnownNames() { for (String code: LicenseCodes.KNOWN_LICENSE_CODES_WITH_REGEX.keySet()) { License l = LicenseCodes.KNOWN_LICENSE_CODES_WITH_LICENSE.get(code); if (l!=null) { String name = l.getName(); assertEquals("lookup of "+name, code, LicenseCodes.getLicenseCode(name)); } } } public void testGetCodesFromRegexLookupKnownCodes() { for (String code: LicenseCodes.KNOWN_LICENSE_CODES_WITH_REGEX.keySet()) { License l = LicenseCodes.KNOWN_LICENSE_CODES_WITH_LICENSE.get(code); if (l!=null) { assertEquals("lookup of "+code, code, code); } } } }
apache-2.0
vovagrechka/fucking-everything
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/codeInsight/intentions/PyJoinIfIntention.java
5981
/* * Copyright 2000-2014 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 vgrechka.phizdetsidea.phizdets.codeInsight.intentions; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import vgrechka.phizdetsidea.phizdets.PyBundle; import vgrechka.phizdetsidea.phizdets.PyTokenTypes; import vgrechka.phizdetsidea.phizdets.psi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * User: catherine * Intention to merge the if clauses in the case of nested ifs where only the inner if contains code (the outer if only contains the inner one) * For instance, * if a: * if b: * # stuff here * into * if a and b: * #stuff here */ public class PyJoinIfIntention extends PyBaseIntentionAction { @NotNull public String getFamilyName() { return PyBundle.message("INTN.join.if"); } @NotNull public String getText() { return PyBundle.message("INTN.join.if.text"); } public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { if (!(file instanceof PyFile)) { return false; } PyIfStatement expression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyIfStatement.class); PyIfStatement outer = getIfStatement(expression); if (outer != null) { if (outer.getElsePart() != null || outer.getElifParts().length > 0) return false; PyStatement firstStatement = getFirstStatement(outer); PyStatementList outerStList = outer.getIfPart().getStatementList(); if (outerStList != null && outerStList.getStatements().length != 1) return false; if (firstStatement instanceof PyIfStatement) { final PyIfStatement inner = (PyIfStatement)firstStatement; if (inner.getElsePart() != null || inner.getElifParts().length > 0) return false; PyStatementList stList = inner.getIfPart().getStatementList(); if (stList != null) if (stList.getStatements().length != 0) return true; } } return false; } public void doInvoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PyIfStatement expression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyIfStatement.class); PyIfStatement ifStatement = getIfStatement(expression); PyStatement firstStatement = getFirstStatement(ifStatement); if (ifStatement == null) return; if (firstStatement != null && firstStatement instanceof PyIfStatement) { PyExpression condition = ((PyIfStatement)firstStatement).getIfPart().getCondition(); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); PyExpression ifCondition = ifStatement.getIfPart().getCondition(); if (ifCondition == null || condition == null) return; StringBuilder replacementText = new StringBuilder(ifCondition.getText() + " and "); if (condition instanceof PyBinaryExpression && ((PyBinaryExpression)condition).getOperator() == PyTokenTypes.OR_KEYWORD) { replacementText.append("(").append(condition.getText()).append(")"); } else replacementText.append(condition.getText()); PyExpression newCondition = elementGenerator.createExpressionFromText(replacementText.toString()); ifCondition.replace(newCondition); PyStatementList stList = ((PyIfStatement)firstStatement).getIfPart().getStatementList(); PyStatementList ifStatementList = ifStatement.getIfPart().getStatementList(); if (ifStatementList == null || stList == null) return; List<PsiComment> comments = PsiTreeUtil.getChildrenOfTypeAsList(ifStatement.getIfPart(), PsiComment.class); comments.addAll(PsiTreeUtil.getChildrenOfTypeAsList(((PyIfStatement)firstStatement).getIfPart(), PsiComment.class)); comments.addAll(PsiTreeUtil.getChildrenOfTypeAsList(ifStatementList, PsiComment.class)); comments.addAll(PsiTreeUtil.getChildrenOfTypeAsList(stList, PsiComment.class)); for (PsiElement comm : comments) { ifStatement.getIfPart().addBefore(comm, ifStatementList); comm.delete(); } ifStatementList.replace(stList); } } @Nullable private static PyStatement getFirstStatement(PyIfStatement ifStatement) { PyStatement firstStatement = null; if (ifStatement != null) { PyStatementList stList = ifStatement.getIfPart().getStatementList(); if (stList != null) { if (stList.getStatements().length != 0) { firstStatement = stList.getStatements()[0]; } } } return firstStatement; } @Nullable private static PyIfStatement getIfStatement(PyIfStatement expression) { while (expression != null) { PyStatementList stList = expression.getIfPart().getStatementList(); if (stList != null) { if (stList.getStatements().length != 0) { PyStatement firstStatement = stList.getStatements()[0]; if (firstStatement instanceof PyIfStatement) { break; } } } expression = PsiTreeUtil.getParentOfType(expression, PyIfStatement.class); } return expression; } }
apache-2.0
bfemiano/cellmate
accumulo-cellmate/src/test/java/cellmate/accumulo/reader/AccumuloReaderTest.java
13464
package cellmate.accumulo.reader; import cellmate.accumulo.cell.SecurityStringValueCell; import cellmate.accumulo.parameters.AccumuloParameters; import cellmate.accumulo.reader.celltransformer.AccumuloCellTransformers; import cellmate.accumulo.reader.celltransformer.SecurityStringCellTransformer; import cellmate.cell.CellGroup; import cellmate.cell.parameters.CommonParameters; import cellmate.extractor.*; import org.apache.accumulo.core.client.*; import org.apache.accumulo.core.client.mock.MockInstance; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.user.RegExFilter; import org.apache.accumulo.core.security.Authorizations; import org.apache.hadoop.io.Text; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.*; /** * User: bfemiano * Date: 9/10/12 * Time: 10:28 PM */ public class AccumuloReaderTest { Instance mockInstance; AccumuloParameters parameters; AccumuloParameters.Builder builder; private static final String PEOPLE_TABLE = "people"; private static final long MAX_MEMORY= 10000L; private static final long MAX_LATENCY=1000L; private static final int MAX_WRITE_THREADS = 4; private static final Text INFO_CF = new Text("info"); private static final Text EVENTS_CF = new Text("events"); private static final Text NAME = new Text("name"); private static final Text AGE = new Text("age"); private static final Text HEIGHT = new Text("height"); private static final Text EVENT1 = new Text("2342"); private static final Text EVENT2 = new Text("2343"); @BeforeClass public void setupParamsAndInstance() throws AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException { mockInstance = new MockInstance("testInstance"); Connector conn = mockInstance.getConnector("user1", "password".getBytes()); if(conn.tableOperations().exists(PEOPLE_TABLE)) conn.tableOperations().delete(PEOPLE_TABLE); conn.tableOperations().create(PEOPLE_TABLE); } @BeforeMethod public void setupBuilder() { builder = new AccumuloParameters.Builder(). setUser("user1"). setZookeepers("localhost:2181"). setInstanceName("testInstance"). setPassword("password"). setMaxResults(100). setTable(PEOPLE_TABLE); } @BeforeClass(dependsOnMethods={"setupParamsAndInstance"}) public void addData() { try { Connector conn = mockInstance.getConnector("user1", "password"); BatchWriter writer = conn.createBatchWriter (PEOPLE_TABLE, MAX_MEMORY, MAX_LATENCY, MAX_WRITE_THREADS); Mutation m1 = new Mutation("row1"); m1.put(INFO_CF, NAME, new Value("brian".getBytes())); m1.put(INFO_CF, AGE, new Value("30".getBytes())); m1.put(INFO_CF, HEIGHT, new Value("6ft".getBytes())); m1.put(EVENTS_CF, EVENT1, new Value("".getBytes())); m1.put(EVENTS_CF, EVENT2, new Value("".getBytes())); Mutation m2 = new Mutation("row2"); m2.put(INFO_CF, NAME, new Value("adam".getBytes())); m2.put(INFO_CF, AGE, new Value("29".getBytes())); m2.put(INFO_CF, HEIGHT, new Value("5ft7inch".getBytes())); m2.put(EVENTS_CF, EVENT1, new Value("".getBytes())); writer.addMutation(m1); writer.addMutation(m2); writer.close(); } catch (Exception e) { fail("failed on setup with exception", e); } } @Test public void readParameters() { parameters = builder.build(); String user = parameters.getUser(); assertEquals(user, "user1"); String password = parameters.getPassword(); assertEquals(password, "password"); String instanceName = parameters.getInstanceName(); assertEquals(instanceName, "testInstance"); String zookeepers = parameters.getZookeepers(); assertEquals(zookeepers, "localhost:2181"); int maxResults = parameters.getMaxResults(); assertEquals(maxResults, 100); } @Test public void readerTypeValidation() { try { CommonParameters badParameters = new CommonParameters.Builder().build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); reader.read(badParameters, AccumuloCellTransformers.stringValueQualtoLabel()); fail("should have throw illegal argument"); } catch (IllegalArgumentException e){ assertTrue(e.getMessage().contains("ReadParameter implementation must be cellmate.accumulo.parameters.AccumuloParameters")); } catch (Exception e){ fail("general exception failure",e); } try { parameters = builder.setZookeepers(null).setInstanceName(null).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); } catch (IllegalArgumentException e){ assertTrue(e.getMessage().contains("missing zookeepers and/or instance id")); } } @Test public void multiFamilyGetAsStrings(){ try { AccumuloParameters localParams = builder.setColumns(new String[]{"info", "events"}).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); List<CellGroup<SecurityStringValueCell>> items = reader.read(localParams, AccumuloCellTransformers.stringValueQualtoLabelWithColFam()); assertNotNull(items); assertEquals(items.size(), 2); assertEquals(items.get(0).getInternalList().size(), 5); assertEquals(items.get(1).getInternalList().size(), 4); } catch (Exception e){ fail("failed with exception",e); } } @Test public void iteratorAttachment() { try { IteratorSetting iter = new IteratorSetting(15, "regexfilter", RegExFilter.class); iter.addOption(RegExFilter.VALUE_REGEX, "brian"); AccumuloParameters localParams = builder.setColumns(new String[]{"info:name"}). addIteratorSetting(iter).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); List<CellGroup<SecurityStringValueCell>> items = reader.read(localParams, AccumuloCellTransformers.stringValueQualtoLabel()); assertNotNull(items); assertEquals(items.size(), 1); SingleMultiValueCellExtractor extractor = new SingleMultiValueCellExtractor(); SecurityStringValueCell cell = extractor.getSingleCellByLabel(items.get(0).getInternalList(), "name"); String value = CellReflector.getValueAsString(cell); assertNotNull(value); assertEquals(value, "brian"); } catch (Exception e){ fail("failed with exception",e); } } @Test public void singleFamilyGetAsStrings() { try { AccumuloParameters localParams = builder.setColumns(new String[]{"info"}).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); List<CellGroup<SecurityStringValueCell>> items = reader.read(localParams, AccumuloCellTransformers.stringValueQualToLabelWithTime_ColVis_ColFam()); assertNotNull(items); assertEquals(items.size(), 2); assertEquals(items.get(0).getInternalList().size(), 3); assertEquals(items.get(1).getInternalList().size(), 3); SingleMultiValueCellExtractor extractor = new SingleMultiValueCellExtractor(); CommonAuxiliaryFieldsCellExtractor auxExtractor = new CommonAuxiliaryFieldsCellExtractor(); SecurityStringValueCell cell = extractor.getSingleCellByLabel(items.get(0).getInternalList(), "name"); String value = CellReflector.getValueAsString(cell); assertNotNull(value); assertEquals(value, "brian"); assertEquals(CellReflector.getColFam(cell), INFO_CF.toString()); String colVis = CellReflector.getAuxiliaryValue(String.class, cell, "colvis"); assertNotNull(colVis); assertEquals(colVis.length(), 0); long timestamp = auxExtractor.getTimestamp(cell, "timestamp"); assertTrue(timestamp > 0l); } catch (Exception e){ fail("failed with exception",e); } } @Test public void restrictedQuals() { try { AccumuloParameters localParams = builder.setColumns(new String[]{"info:name"}).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); List<CellGroup<SecurityStringValueCell>> items = reader.read(localParams, AccumuloCellTransformers.stringValueQualtoLabel()); assertNotNull(items); assertEquals(items.size(), 2); assertEquals(items.get(0).getInternalList().size(), 1); assertEquals(items.get(1).getInternalList().size(), 1); SingleMultiValueCellExtractor extractor = new SingleMultiValueCellExtractor(); CommonAuxiliaryFieldsCellExtractor auxExtractor = new CommonAuxiliaryFieldsCellExtractor(); SecurityStringValueCell cell = extractor.getSingleCellByLabel(items.get(0).getInternalList(), "name"); String value = CellReflector.getValueAsString(cell); assertNotNull(value); assertEquals(value, "brian"); assertEquals(CellReflector.getColFam(cell), INFO_CF.toString()); extractor.getSingleCellByLabel(items.get(0).getInternalList(), "age"); fail("should not have extracted. age does not exist in this scan"); } catch (CellExtractorException e) { if(e.getType().equals(ErrorType.MISSING_FIELD)) { assertTrue(e.getMessage().contains("No value for single get")); } } catch (Exception e){ fail("failed with exception",e); } } @Test public void testRange() { try { AccumuloParameters localParams = builder. setColumns(new String[]{"info"}). setStartKey("row1"). setEndKey("row1").build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); List<CellGroup<SecurityStringValueCell>> items = reader.read(localParams, AccumuloCellTransformers.stringValueQualtoLabel()); assertNotNull(items); assertEquals(items.size(), 1); assertEquals(items.get(0).getInternalList().size(), 3); assertEquals(items.get(0).getTag(), "row1"); } catch (Exception e){ fail("failed with exception",e); } } @Test public void missingTable() { try { AccumuloParameters localParams = builder.setTable(null).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); reader.read(localParams, AccumuloCellTransformers.stringValueQualtoLabel()); fail("reader should complain there is no table"); } catch (IllegalArgumentException e){ assertEquals(e.getMessage(), "Missing table name in parameters"); }catch (Exception e){ fail("failed with exception",e); } } @Test public void missingUser() { try { AccumuloParameters localParams = builder.setUser(null).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); reader.read(localParams, AccumuloCellTransformers.stringValueQualtoLabel()); fail("reader should complain there is no user"); } catch (IllegalArgumentException e){ assertEquals(e.getMessage(), "missing user/pass"); }catch (Exception e){ fail("failed with exception",e); } } @Test public void malforedColFamEntry() { try { AccumuloParameters localParams = builder.setColumns(new String[]{"cf:blah:blah"}).build(); AccumuloDBResultReader reader = new AccumuloDBResultReader(mockInstance); assertNotNull(reader); reader.read(localParams, AccumuloCellTransformers.stringValueQualtoLabel()); fail("reader should complain about malformed column family"); } catch (IllegalArgumentException e){ assertEquals(e.getMessage(), "malformed colFam entry: cf:blah:blah"); }catch (Exception e){ fail("failed with exception",e); } } }
apache-2.0
zurche/open-weather-map-android-wrapper
OWApi/src/main/java/az/openweatherapi/utils/OWSupportedUnits.java
301
package az.openweatherapi.utils; /** * Created by az on 13/10/16. */ public enum OWSupportedUnits { METRIC("metric"), FAHRENHEIT("imperial"); String unit; OWSupportedUnits(String unit) { this.unit = unit; } public String getUnit() { return unit; } }
apache-2.0
zorzella/test-libraries-for-java
src/main/java/com/google/common/testing/junit4/JUnitAsserts.java
8069
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing.junit4; import junit.framework.Assert; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Contains additional assertion methods not found in JUnit. * * @author kevinb */ public final class JUnitAsserts { private JUnitAsserts() { } /** * Asserts that {@code actual} is not equal {@code unexpected}, according * to both {@code ==} and {@link Object#equals}. */ public static void assertNotEqual( String message, Object unexpected, Object actual) { if (equal(unexpected, actual)) { failEqual(message, unexpected); } } /** * Variant of {@link #assertNotEqual(String,Object,Object)} using a * generic message. */ public static void assertNotEqual(Object unexpected, Object actual) { assertNotEqual(null, unexpected, actual); } /** * Asserts that {@code expectedRegex} exactly matches {@code actual} and * fails with {@code message} if it does not. The MatchResult is returned * in case the test needs access to any captured groups. Note that you can * also use this for a literal string, by wrapping your expected string in * {@link Pattern#quote}. */ public static MatchResult assertMatchesRegex( String message, String expectedRegex, String actual) { if (actual == null) { failNotMatches(message, expectedRegex, null); } Matcher matcher = getMatcher(expectedRegex, actual); if (!matcher.matches()) { failNotMatches(message, expectedRegex, actual); } return matcher; } /** * Variant of {@link #assertMatchesRegex(String,String,String)} using a * generic message. */ public static MatchResult assertMatchesRegex( String expectedRegex, String actual) { return assertMatchesRegex(null, expectedRegex, actual); } /** * Asserts that {@code expectedRegex} matches any substring of {@code actual} * and fails with {@code message} if it does not. The Matcher is returned in * case the test needs access to any captured groups. Note that you can also * use this for a literal string, by wrapping your expected string in * {@link Pattern#quote}. */ public static MatchResult assertContainsRegex( String message, String expectedRegex, String actual) { if (actual == null) { failNotContainsRegex(message, expectedRegex, null); } Matcher matcher = getMatcher(expectedRegex, actual); if (!matcher.find()) { failNotContainsRegex(message, expectedRegex, actual); } return matcher; } /** * Variant of {@link #assertContainsRegex(String,String,String)} using a * generic message. */ public static MatchResult assertContainsRegex( String expectedRegex, String actual) { return assertContainsRegex(null, expectedRegex, actual); } /** * Asserts that {@code unexpectedRegex} does not exactly match {@code actual}, * and fails with {@code message} if it does. Note that you can also use * this for a literal string, by wrapping your expected string in * {@link Pattern#quote}. */ public static void assertNotMatchesRegex( String message, String unexpectedRegex, String actual) { Matcher matcher = getMatcher(unexpectedRegex, actual); if (matcher.matches()) { failMatch(message, unexpectedRegex, actual); } } /** * Variant of {@link #assertNotMatchesRegex(String,String,String)} using a * generic message. */ public static void assertNotMatchesRegex( String unexpectedRegex, String actual) { assertNotMatchesRegex(null, unexpectedRegex, actual); } /** * Asserts that {@code unexpectedRegex} does not match any substring of * {@code actual}, and fails with {@code message} if it does. Note that you * can also use this for a literal string, by wrapping your expected string * in {@link Pattern#quote}. */ public static void assertNotContainsRegex( String message, String unexpectedRegex, String actual) { Matcher matcher = getMatcher(unexpectedRegex, actual); if (matcher.find()) { failContainsRegex(message, unexpectedRegex, actual); } } /** * Variant of {@link #assertNotContainsRegex(String,String,String)} using a * generic message. */ public static void assertNotContainsRegex( String unexpectedRegex, String actual) { assertNotContainsRegex(null, unexpectedRegex, actual); } /** * Asserts that {@code actual} contains precisely the elements * {@code expected}, and in the same order. */ public static void assertContentsInOrder( String message, Iterable<?> actual, Object... expected) { Assert.assertEquals(message, Arrays.asList(expected), newArrayList(actual)); } /** * Variant of {@link #assertContentsInOrder(String,Iterable,Object...)} * using a generic message. */ public static void assertContentsInOrder( Iterable<?> actual, Object... expected) { assertContentsInOrder((String) null, actual, expected); } private static Matcher getMatcher(String expectedRegex, String actual) { Pattern pattern = Pattern.compile(expectedRegex); return pattern.matcher(actual); } private static void failEqual(String message, Object unexpected) { failWithMessage(message, "expected not to be:<" + unexpected + ">"); } private static void failNotMatches( String message, String expectedRegex, String actual) { String actualDesc = (actual == null) ? "null" : ('<' + actual + '>'); failWithMessage(message, "expected to match regex:<" + expectedRegex + "> but was:" + actualDesc); } private static void failNotContainsRegex( String message, String expectedRegex, String actual) { String actualDesc = (actual == null) ? "null" : ('<' + actual + '>'); failWithMessage(message, "expected to contain regex:<" + expectedRegex + "> but was:" + actualDesc); } private static void failMatch( String message, String expectedRegex, String actual) { failWithMessage(message, "expected not to match regex:<" + expectedRegex + "> but was:<" + actual + '>'); } private static void failContainsRegex( String message, String expectedRegex, String actual) { failWithMessage(message, "expected not to contain regex:<" + expectedRegex + "> but was:<" + actual + '>'); } private static void failWithMessage(String userMessage, String ourMessage) { Assert.fail((userMessage == null) ? ourMessage : userMessage + ' ' + ourMessage); } private static boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Copied from Google collections to avoid (for now) depending on it (until * we really need it). */ private static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) { // Let ArrayList's sizing logic work, if possible if (elements instanceof Collection) { @SuppressWarnings("unchecked") Collection<? extends E> collection = (Collection<? extends E>) elements; return new ArrayList<E>(collection); } else { Iterator<? extends E> elements1 = elements.iterator(); ArrayList<E> list = new ArrayList<E>(); while (elements1.hasNext()) { list.add(elements1.next()); } return list; } } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-cognitosync/src/main/java/com/amazonaws/services/cognitosync/model/transform/GetIdentityPoolConfigurationResultJsonUnmarshaller.java
3548
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitosync.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.cognitosync.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetIdentityPoolConfigurationResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetIdentityPoolConfigurationResultJsonUnmarshaller implements Unmarshaller<GetIdentityPoolConfigurationResult, JsonUnmarshallerContext> { public GetIdentityPoolConfigurationResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetIdentityPoolConfigurationResult getIdentityPoolConfigurationResult = new GetIdentityPoolConfigurationResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return getIdentityPoolConfigurationResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("IdentityPoolId", targetDepth)) { context.nextToken(); getIdentityPoolConfigurationResult.setIdentityPoolId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("PushSync", targetDepth)) { context.nextToken(); getIdentityPoolConfigurationResult.setPushSync(PushSyncJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("CognitoStreams", targetDepth)) { context.nextToken(); getIdentityPoolConfigurationResult.setCognitoStreams(CognitoStreamsJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return getIdentityPoolConfigurationResult; } private static GetIdentityPoolConfigurationResultJsonUnmarshaller instance; public static GetIdentityPoolConfigurationResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetIdentityPoolConfigurationResultJsonUnmarshaller(); return instance; } }
apache-2.0
eemirtekin/Sakai-10.6-TR
providers/jldap/src/java/edu/amc/sakai/user/RegexpBlacklistEidValidator.java
5398
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/providers/tags/sakai-10.6/jldap/src/java/edu/amc/sakai/user/RegexpBlacklistEidValidator.java $ * $Id: RegexpBlacklistEidValidator.java 105079 2012-02-24 23:08:11Z ottenhoff@longsight.com $ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package edu.amc.sakai.user; import java.util.Collection; import java.util.HashSet; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; /** * Implements <code>User</code> EID "validation" by checking * for matches in a configurable blacklist, entries in which * are treated as regular expressions. * * @author dmccallum * */ public class RegexpBlacklistEidValidator implements EidValidator { private Collection<Pattern> eidBlacklist; private int regexpFlags; /** * Requires minimally valid and non-blacklisted EIDs. This * is tested by calling {@link #isMinimallyValidEid(String)} * and {@link #isBlackListedEid(String)}. Theoretically, then, * a subclass could override {@link #isMinimallyValidEid(String)} * to, for example, allow any non-null EID but allow any * EID not described by the current blacklist. */ public boolean isSearchableEid(String eid) { return isMinimallyValidEid(eid) && !(isBlackListedEid(eid)); } /** * As implemented requires that the given ID be non-null * and non-whitespace. * * @param eid and EID to test * @return <code>true<code> unless the given String is * null or entirely whitespace */ protected boolean isMinimallyValidEid(String eid) { return StringUtils.isNotBlank(eid); } /** * Encapsulates the logic for actually checking a user EID * against the configured blacklist. If no blacklist is * configured, will return <code>false</code> * * @return <code>true</code> if the eid matches a configured * blacklist pattern. <code>false</code> otherwise (e.g. * if no configured blacklist). */ protected boolean isBlackListedEid(String eid) { if ( eidBlacklist == null || eidBlacklist.isEmpty() ) { return false; } for ( Pattern pattern : eidBlacklist ) { if ( pattern.matcher(eid).matches() ) { return true; } } return false; } /** * Access the String representation of blacklisted User EID * regexps configured on this object. The returned collection * may or may not be equivalent to the collection passed to * {@link #setEidBlacklist(Collection)} * * @return */ public Collection<String> getEidBlacklist() { return eidBlacklistAsStrings(); } private Collection<String> eidBlacklistAsStrings() { if ( eidBlacklist == null || eidBlacklist.isEmpty() ) { return new HashSet<String>(0); } HashSet<String> patternStrings = new HashSet<String>(eidBlacklist.size()); for ( Pattern pattern : eidBlacklist ) { patternStrings.add(pattern.pattern()); } return patternStrings; } /** * Converts the given collection of Strings into a collection * of {@Link Pattern}s and caches the latter for evaluation * by {@link #isSearchableEid(String)}. Configure {link Pattern} * evaluation flags with {@link #setRegexpFlags(int)}. * * @param eidBlacklist a collection of Strings to be compiled * into {@link Patterns}. May be <code>null</code>, which * will have the same semantics as an empty collection. */ public void setEidBlacklist(Collection<String> eidBlacklist) { this.eidBlacklist = eidBlacklistAsPatterns(eidBlacklist); } private Collection<Pattern> eidBlacklistAsPatterns( Collection<String> eidBlacklistStrings) { if ( eidBlacklistStrings == null || eidBlacklistStrings.isEmpty() ) { return new HashSet<Pattern>(0); } HashSet<Pattern> patterns = new HashSet<Pattern>(eidBlacklistStrings.size()); for ( String patternString : eidBlacklistStrings ) { Pattern pattern = Pattern.compile(patternString, regexpFlags); patterns.add(pattern); } return patterns; } /** * Access the configured set of {@link Pattern} matching * flags. Defaults to zero. * * @see Pattern#compile(String, int) * @return a bitmask of {@link Pattern} matching flags */ public int getRegexpFlags() { return regexpFlags; } /** * Assign a bitmask for {@link Pattern} matching behaviors. * Be sure to set this property prior to invoking * {@link #setEidBlacklist(Collection)}. The cached {@link Patterns} * will <code>not</code> be recompiled as a side-effect of * invoking this method. * * @param regexpFlags */ public void setRegexpFlags(int regexpFlags) { this.regexpFlags = regexpFlags; } }
apache-2.0
xuse/ef-others
common-misc/src/main/java/jef/dynamic/ClassSource.java
1514
/* * JEF - Copyright 2009-2010 Jiyi (mr.jiyi@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jef.dynamic; import java.io.File; import java.io.IOException; import jef.tools.Assert; import jef.tools.IOUtils; public interface ClassSource { String getName(); byte[] getData(); long getLastModified(); public static class FileClassSource implements ClassSource{ private File file; private String name; private long lastModified; public FileClassSource(File file,String className){ Assert.isTrue(file.exists()); this.name=className; this.file=file; this.lastModified=file.lastModified(); } public byte[] getData() { try { return IOUtils.toByteArray(file); } catch (IOException e) { throw new RuntimeException(e); } } public long getLastModified() { return lastModified; } public String getName() { return name; } @Override public String toString() { return name+"\t"+file.getAbsolutePath(); } } }
apache-2.0
idf/commons-util
src/test/java/io/deepreader/java/commons/util/SerializerTest.java
743
package io.deepreader.java.commons.util; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Created by Daniel on 09/10/15. */ public class SerializerTest extends TestCase { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testSerialize() throws Exception { Double[] arr = new Double[] {0.0, 1.0, 2.0}; assertEquals("[0.00000,1.00000,2.00000]", Serializer.serialize(arr)); } @Test public void testSerialize1() throws Exception { Integer[] arr = new Integer[] {0, 1, 2}; assertEquals("[0,1,2]", Serializer.serialize(arr)); } }
apache-2.0
BMambaYe/SkinExpert
app/src/main/java/com/zhanghao/skinexpert/beans/QuestionBean.java
626
package com.zhanghao.skinexpert.beans; /** * Created by RockGao on 2016/12/23. */ /** * 测试问题的bean类 */ public class QuestionBean { private String title; private String score; public QuestionBean() { } public QuestionBean(String title, String score) { this.title = title; this.score = score; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } }
apache-2.0
Zhangsongsong/GraduationPro
毕业设计/code/android/YYFramework/src/app/logic/activity/search/SearchActivity.java
12596
package app.logic.activity.search; import java.util.ArrayList; import java.util.List; import org.QLConstant; import org.ql.activity.customtitle.ActActivity; import org.ql.utils.QLToastUtils; import com.facebook.drawee.view.SimpleDraweeView; import com.squareup.picasso.Picasso; import android.R.integer; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import app.config.http.HttpConfig; import app.logic.activity.notice.DefaultNoticeActivity; import app.logic.activity.org.DPMListActivity; import app.logic.activity.user.PreviewFriendsInfoActivity; import app.logic.adapter.YYBaseListAdapter; import app.logic.controller.AnnounceController; import app.logic.controller.OrganizationController; import app.logic.controller.UserManagerController; import app.logic.pojo.NoticeInfo; import app.logic.pojo.OrganizationInfo; import app.logic.pojo.SearchInfo; import app.logic.pojo.SearchItemInfo; import app.logic.pojo.UserInfo; import app.logic.pojo.YYChatSessionInfo; import app.utils.common.FrescoImageShowThumb; import app.utils.common.Listener; import app.utils.helpers.ChartHelper; import app.view.YYListView; import app.yy.geju.R; /* * GZYY 2016-12-6 下午6:05:07 * author: zsz */ public class SearchActivity extends ActActivity { private UserInfo userInfo; private EditText search_edt; private RelativeLayout search_default_rl; private YYListView listView; private LayoutInflater inflater; private List<SearchItemInfo> datas = new ArrayList<SearchItemInfo>(); private YYBaseListAdapter<SearchItemInfo> mAdapter = new YYBaseListAdapter<SearchItemInfo>(this) { @Override public View createView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == 2) { if (convertView == null) { convertView = inflater.inflate(R.layout.item_search_listview_org, null); saveView("item_iv", R.id.item_iv, convertView); saveView("item_name_tv", R.id.item_name_tv, convertView); saveView("item_title", R.id.item_title, convertView); } SearchItemInfo info = getItem(position); if (info != null) { SimpleDraweeView imageView = getViewForName("item_iv", convertView); // imageView.setImageURI(HttpConfig.getUrl(info.getOrgDatas().getOrg_logo_url())); FrescoImageShowThumb.showThrumb(Uri.parse(HttpConfig.getUrl(info.getOrgDatas().getOrg_logo_url())),imageView); // Picasso.with(SearchActivity.this).load(HttpConfig.getUrl(info.getOrgDatas().getOrg_logo_url())).fit().centerCrop().into(imageView); setTextToViewText(info.getOrgDatas().getOrg_name(), "item_name_tv", convertView); TextView titleTv = getViewForName("item_title", convertView); titleTv.setText("格局"); titleTv.setVisibility(info.isTitleStatus() ? View.VISIBLE : View.GONE); } } else if (getItemViewType(position) == 1) { if (convertView == null) { convertView = inflater.inflate(R.layout.item_search_listview_org, null); saveView("item_iv", R.id.item_iv, convertView); saveView("item_name_tv", R.id.item_name_tv, convertView); saveView("item_title", R.id.item_title, convertView); } SearchItemInfo info = getItem(position); if (info != null) { setImageToImageViewCenterCrop(HttpConfig.getUrl(info.getNoticeDatas().getMsg_cover()), "item_iv", -1, convertView); setTextToViewText(info.getNoticeDatas().getMsg_title(), "item_name_tv", convertView); TextView titleTv = getViewForName("item_title", convertView); titleTv.setText("公告"); titleTv.setVisibility(info.isTitleStatus() ? View.VISIBLE : View.GONE); } } else { if (convertView == null) { convertView = inflater.inflate(R.layout.item_search_listview_message, null); saveView("item_iv", R.id.item_iv, convertView); saveView("item_name_tv", R.id.item_name_tv, convertView); saveView("item_title", R.id.item_title, convertView); saveView("item_centent_tv", R.id.item_centent_tv, convertView); } SearchItemInfo info = getItem(position); if (info != null) { setImageToImageViewCenterCrop(HttpConfig.getUrl(info.getChatDatas().getPicture_url()), "item_iv", -1, convertView); if(info.getChatDatas().getFriend_name()!=null && !TextUtils.isEmpty(info.getChatDatas().getFriend_name())){ setTextToViewText(info.getChatDatas().getFriend_name(), "item_name_tv", convertView); }else{ setTextToViewText(info.getChatDatas().getNickName(), "item_name_tv", convertView); } TextView titleTv = getViewForName("item_title", convertView); titleTv.setText("联系人"); titleTv.setVisibility(info.isTitleStatus() ? View.VISIBLE : View.GONE); } } return convertView; } /** * 0是对话消息,1是公告,2是组织 */ public int getItemViewType(int position) { SearchItemInfo info = getItem(position); if (info.getOrgDatas() != null) { return 2; } if (info.getNoticeDatas() != null) { return 1; } return 0; } public int getViewTypeCount() { return 3; } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_search); userInfo = UserManagerController.getCurrUserInfo(); inflater = LayoutInflater.from(this); findViewById(R.id.left_iv).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); initView(); addListener(); } private void initView() { search_edt = (EditText) findViewById(R.id.search_edt); search_default_rl = (RelativeLayout) findViewById(R.id.search_default_rl); listView = (YYListView) findViewById(R.id.listView); listView.setPullLoadEnable(false, true); listView.setPullRefreshEnable(false); listView.setAdapter(mAdapter); } private void addListener() { search_edt.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!TextUtils.isEmpty(s.toString())) { getData(s.toString()); } else { search_default_rl.setVisibility(View.VISIBLE); listView.setVisibility(View.GONE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SearchItemInfo info = datas.get(position - 1); if (info == null) { return; } if (info.getOrgDatas() != null) { Intent intent = new Intent(SearchActivity.this, DPMListActivity.class); intent.putExtra(DPMListActivity.kORG_ID, info.getOrgDatas().getOrg_id()); intent.putExtra(DPMListActivity.kORG_NAME, info.getOrgDatas().getOrg_name()); startActivity(intent); } else if (info.getNoticeDatas() != null) { startActivity(new Intent(SearchActivity.this, DefaultNoticeActivity.class).putExtra(DefaultNoticeActivity.NOTICE_ID, info.getNoticeDatas().getMsg_id())); } else { String tagerIdString = info.getChatDatas().getWp_other_info_id(); if (QLConstant.client_id.equals(tagerIdString)) { QLToastUtils.showToast(SearchActivity.this, "该用户是自己"); return; } // ChartHelper.startChart(SearchActivity.this, info.getChatDatas().getWp_other_info_id(), ""); Intent openFriendDetailsIntent = new Intent(SearchActivity.this, PreviewFriendsInfoActivity.class); openFriendDetailsIntent.putExtra(PreviewFriendsInfoActivity.kFROM_CHART_ACTIVITY, false); openFriendDetailsIntent.putExtra(PreviewFriendsInfoActivity.kUSER_MEMBER_ID, info.getChatDatas().getWp_other_info_id()); startActivity(openFriendDetailsIntent); } } }); } private synchronized void getData(String keyword) { UserManagerController.getSearchAllMessage(this, keyword, new Listener<Integer, SearchInfo>() { @Override public void onCallBack(Integer status, SearchInfo reply) { if (reply != null) { datas.clear(); int titleStatus = 0; if (reply.getAssociation() != null) { for (OrganizationInfo info : reply.getAssociation()) { SearchItemInfo itemInfo = new SearchItemInfo(); itemInfo.setOrgDatas(info); datas.add(itemInfo); itemInfo.setTitleStatus(titleStatus == 0 ? true : false); titleStatus = 1; } } titleStatus = 0; if (reply.getMessage() != null) { for (NoticeInfo info : reply.getMessage()) { SearchItemInfo itemInfo = new SearchItemInfo(); itemInfo.setNoticeDatas(info); datas.add(itemInfo); itemInfo.setTitleStatus(titleStatus == 0 ? true : false); titleStatus = 1; } } titleStatus = 0; if (reply.getMember() != null) { for (YYChatSessionInfo info : reply.getMember()) { SearchItemInfo itemInfo = new SearchItemInfo(); itemInfo.setChatDatas(info); datas.add(itemInfo); itemInfo.setTitleStatus(titleStatus == 0 ? true : false); titleStatus = 1; } } mAdapter.setDatas(datas); if (datas.size() > 0) { search_default_rl.setVisibility(View.GONE); listView.setVisibility(View.VISIBLE); } else { search_default_rl.setVisibility(View.VISIBLE); listView.setVisibility(View.GONE); } } } }); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-globalaccelerator/src/main/java/com/amazonaws/services/globalaccelerator/model/transform/WithdrawByoipCidrRequestProtocolMarshaller.java
2762
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.globalaccelerator.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.globalaccelerator.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * WithdrawByoipCidrRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class WithdrawByoipCidrRequestProtocolMarshaller implements Marshaller<Request<WithdrawByoipCidrRequest>, WithdrawByoipCidrRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("GlobalAccelerator_V20180706.WithdrawByoipCidr").serviceName("AWSGlobalAccelerator").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public WithdrawByoipCidrRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<WithdrawByoipCidrRequest> marshall(WithdrawByoipCidrRequest withdrawByoipCidrRequest) { if (withdrawByoipCidrRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<WithdrawByoipCidrRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, withdrawByoipCidrRequest); protocolMarshaller.startMarshalling(); WithdrawByoipCidrRequestMarshaller.getInstance().marshall(withdrawByoipCidrRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
nelt/codingmatters-value-objects
cdm-value-objects-generation/src/test/java/org/codingmatters/value/objects/generation/collection/ValueSetImplementationTest.java
3086
package org.codingmatters.value.objects.generation.collection; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import org.codingmatters.tests.compile.CompiledCode; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.lang.reflect.Constructor; import java.util.Collection; import java.util.HashSet; import static org.codingmatters.tests.reflect.ReflectMatchers.*; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * Created by nelt on 11/19/16. */ public class ValueSetImplementationTest { @Rule public TemporaryFolder dir = new TemporaryFolder(); private CompiledCode compiled; @Before public void setUp() throws Exception { String packageName = "org.generated"; File dest = this.dir.newFolder(); TypeSpec valueSetType = new ValueSet(packageName).type(); TypeSpec valueSetImplementation = new ValueSetImplementation(packageName, valueSetType).type(); JavaFile.builder(packageName, valueSetType) .build() .writeTo(dest); JavaFile javaFile = JavaFile.builder(packageName, valueSetImplementation) .build(); javaFile .writeTo(dest); this.compiled = CompiledCode.builder().source(dest).compile(); } @Test public void extendsHashSet() throws Exception { assertThat( compiled.getClass("org.generated.ValueSetImpl"), is( aPackagePrivate().class_() .extending(HashSet.class) .withParameter(variableType().named("E")) .implementing(compiled.getClass("org.generated.ValueSet")) ) ); } @Test public void constructorFromArray() throws Exception { assertThat( compiled.getClass("org.generated.ValueSetImpl"), is( aPackagePrivate().class_().with( aConstructor().withParameters(typeArray(variableType().named("E"))) ) ) ); Constructor constr = compiled.getClass("org.generated.ValueSetImpl") .getConstructor(new Class[]{Object[].class});; constr.setAccessible(true); Object list = constr.newInstance(new Object[]{new Object[]{"a", "b", "a"}}); assertThat(this.compiled.on(list).invoke("toArray"), is(new Object [] {"a", "b"})); } @Test public void constructorFromCollection() throws Exception { assertThat( compiled.getClass("org.generated.ValueSetImpl"), is( aPackagePrivate().class_().with( aConstructor().withParameters(genericType().baseClass(Collection.class).withParameters(typeParameter().named("E"))) ) ) ); } }
apache-2.0
jitsi/jicofo
src/main/java/org/jitsi/protocol/xmpp/util/TransportSignaling.java
2564
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2015-Present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.protocol.xmpp.util; import org.jetbrains.annotations.*; import org.jitsi.xmpp.extensions.jingle.*; import java.util.*; /** * Class contains utilities specific to transport signaling in Jitsi Meet * conferences. * * @author Pawel Domas */ public class TransportSignaling { /** * Merges source transport into destination by copying information * important for Jitsi Meet transport signaling. * @param dst destination <tt>IceUdpTransportPacketExtension</tt> * @param src source <tt>IceUdpTransportPacketExtension</tt> from which * all relevant information will be merged into <tt>dst</tt> */ static public void mergeTransportExtension( @NotNull IceUdpTransportPacketExtension dst, @NotNull IceUdpTransportPacketExtension src) { // Attributes for (String attribute : src.getAttributeNames()) { dst.setAttribute(attribute, src.getAttribute(attribute)); } // RTCP-MUX if (src.isRtcpMux() && !dst.isRtcpMux()) { dst.addChildExtension(new IceRtcpmuxPacketExtension()); } // Candidates for (CandidatePacketExtension c : src.getCandidateList()) { dst.addCandidate(c); } // DTLS fingerprint DtlsFingerprintPacketExtension srcDtls = src.getFirstChildOfType(DtlsFingerprintPacketExtension.class); if (srcDtls != null) { // Remove the current one if any DtlsFingerprintPacketExtension dstDtls = dst.getFirstChildOfType( DtlsFingerprintPacketExtension.class); if (dstDtls != null) { dst.removeChildExtension(dstDtls); } // Set the fingerprint from the source dst.addChildExtension(srcDtls); } } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/transform/BatchGetOnPremisesInstancesResultJsonUnmarshaller.java
3067
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codedeploy.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.codedeploy.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * BatchGetOnPremisesInstancesResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class BatchGetOnPremisesInstancesResultJsonUnmarshaller implements Unmarshaller<BatchGetOnPremisesInstancesResult, JsonUnmarshallerContext> { public BatchGetOnPremisesInstancesResult unmarshall(JsonUnmarshallerContext context) throws Exception { BatchGetOnPremisesInstancesResult batchGetOnPremisesInstancesResult = new BatchGetOnPremisesInstancesResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return batchGetOnPremisesInstancesResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("instanceInfos", targetDepth)) { context.nextToken(); batchGetOnPremisesInstancesResult.setInstanceInfos(new ListUnmarshaller<InstanceInfo>(InstanceInfoJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return batchGetOnPremisesInstancesResult; } private static BatchGetOnPremisesInstancesResultJsonUnmarshaller instance; public static BatchGetOnPremisesInstancesResultJsonUnmarshaller getInstance() { if (instance == null) instance = new BatchGetOnPremisesInstancesResultJsonUnmarshaller(); return instance; } }
apache-2.0
phax/ph-commons
ph-graph/src/main/java/com/helger/graph/algo/Dijkstra.java
12144
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.graph.algo; import java.util.function.ToIntFunction; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.collection.impl.CommonsArrayList; import com.helger.commons.collection.impl.CommonsLinkedHashMap; import com.helger.commons.collection.impl.CommonsLinkedHashSet; import com.helger.commons.collection.impl.ICommonsList; import com.helger.commons.collection.impl.ICommonsOrderedMap; import com.helger.commons.collection.impl.ICommonsOrderedSet; import com.helger.commons.debug.GlobalDebug; import com.helger.commons.lang.GenericReflection; import com.helger.graph.IMutableBaseGraph; import com.helger.graph.IMutableBaseGraphNode; import com.helger.graph.IMutableBaseGraphRelation; import com.helger.graph.IMutableDirectedGraphNode; import com.helger.graph.IMutableDirectedGraphRelation; /** * Find the shortest path between 2 graph nodes, using Dijsktra's algorithm * * @author Philip Helger */ public final class Dijkstra { private static final Logger LOGGER = LoggerFactory.getLogger (Dijkstra.class); private static final class WorkElement <N extends IMutableBaseGraphNode <N, ?>> { private final N m_aFromNode; private final int m_nDistance; private final N m_aToNode; /** * Special constructor for the initial state * * @param nDistance * Distance to use * @param aToNode * to-node to use */ public WorkElement (@Nonnegative final int nDistance, @Nonnull final N aToNode) { this (null, nDistance, aToNode); } public WorkElement (@Nullable final N aFromNode, @Nonnegative final int nDistance, @Nonnull final N aToNode) { ValueEnforcer.isGE0 (nDistance, "Distance"); ValueEnforcer.notNull (aToNode, "ToNode"); m_aFromNode = aFromNode; m_nDistance = nDistance; m_aToNode = aToNode; } @Nullable public N getFromNode () { return m_aFromNode; } @Nullable public String getFromNodeID () { return m_aFromNode == null ? null : m_aFromNode.getID (); } @Nonnegative public int getDistance () { return m_nDistance; } @Nonnull public N getToNode () { return m_aToNode; } @Nonnull public String getToNodeID () { return m_aToNode.getID (); } @Nonnull @Nonempty public String getAsString () { return "{" + (m_aFromNode == null ? "" : "'" + m_aFromNode.getID () + "',") + (m_nDistance == Integer.MAX_VALUE ? "Inf" : Integer.toString (m_nDistance)) + ",'" + m_aToNode.getID () + "'}"; } } private static final class WorkRow <N extends IMutableBaseGraphNode <N, ?>> { private final ICommonsOrderedMap <String, WorkElement <N>> m_aElements; public WorkRow (@Nonnegative final int nElements) { ValueEnforcer.isGT0 (nElements, "Elements"); m_aElements = new CommonsLinkedHashMap <> (nElements); } public void add (@Nonnull final WorkElement <N> aElement) { ValueEnforcer.notNull (aElement, "Element"); m_aElements.put (aElement.getToNodeID (), aElement); } @Nullable public WorkElement <N> getElement (@Nullable final String sNodeID) { return m_aElements.get (sNodeID); } /** * @return The element with the smallest distance! */ @Nonnull public WorkElement <N> getClosestElement () { WorkElement <N> ret = null; for (final WorkElement <N> aElement : m_aElements.values ()) if (ret == null || aElement.getDistance () < ret.getDistance ()) ret = aElement; if (ret == null) throw new IllegalStateException ("Cannot call this method without an element!"); return ret; } @Nonnull @ReturnsMutableCopy public ICommonsList <WorkElement <N>> getAllElements () { return m_aElements.copyOfValues (); } } @Immutable public static final class Result <N extends IMutableBaseGraphNode <N, ?>> { private final ICommonsList <N> m_aResultNodes; private final int m_nResultDistance; public Result (@Nonnull @Nonempty final ICommonsList <N> aResultNodes, @Nonnegative final int nResultDistance) { ValueEnforcer.notEmpty (aResultNodes, "EesultNodes"); ValueEnforcer.isGE0 (nResultDistance, "Result Distance"); m_aResultNodes = aResultNodes; m_nResultDistance = nResultDistance; } @Nonnull @ReturnsMutableCopy public ICommonsList <N> getAllResultNodes () { return m_aResultNodes.getClone (); } @Nonnegative public int getResultNodeCount () { return m_aResultNodes.size (); } @Nonnegative public int getResultDistance () { return m_nResultDistance; } @Nonnull @Nonempty public String getAsString () { final StringBuilder aSB = new StringBuilder (); aSB.append ("Distance ").append (m_nResultDistance).append (" for route {"); int nIndex = 0; for (final N aNode : m_aResultNodes) { if (nIndex > 0) aSB.append (','); aSB.append ('\'').append (aNode.getID ()).append ('\''); nIndex++; } return aSB.append ('}').toString (); } } private Dijkstra () {} @Nullable private static <N extends IMutableBaseGraphNode <N, R>, R extends IMutableBaseGraphRelation <N, R>> R _getRelationFromLastMatch (@Nonnull final WorkElement <N> aLastMatch, @Nonnull final N aNode) { if (aNode.isDirected ()) { // Directed // Cast to Object required for JDK command line compiler final Object aDirectedFromNode = aLastMatch.getToNode (); final Object aDirectedToNode = aNode; final IMutableDirectedGraphRelation r = ((IMutableDirectedGraphNode) aDirectedFromNode).getOutgoingRelationTo ((IMutableDirectedGraphNode) aDirectedToNode); return GenericReflection.uncheckedCast (r); } // Undirected return aLastMatch.getToNode ().getRelation (aNode); } @Nonnull public static <N extends IMutableBaseGraphNode <N, R>, R extends IMutableBaseGraphRelation <N, R>> Dijkstra.Result <N> applyDijkstra (@Nonnull final IMutableBaseGraph <N, R> aGraph, @Nonnull @Nonempty final String sFromID, @Nonnull @Nonempty final String sToID, @Nonnull final ToIntFunction <? super R> aRelationCostProvider) { final N aStartNode = aGraph.getNodeOfID (sFromID); if (aStartNode == null) throw new IllegalArgumentException ("Invalid From ID: " + sFromID); final N aEndNode = aGraph.getNodeOfID (sToID); if (aEndNode == null) throw new IllegalArgumentException ("Invalid To ID: " + sToID); // Ordered set for deterministic results final ICommonsOrderedSet <N> aAllRemainingNodes = new CommonsLinkedHashSet <> (aGraph.getAllNodes ().values ()); if (GlobalDebug.isDebugMode ()) if (LOGGER.isInfoEnabled ()) LOGGER.info ("Starting Dijkstra on directed graph with " + aAllRemainingNodes.size () + " nodes starting from '" + sFromID + "' and up to '" + sToID + "'"); // Map from to-node-id to element final ICommonsOrderedMap <String, WorkElement <N>> aAllMatches = new CommonsLinkedHashMap <> (); WorkElement <N> aLastMatch = null; WorkRow <N> aLastRow = null; int nIteration = 0; do { final WorkRow <N> aRow = new WorkRow <> (aAllRemainingNodes.size ()); if (aLastRow == null) { // Initial row - no from node for (final N aNode : aAllRemainingNodes) if (aNode.equals (aStartNode)) { // Start node has distance 0 to itself aRow.add (new WorkElement <> (0, aNode)); } else { // All other elements have infinite distance to the start node (for // now) aRow.add (new WorkElement <> (Integer.MAX_VALUE, aNode)); } } else { // All following rows for (final N aNode : aAllRemainingNodes) { // Find distance to last match final WorkElement <N> aPrevElement = aLastRow.getElement (aNode.getID ()); // Get the relation from the last match to this node (may be null if // nodes are not connected) final R aRelation = Dijkstra.<N, R> _getRelationFromLastMatch (aLastMatch, aNode); if (aRelation != null) { // Nodes are related - check weight final int nNewDistance = aLastMatch.getDistance () + aRelationCostProvider.applyAsInt (aRelation); // Use only, if distance is shorter (=better) than before! if (nNewDistance < aPrevElement.getDistance ()) aRow.add (new WorkElement <> (aLastMatch.getToNode (), nNewDistance, aNode)); else aRow.add (aPrevElement); } else { // Nodes are not related - use result from previous row aRow.add (aPrevElement); } } } // Get the closest element of the current row final WorkElement <N> aClosest = aRow.getClosestElement (); if (GlobalDebug.isDebugMode ()) { final StringBuilder aSB = new StringBuilder ("Iteration[").append (nIteration).append ("]: "); for (final WorkElement <N> e : aRow.getAllElements ()) aSB.append (e.getAsString ()); aSB.append (" ==> ").append (aClosest.getAsString ()); if (LOGGER.isInfoEnabled ()) LOGGER.info (aSB.toString ()); } aAllRemainingNodes.remove (aClosest.getToNode ()); aAllMatches.put (aClosest.getToNodeID (), aClosest); aLastMatch = aClosest; aLastRow = aRow; ++nIteration; if (aClosest.getToNode ().equals (aEndNode)) { // We found the shortest way to the end node! break; } } while (true); // Now get the result path from back to front final int nResultDistance = aLastMatch.getDistance (); final ICommonsList <N> aResultNodes = new CommonsArrayList <> (); while (true) { aResultNodes.add (0, aLastMatch.getToNode ()); // Are we at the start node? if (aLastMatch.getFromNode () == null) break; aLastMatch = aAllMatches.get (aLastMatch.getFromNodeID ()); if (aLastMatch == null) throw new IllegalStateException ("Inconsistency!"); } // Results return new Dijkstra.Result <> (aResultNodes, nResultDistance); } }
apache-2.0
santhosh-tekuri/jlibs
i18n-apt/src/test/resources/i18n/MethodSignatureClash2Bundle.java
299
package i18n; import jlibs.core.util.i18n.Message; import jlibs.core.util.i18n.ResourceBundle; /** * @author Santhosh Kumar T */ @ResourceBundle public interface MethodSignatureClash2Bundle{ @Message(key="EXECUTING_QUERY", value="executing {0}") public String executing(String query); }
apache-2.0
josuemontano/SHTezt
No XML Configuration/src/main/java/com/hanovit/app/config/HibernateConfig.java
2212
package com.hanovit.app.config; import java.util.Properties; import javax.annotation.Resource; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.core.env.Environment; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; /** * * @author Josue Montano */ @Configuration @PropertySource("classpath:database.properties") public class HibernateConfig { @Resource public Environment env; @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[]{"com.hanovit.app"}); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("database.driverClassName")); dataSource.setUrl(env.getProperty("database.url")); dataSource.setUsername(env.getProperty("database.username")); dataSource.setPassword(env.getProperty("database.password")); dataSource.setValidationQuery(env.getProperty("database.validationQuery")); return dataSource; } @Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); return transactionManager; } @Bean public Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", env.getProperty("database.dialect")); properties.put("hibernate.show_sql", false); return properties; } }
apache-2.0
redox/OrientDB
core/src/main/java/com/orientechnologies/orient/core/command/script/OScriptManager.java
6461
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.command.script; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import com.orientechnologies.orient.core.command.script.formatter.OJSScriptFormatter; import com.orientechnologies.orient.core.command.script.formatter.ORubyScriptFormatter; import com.orientechnologies.orient.core.command.script.formatter.OScriptFormatter; import com.orientechnologies.orient.core.db.ODatabaseComplex; import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx; import com.orientechnologies.orient.core.metadata.function.OFunction; import com.orientechnologies.orient.core.sql.OSQLScriptEngine; /** * Executes Script Commands. * * @see OCommandScript * @author Luca Garulli * */ public class OScriptManager { protected final String DEF_LANGUAGE = "javascript"; protected ScriptEngineManager scriptEngineManager; protected Map<String, ScriptEngine> engines; protected String defaultLanguage = DEF_LANGUAGE; protected Map<String, OScriptFormatter> formatters = new HashMap<String, OScriptFormatter>(); protected List<OScriptInjection> injections = new ArrayList<OScriptInjection>(); public OScriptManager() { if (engines == null) { engines = new HashMap<String, ScriptEngine>(); scriptEngineManager = new ScriptEngineManager(); for (ScriptEngineFactory f : scriptEngineManager.getEngineFactories()) { registerEngine(f.getLanguageName().toLowerCase(), f.getScriptEngine()); if (defaultLanguage == null) defaultLanguage = f.getLanguageName(); } if (!engines.containsKey(DEF_LANGUAGE)) { registerEngine(DEF_LANGUAGE, scriptEngineManager.getEngineByName(DEF_LANGUAGE)); defaultLanguage = DEF_LANGUAGE; } if (!engines.containsKey(OSQLScriptEngine.ENGINE)) registerEngine(DEF_LANGUAGE, scriptEngineManager.getEngineByName(DEF_LANGUAGE)); registerFormatter(DEF_LANGUAGE, new OJSScriptFormatter()); registerFormatter("ruby", new ORubyScriptFormatter()); } } public String getFunction(final OFunction iFunction) { final OScriptFormatter formatter = formatters.get(iFunction.getLanguage().toLowerCase()); if (formatter == null) throw new IllegalArgumentException("Cannot find script formatter for the language '" + DEF_LANGUAGE + "'"); return formatter.getFunction(iFunction); } /** * Format the library of functions for a language. * * @param db * Current database instance * @param iLanguage * Language as filter * @return String containing all the functions */ public String getLibrary(final ODatabaseComplex<?> db, final String iLanguage) { final StringBuilder code = new StringBuilder(); final String[] functions = db.getMetadata().getFunctionLibrary().getFunctionNames(); for (String fName : functions) { final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(fName); if (f.getLanguage().equalsIgnoreCase(iLanguage)) { code.append(getFunction(f)); code.append("\n"); } } return code.toString(); } public ScriptEngine getEngine(final String iLanguage) { if (iLanguage == null) throw new OCommandScriptException("No language was specified"); final String lang = iLanguage.toLowerCase(); if (!engines.containsKey(lang)) throw new OCommandScriptException("Unsupported language: " + iLanguage + ". Supported languages are: " + engines); final ScriptEngine scriptEngine = engines.get(lang); if (scriptEngine == null) throw new OCommandScriptException("Cannot find script engine: " + iLanguage); return scriptEngine; } public Bindings bind(final ScriptEngine iEngine, final ODatabaseRecordTx db, final Map<String, Object> iContext, final Map<Object, Object> iArgs) { final Bindings binding = iEngine.createBindings(); for (OScriptInjection i : injections) i.bind(binding); // BIND FIXED VARIABLES binding.put("db", new OScriptDocumentDatabaseWrapper(db)); binding.put("gdb", new OScriptGraphDatabaseWrapper(db)); // BIND CONTEXT VARIABLE INTO THE SCRIPT if (iContext != null) { for (Entry<String, Object> a : iContext.entrySet()) binding.put(a.getKey(), a.getValue()); } // BIND PARAMETERS INTO THE SCRIPT if (iArgs != null) { for (Entry<Object, Object> a : iArgs.entrySet()) binding.put(a.getKey().toString(), a.getValue()); binding.put("params", iArgs); } else binding.put("params", new HashMap<Object, Object>()); return binding; } /** * Unbinds variables * * @param binding */ public void unbind(Bindings binding) { for (OScriptInjection i : injections) i.unbind(binding); } public void registerInjection(final OScriptInjection iInj) { if (!injections.contains(iInj)) injections.add(iInj); } public void unregisterInjection(final OScriptInjection iInj) { injections.remove(iInj); } public OScriptManager registerEngine(final String iLanguage, final ScriptEngine iEngine) { engines.put(iLanguage, iEngine); return this; } public OScriptManager registerFormatter(final String iLanguage, final OScriptFormatter iFormatterImpl) { formatters.put(iLanguage, iFormatterImpl); return this; } }
apache-2.0
knpFletcher/CapstoneProject
ForArtsSake/app/src/main/java/com/karenpownall/android/aca/forartssake/LInks.java
158
package com.karenpownall.android.aca.forartssake; public class Links { @Override public String toString(){ return super.toString(); } }
apache-2.0
dremio/dremio-oss
plugins/elasticsearch/src/main/java/com/dremio/plugins/elastic/planning/functions/UnaryFunction.java
1461
/* * Copyright (C) 2017-2019 Dremio 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 com.dremio.plugins.elastic.planning.functions; import org.apache.calcite.rex.RexCall; import com.google.common.base.Preconditions; public class UnaryFunction extends ElasticFunction { public UnaryFunction(String commonName){ super(commonName, commonName); } public UnaryFunction(String dremioName, String elasticName){ super(dremioName, elasticName); } @Override public FunctionRender render(FunctionRenderer renderer, RexCall call) { Preconditions.checkArgument(call.getOperands().size() == 1, "Unary operation %s should only have one argument, but got %s.", dremioName, call.getOperands().size()); FunctionRender operand = call.getOperands().get(0).accept(renderer.getVisitor()); return new FunctionRender(String.format("%s(%s)", elasticName, operand.getScript()), operand.getNulls()); } }
apache-2.0
McLeodMoores/starling
projects/financial-types/src/main/java/com/opengamma/financial/security/option/SupersharePayoffStyle.java
8151
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.security.option; import java.util.Map; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; /** * The super share payoff style. */ @BeanDefinition public class SupersharePayoffStyle extends PayoffStyle { /** Serialization version. */ private static final long serialVersionUID = 1L; /** * The upper bound. */ @PropertyDefinition private double _lowerBound; /** * The lower bound. */ @PropertyDefinition private double _upperBound; /** * Creates an instance. */ private SupersharePayoffStyle() { } /** * Creates an instance. * * @param upperBound the upper bound * @param lowerBound the lower bound */ public SupersharePayoffStyle(final double upperBound, final double lowerBound) { setUpperBound(upperBound); setLowerBound(lowerBound); } //------------------------------------------------------------------------- @Override public <T> T accept(final PayoffStyleVisitor<T> visitor) { return visitor.visitSupersharePayoffStyle(this); } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code SupersharePayoffStyle}. * @return the meta-bean, not null */ public static SupersharePayoffStyle.Meta meta() { return SupersharePayoffStyle.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(SupersharePayoffStyle.Meta.INSTANCE); } @Override public SupersharePayoffStyle.Meta metaBean() { return SupersharePayoffStyle.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the upper bound. * @return the value of the property */ public double getLowerBound() { return _lowerBound; } /** * Sets the upper bound. * @param lowerBound the new value of the property */ public void setLowerBound(double lowerBound) { this._lowerBound = lowerBound; } /** * Gets the the {@code lowerBound} property. * @return the property, not null */ public final Property<Double> lowerBound() { return metaBean().lowerBound().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the lower bound. * @return the value of the property */ public double getUpperBound() { return _upperBound; } /** * Sets the lower bound. * @param upperBound the new value of the property */ public void setUpperBound(double upperBound) { this._upperBound = upperBound; } /** * Gets the the {@code upperBound} property. * @return the property, not null */ public final Property<Double> upperBound() { return metaBean().upperBound().createProperty(this); } //----------------------------------------------------------------------- @Override public SupersharePayoffStyle clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { SupersharePayoffStyle other = (SupersharePayoffStyle) obj; return JodaBeanUtils.equal(getLowerBound(), other.getLowerBound()) && JodaBeanUtils.equal(getUpperBound(), other.getUpperBound()) && super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; hash = hash * 31 + JodaBeanUtils.hashCode(getLowerBound()); hash = hash * 31 + JodaBeanUtils.hashCode(getUpperBound()); return hash ^ super.hashCode(); } @Override public String toString() { StringBuilder buf = new StringBuilder(96); buf.append("SupersharePayoffStyle{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } @Override protected void toString(StringBuilder buf) { super.toString(buf); buf.append("lowerBound").append('=').append(JodaBeanUtils.toString(getLowerBound())).append(',').append(' '); buf.append("upperBound").append('=').append(JodaBeanUtils.toString(getUpperBound())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code SupersharePayoffStyle}. */ public static class Meta extends PayoffStyle.Meta { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code lowerBound} property. */ private final MetaProperty<Double> _lowerBound = DirectMetaProperty.ofReadWrite( this, "lowerBound", SupersharePayoffStyle.class, Double.TYPE); /** * The meta-property for the {@code upperBound} property. */ private final MetaProperty<Double> _upperBound = DirectMetaProperty.ofReadWrite( this, "upperBound", SupersharePayoffStyle.class, Double.TYPE); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "lowerBound", "upperBound"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 1200084733: // lowerBound return _lowerBound; case -1690761732: // upperBound return _upperBound; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends SupersharePayoffStyle> builder() { return new DirectBeanBuilder<SupersharePayoffStyle>(new SupersharePayoffStyle()); } @Override public Class<? extends SupersharePayoffStyle> beanType() { return SupersharePayoffStyle.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code lowerBound} property. * @return the meta-property, not null */ public final MetaProperty<Double> lowerBound() { return _lowerBound; } /** * The meta-property for the {@code upperBound} property. * @return the meta-property, not null */ public final MetaProperty<Double> upperBound() { return _upperBound; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 1200084733: // lowerBound return ((SupersharePayoffStyle) bean).getLowerBound(); case -1690761732: // upperBound return ((SupersharePayoffStyle) bean).getUpperBound(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case 1200084733: // lowerBound ((SupersharePayoffStyle) bean).setLowerBound((Double) newValue); return; case -1690761732: // upperBound ((SupersharePayoffStyle) bean).setUpperBound((Double) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
apache-2.0
wangxu2013/PCCREDIT_QZ
src/java/com/cardpay/pccredit/intopieces/web/IntoPiecesXingzhengbeginControl.java
10908
package com.cardpay.pccredit.intopieces.web; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.cardpay.pccredit.QZBankInterface.model.Circle; import com.cardpay.pccredit.QZBankInterface.service.CircleService; import com.cardpay.pccredit.QZBankInterface.service.ECIFService; import com.cardpay.pccredit.QZBankInterface.web.IESBForECIFReturnMap; import com.cardpay.pccredit.customer.filter.VideoAccessoriesFilter; import com.cardpay.pccredit.customer.model.CustomerInfor; import com.cardpay.pccredit.customer.service.CustomerInforService; import com.cardpay.pccredit.intopieces.constant.Constant; import com.cardpay.pccredit.intopieces.filter.CustomerApplicationProcessFilter; import com.cardpay.pccredit.intopieces.model.CustomerApplicationInfo; import com.cardpay.pccredit.intopieces.model.CustomerApplicationProcess; import com.cardpay.pccredit.intopieces.model.QzApplnAttachmentList; import com.cardpay.pccredit.intopieces.model.QzApplnJyxx; import com.cardpay.pccredit.intopieces.model.QzApplnNbscyjb; import com.cardpay.pccredit.intopieces.model.VideoAccessories; import com.cardpay.pccredit.intopieces.service.AttachmentListService; import com.cardpay.pccredit.intopieces.service.CustomerApplicationInfoService; import com.cardpay.pccredit.intopieces.service.CustomerApplicationIntopieceWaitService; import com.cardpay.pccredit.intopieces.service.CustomerApplicationProcessService; import com.cardpay.pccredit.intopieces.service.IntoPiecesService; import com.cardpay.pccredit.intopieces.service.JyxxService; import com.cardpay.pccredit.intopieces.service.NbscyjbService; import com.cardpay.workflow.constant.ApproveOperationTypeEnum; import com.wicresoft.jrad.base.auth.IUser; import com.wicresoft.jrad.base.auth.JRadModule; import com.wicresoft.jrad.base.auth.JRadOperation; import com.wicresoft.jrad.base.constant.JRadConstants; import com.wicresoft.jrad.base.database.model.QueryResult; import com.wicresoft.jrad.base.web.JRadModelAndView; import com.wicresoft.jrad.base.web.controller.BaseController; import com.wicresoft.jrad.base.web.result.JRadPagedQueryResult; import com.wicresoft.jrad.base.web.result.JRadReturnMap; import com.wicresoft.jrad.base.web.security.LoginManager; import com.wicresoft.util.spring.Beans; import com.wicresoft.util.spring.mvc.mv.AbstractModelAndView; import com.wicresoft.util.web.RequestHelper; @Controller @RequestMapping("/intopieces/intopiecesxingzheng1/*") @JRadModule("intopieces.intopiecesxingzheng1") public class IntoPiecesXingzhengbeginControl extends BaseController { @Autowired private IntoPiecesService intoPiecesService; @Autowired private CustomerInforService customerInforService; @Autowired private CustomerApplicationIntopieceWaitService customerApplicationIntopieceWaitService; @Autowired private CustomerApplicationProcessService customerApplicationProcessService; @Autowired private CircleService circleService; @Autowired private ECIFService eCIFService; @Autowired private NbscyjbService nbscyjbService; @Autowired private JyxxService jyxxService; @Autowired private AttachmentListService attachmentListService; /** * 行政岗初进件页面 * * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "xingzhengbegin.page", method = { RequestMethod.GET }) public AbstractModelAndView xingzhengbegin(@ModelAttribute CustomerApplicationProcessFilter filter, HttpServletRequest request) throws SQLException { filter.setRequest(request); IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String loginId = user.getId(); filter.setLoginId(loginId); filter.setNodeName(Constant.status_xingzheng1); QueryResult<CustomerApplicationIntopieceWaitForm> result = customerApplicationIntopieceWaitService.recieveIntopieceWaitForm(filter); JRadPagedQueryResult<CustomerApplicationIntopieceWaitForm> pagedResult = new JRadPagedQueryResult<CustomerApplicationIntopieceWaitForm>(filter, result); JRadModelAndView mv = new JRadModelAndView( "/intopieces/intopieces_wait/intopiecesApprove_xingzhengbegin", request); mv.addObject(PAGED_RESULT, pagedResult); mv.addObject("filter", filter); return mv; } /** * 进入上传扫描件页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "create_upload.page") public AbstractModelAndView createUpload(@ModelAttribute VideoAccessoriesFilter filter,HttpServletRequest request) { String appId = request.getParameter("appId"); //是否只读标记 String type = request.getParameter("type"); List<QzDcnrUploadForm> result =intoPiecesService.getUploadList(appId); JRadModelAndView mv = new JRadModelAndView("/intopieces/intopieces_wait/intopiecesApprove_xingzhengbegin_upload", request); mv.addObject("result", result); mv.addObject("appId",appId); mv.addObject("type",type); return mv; } /** * 调查内容保存 * * @param request * @return * @throws IOException */ @ResponseBody @RequestMapping(value = "saveYxzl.json",method = { RequestMethod.POST }) @JRadOperation(JRadOperation.CREATE) public Map<String,Object> saveYxzl(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request,HttpServletResponse response){ Map<String,Object> map = new HashMap<String,Object>(); try { if(file==null||file.isEmpty()){ map.put(JRadConstants.SUCCESS, false); map.put(JRadConstants.MESSAGE, Constant.FILE_EMPTY); return map; } intoPiecesService.saveDcnrByCustomerId(request.getParameter("appId"),request.getParameter("reportId"),request.getParameter("remark"),file); map.put(JRadConstants.SUCCESS, true); map.put(JRadConstants.MESSAGE, Constant.SUCCESS_MESSAGE); } catch (Exception e) { e.printStackTrace(); map.put(JRadConstants.SUCCESS, false); map.put(JRadConstants.MESSAGE, Constant.FAIL_MESSAGE); return map; } return map; } /** * 申请件审批通过 * 从行政岗--授信审批岗 * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "save_apply.json") public JRadReturnMap saveApply(HttpServletRequest request) throws SQLException { JRadReturnMap returnMap = new JRadReturnMap(); try { String appId = request.getParameter("id"); CustomerApplicationProcess process = customerApplicationProcessService.findByAppId(appId); request.setAttribute("serialNumber", process.getSerialNumber()); request.setAttribute("applicationId", process.getApplicationId()); request.setAttribute("applicationStatus", ApproveOperationTypeEnum.APPROVE.toString()); request.setAttribute("objection", "false"); //查找审批金额 Circle circle = circleService.findCircleByAppId(appId); request.setAttribute("examineAmount", circle.getContractAmt()); customerApplicationIntopieceWaitService.updateCustomerApplicationProcessBySerialNumberApplicationInfo1(request); returnMap.addGlobalMessage(CHANGE_SUCCESS); } catch (Exception e) { returnMap.addGlobalMessage("保存失败"); e.printStackTrace(); } return returnMap; } /** * 申请件退件 * 从行政岗--初审 * @param filter * @param request * @return */ @ResponseBody @RequestMapping(value = "returnAppln.json") public JRadReturnMap returnAppln(HttpServletRequest request) throws SQLException { JRadReturnMap returnMap = new JRadReturnMap(); try { String appId = request.getParameter("appId"); String operate = request.getParameter("operate"); String nodeName = request.getParameter("nodeName"); //退回客户经理和其他岗位不一致 if("1".equals(nodeName)){ intoPiecesService.checkDoNotToManager(appId,request); }else{ intoPiecesService.returnAppln(appId, request,nodeName); } returnMap.addGlobalMessage(CHANGE_SUCCESS); } catch (Exception e) { returnMap.addGlobalMessage("保存失败"); e.printStackTrace(); } return returnMap; } /** * 进入电核页面 * * @param request * @return */ @ResponseBody @RequestMapping(value = "in_applove.page") public AbstractModelAndView inApplove(HttpServletRequest request) { String appId = request.getParameter("appId"); String type = request.getParameter("type"); JRadModelAndView mv = new JRadModelAndView("/qzbankinterface/appIframeInfo/page7_change", request); QzApplnNbscyjb qzApplnNbscyjb = nbscyjbService.findNbscyjbByAppId(appId); mv = new JRadModelAndView("/qzbankinterface/appIframeInfo/page7_for_approve", request); mv.addObject("qzApplnNbscyjb", qzApplnNbscyjb); mv.addObject("type", type); CustomerInfor customerInfo = customerInforService.findCustomerInforById(intoPiecesService.findCustomerApplicationInfoByApplicationId(appId).getCustomerId()); mv.addObject("customerInfo", customerInfo); //修改为appid查询 QzApplnJyxx qzApplnJyxx = jyxxService.findJyxx(customerInfo.getId(), null); mv.addObject("qzApplnJyxx", qzApplnJyxx); IUser user = Beans.get(LoginManager.class).getLoggedInUser(request); String loginId = user.getLogin(); String displayName = user.getDisplayName(); mv.addObject("displayName", displayName); mv.addObject("loginId", loginId); return mv; } //iframe_approve(申请后) @ResponseBody @RequestMapping(value = "iframe_approve.page") public AbstractModelAndView iframeApprove(HttpServletRequest request) { JRadModelAndView mv = new JRadModelAndView("/qzbankinterface/appIframeInfo/iframe_approve", request); String customerInforId = RequestHelper.getStringValue(request, ID); String appId = RequestHelper.getStringValue(request, "appId"); if (StringUtils.isNotEmpty(customerInforId)) { CustomerInfor customerInfor = customerInforService.findCustomerInforById(customerInforId); mv.addObject("customerInfor", customerInfor); mv.addObject("customerId", customerInfor.getId()); mv.addObject("appId", appId); mv.addObject("operate", Constant.status_xingzheng1); } return mv; } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/ListTagsResult.java
4500
/* * Copyright 2012-2017 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.lambda.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/ListTags" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListTagsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The list of tags assigned to the function. * </p> */ private com.amazonaws.internal.SdkInternalMap<String, String> tags; /** * <p> * The list of tags assigned to the function. * </p> * * @return The list of tags assigned to the function. */ public java.util.Map<String, String> getTags() { if (tags == null) { tags = new com.amazonaws.internal.SdkInternalMap<String, String>(); } return tags; } /** * <p> * The list of tags assigned to the function. * </p> * * @param tags * The list of tags assigned to the function. */ public void setTags(java.util.Map<String, String> tags) { this.tags = tags == null ? null : new com.amazonaws.internal.SdkInternalMap<String, String>(tags); } /** * <p> * The list of tags assigned to the function. * </p> * * @param tags * The list of tags assigned to the function. * @return Returns a reference to this object so that method calls can be chained together. */ public ListTagsResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; } public ListTagsResult addTagsEntry(String key, String value) { if (null == this.tags) { this.tags = new com.amazonaws.internal.SdkInternalMap<String, String>(); } if (this.tags.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.tags.put(key, value); return this; } /** * Removes all the entries added into Tags. * * @return Returns a reference to this object so that method calls can be chained together. */ public ListTagsResult clearTagsEntries() { this.tags = null; return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListTagsResult == false) return false; ListTagsResult other = (ListTagsResult) obj; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public ListTagsResult clone() { try { return (ListTagsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
unipop-graph/unipop
unipop-core/src/org/unipop/process/strategyregistrar/StandardStrategyProvider.java
1536
package org.unipop.process.strategyregistrar; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies; import org.apache.tinkerpop.gremlin.process.traversal.util.DefaultTraversalStrategies; import org.apache.tinkerpop.gremlin.structure.Graph; import org.unipop.process.coalesce.UniGraphCoalesceStepStrategy; import org.unipop.process.edge.EdgeStepsStrategy; import org.unipop.process.order.UniGraphOrderStrategy; import org.unipop.process.properties.UniGraphPropertiesStrategy; import org.unipop.process.repeat.UniGraphRepeatStepStrategy; import org.unipop.process.graph.UniGraphStepStrategy; import org.unipop.process.vertex.UniGraphVertexStepStrategy; import org.unipop.process.where.UniGraphWhereStepStrategy; public class StandardStrategyProvider implements StrategyProvider { @Override public TraversalStrategies get() { DefaultTraversalStrategies traversalStrategies = new DefaultTraversalStrategies(); traversalStrategies.addStrategies( new UniGraphStepStrategy(), new UniGraphVertexStepStrategy(), new EdgeStepsStrategy(), new UniGraphPropertiesStrategy(), new UniGraphCoalesceStepStrategy(), new UniGraphWhereStepStrategy(), new UniGraphRepeatStepStrategy(), new UniGraphOrderStrategy()); TraversalStrategies.GlobalCache.getStrategies(Graph.class).toList().forEach(traversalStrategies::addStrategies); return traversalStrategies; } }
apache-2.0
pepoc/Joke
Joke/app/src/main/java/com/pepoc/joke/view/activity/JokeContentActivity.java
4698
package com.pepoc.joke.view.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Toast; import com.pepoc.joke.R; import com.pepoc.joke.data.bean.JokeComment; import com.pepoc.joke.data.bean.JokeContent; import com.pepoc.joke.data.user.UserManager; import com.pepoc.joke.presenter.JokeContentPresenter; import com.pepoc.joke.util.Util; import com.pepoc.joke.view.adapter.JokeContentAdapter; import com.pepoc.joke.view.iview.IJokeContentView; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class JokeContentActivity extends BaseSwipeBackActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, IJokeContentView<JokeComment> { @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.recyclerview_joke_content) RecyclerView recyclerviewJokeContent; @Bind(R.id.swiperefresh_joke_content) SwipeRefreshLayout swiperefreshJokeContent; @Bind(R.id.et_joke_comment) EditText etJokeComment; @Bind(R.id.btn_send_comment) Button btnSendComment; @Bind(R.id.rl_comment) RelativeLayout rlComment; private JokeContent jokeContent; private JokeContentAdapter jokeContentAdapter; private JokeContentPresenter jokeContentPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_joke_content); ButterKnife.bind(this); jokeContentPresenter = new JokeContentPresenter(this); Intent intent = getIntent(); jokeContent = intent.getParcelableExtra("JokeContent"); init(); jokeContentPresenter.getComment(context, jokeContent.getJokeId()); } @Override public void init() { super.init(); toolbar.setTitle(R.string.activity_joke_content); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); swiperefreshJokeContent.setColorSchemeResources(R.color.colorAccent); swiperefreshJokeContent.setOnRefreshListener(this); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context); recyclerviewJokeContent.setLayoutManager(linearLayoutManager); jokeContentAdapter = new JokeContentAdapter(context, jokeContentPresenter); jokeContentAdapter.setJokeContent(jokeContent); recyclerviewJokeContent.setAdapter(jokeContentAdapter); btnSendComment.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_send_comment: if (UserManager.getCurrentUser() != null) { String commentContent = etJokeComment.getText().toString(); if (TextUtils.isEmpty(commentContent)) { Toast.makeText(context, "评论内容不能为空", Toast.LENGTH_SHORT).show(); } else { jokeContentPresenter.comment(context, jokeContent.getJokeId(), commentContent); } } else { Toast.makeText(context, "登录后才能评论", Toast.LENGTH_SHORT).show(); } break; } } @Override public void onRefresh() { jokeContentPresenter.getComment(context, jokeContent.getJokeId()); } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void updateCommentData(List<JokeComment> datas) { swiperefreshJokeContent.setRefreshing(false); jokeContentAdapter.setJokeComments(datas); jokeContentAdapter.notifyDataSetChanged(); } @Override public void commentSuccess() { Toast.makeText(context, "comment success", Toast.LENGTH_SHORT).show(); etJokeComment.setText(""); Util.hiddenSoftKeyborad(etJokeComment, context); jokeContentPresenter.getComment(context, jokeContent.getJokeId()); } @Override public void onError() { swiperefreshJokeContent.setRefreshing(false); } }
apache-2.0
icecp/icecp
icecp-node/src/main/java/com/intel/icecp/node/security/crypto/utils/CryptoUtils.java
5374
/* * Copyright (c) 2017 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 com.intel.icecp.node.security.crypto.utils; import com.intel.icecp.core.security.crypto.key.Key; import com.intel.icecp.core.security.crypto.exception.hash.HashError; import com.intel.icecp.core.security.crypto.exception.key.InvalidKeyTypeException; import com.intel.icecp.node.security.SecurityConstants; import com.intel.icecp.core.security.crypto.key.asymmetric.PrivateKey; import com.intel.icecp.core.security.crypto.key.asymmetric.PublicKey; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; /** * Collection of utility methods, used by crypto package classes * */ public class CryptoUtils { private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); /** * Computes an hash of the given input, using the specified algorithm. * * @param input * @param algorithm * @return The hash value, if the algorithm is supported * @throws HashError if something went wrong */ public static byte[] hash(byte[] input, String algorithm) throws HashError { try { MessageDigest m = MessageDigest.getInstance(algorithm); m.update(input); return m.digest(); } catch (NoSuchAlgorithmException ex) { throw new HashError("Unable to compute the hash of the given input.", ex); } } /** * Converts a given byte array into a HEX String representation * * @param bytes bytes to convert into HEX string * @return The corresponding HEX string */ public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } /** * Converts a HEX string into bytes * * @param hexString HEX String to convert into bytes * @return The corresponding bytes */ public static byte[] hexStringToByteArray(String hexString) { int len = hexString.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16)); } return data; } /** * Base64 encoding using {@link Base64#getEncoder() } encoder * * @param data Data to encode * @return The Base64 encoded String * @throws IllegalArgumentException In case of error while encoding the given bytes */ public static byte[] base64Encode(byte[] data) throws IllegalArgumentException { return Base64.getEncoder().encode(data); } /** * Base64 decoding using {@link Base64#getDecoder() } decoder * * @param data Data to decode * @return The decoded bytes * @throws IllegalArgumentException In case of error in decoding the given bytes */ public static byte[] base64Decode(byte[] data) throws IllegalArgumentException { return Base64.getDecoder().decode(data); } /** * Compares the given two byte arrays * * @param first * @param second * @return True iif first == true */ public static boolean compareBytes(byte[] first, byte[] second) { return MessageDigest.isEqual(first, second); } /** * Given a key, returns a suitable signing algorithm (if exists). * * @param key * @return * @throws InvalidKeyTypeException */ public static String getPublicKeyAlgorithmFromKey(Key key) throws InvalidKeyTypeException { String keyType; if (key instanceof PrivateKey) { PrivateKey k = (PrivateKey) key; keyType = k.getKey().getAlgorithm(); } else if (key instanceof PublicKey) { PublicKey k = (PublicKey) key; keyType = k.getPublicKey().getAlgorithm(); } else { // All other types of keys are not valid asymmetric keys throw new InvalidKeyTypeException("Invalid key type " + key.getClass().getName()); } System.out.println("********" + keyType); if (SecurityConstants.SHA1withDSA.contains(keyType)) { return SecurityConstants.SHA1withDSA; } else if (SecurityConstants.SHA1withRSA.contains(keyType)) { return SecurityConstants.SHA1withRSA; } else if (SecurityConstants.SHA256withRSA.contains(keyType)) { return SecurityConstants.SHA256withRSA; } throw new InvalidKeyTypeException("Invalid key type " + keyType); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/JourneyExecutionActivityMetricsResponse.java
26522
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.pinpoint.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Provides the results of a query that retrieved the data for a standard execution metric that applies to a journey * activity, and provides information about that query. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/JourneyExecutionActivityMetricsResponse" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class JourneyExecutionActivityMetricsResponse implements Serializable, Cloneable, StructuredPojo { /** * <p> * The type of activity that the metric applies to. Possible values are: * </p> * <ul> * <li> * <p> * CONDITIONAL_SPLIT - For a yes/no split activity, which is an activity that sends participants down one of two * paths in a journey. * </p> * </li> * <li> * <p> * HOLDOUT - For a holdout activity, which is an activity that stops a journey for a specified percentage of * participants. * </p> * </li> * <li> * <p> * MESSAGE - For an email activity, which is an activity that sends an email message to participants. * </p> * </li> * <li> * <p> * MULTI_CONDITIONAL_SPLIT - For a multivariate split activity, which is an activity that sends participants down * one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * RANDOM_SPLIT - For a random split activity, which is an activity that sends specified percentages of participants * down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * WAIT - For a wait activity, which is an activity that waits for a certain amount of time or until a specific date * and time before moving participants to the next activity in a journey. * </p> * </li> * </ul> */ private String activityType; /** * <p> * The unique identifier for the application that the metric applies to. * </p> */ private String applicationId; /** * <p> * The unique identifier for the activity that the metric applies to. * </p> */ private String journeyActivityId; /** * <p> * The unique identifier for the journey that the metric applies to. * </p> */ private String journeyId; /** * <p> * The date and time, in ISO 8601 format, when Amazon Pinpoint last evaluated the execution status of the activity * and updated the data for the metric. * </p> */ private String lastEvaluatedTime; /** * <p> * A JSON object that contains the results of the query. The results vary depending on the type of activity * (ActivityType). For information about the structure and contents of the results, see the <a * href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html">Amazon Pinpoint * Developer Guide</a>. * </p> */ private java.util.Map<String, String> metrics; /** * <p> * The type of activity that the metric applies to. Possible values are: * </p> * <ul> * <li> * <p> * CONDITIONAL_SPLIT - For a yes/no split activity, which is an activity that sends participants down one of two * paths in a journey. * </p> * </li> * <li> * <p> * HOLDOUT - For a holdout activity, which is an activity that stops a journey for a specified percentage of * participants. * </p> * </li> * <li> * <p> * MESSAGE - For an email activity, which is an activity that sends an email message to participants. * </p> * </li> * <li> * <p> * MULTI_CONDITIONAL_SPLIT - For a multivariate split activity, which is an activity that sends participants down * one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * RANDOM_SPLIT - For a random split activity, which is an activity that sends specified percentages of participants * down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * WAIT - For a wait activity, which is an activity that waits for a certain amount of time or until a specific date * and time before moving participants to the next activity in a journey. * </p> * </li> * </ul> * * @param activityType * The type of activity that the metric applies to. Possible values are:</p> * <ul> * <li> * <p> * CONDITIONAL_SPLIT - For a yes/no split activity, which is an activity that sends participants down one of * two paths in a journey. * </p> * </li> * <li> * <p> * HOLDOUT - For a holdout activity, which is an activity that stops a journey for a specified percentage of * participants. * </p> * </li> * <li> * <p> * MESSAGE - For an email activity, which is an activity that sends an email message to participants. * </p> * </li> * <li> * <p> * MULTI_CONDITIONAL_SPLIT - For a multivariate split activity, which is an activity that sends participants * down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * RANDOM_SPLIT - For a random split activity, which is an activity that sends specified percentages of * participants down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * WAIT - For a wait activity, which is an activity that waits for a certain amount of time or until a * specific date and time before moving participants to the next activity in a journey. * </p> * </li> */ public void setActivityType(String activityType) { this.activityType = activityType; } /** * <p> * The type of activity that the metric applies to. Possible values are: * </p> * <ul> * <li> * <p> * CONDITIONAL_SPLIT - For a yes/no split activity, which is an activity that sends participants down one of two * paths in a journey. * </p> * </li> * <li> * <p> * HOLDOUT - For a holdout activity, which is an activity that stops a journey for a specified percentage of * participants. * </p> * </li> * <li> * <p> * MESSAGE - For an email activity, which is an activity that sends an email message to participants. * </p> * </li> * <li> * <p> * MULTI_CONDITIONAL_SPLIT - For a multivariate split activity, which is an activity that sends participants down * one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * RANDOM_SPLIT - For a random split activity, which is an activity that sends specified percentages of participants * down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * WAIT - For a wait activity, which is an activity that waits for a certain amount of time or until a specific date * and time before moving participants to the next activity in a journey. * </p> * </li> * </ul> * * @return The type of activity that the metric applies to. Possible values are:</p> * <ul> * <li> * <p> * CONDITIONAL_SPLIT - For a yes/no split activity, which is an activity that sends participants down one of * two paths in a journey. * </p> * </li> * <li> * <p> * HOLDOUT - For a holdout activity, which is an activity that stops a journey for a specified percentage of * participants. * </p> * </li> * <li> * <p> * MESSAGE - For an email activity, which is an activity that sends an email message to participants. * </p> * </li> * <li> * <p> * MULTI_CONDITIONAL_SPLIT - For a multivariate split activity, which is an activity that sends participants * down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * RANDOM_SPLIT - For a random split activity, which is an activity that sends specified percentages of * participants down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * WAIT - For a wait activity, which is an activity that waits for a certain amount of time or until a * specific date and time before moving participants to the next activity in a journey. * </p> * </li> */ public String getActivityType() { return this.activityType; } /** * <p> * The type of activity that the metric applies to. Possible values are: * </p> * <ul> * <li> * <p> * CONDITIONAL_SPLIT - For a yes/no split activity, which is an activity that sends participants down one of two * paths in a journey. * </p> * </li> * <li> * <p> * HOLDOUT - For a holdout activity, which is an activity that stops a journey for a specified percentage of * participants. * </p> * </li> * <li> * <p> * MESSAGE - For an email activity, which is an activity that sends an email message to participants. * </p> * </li> * <li> * <p> * MULTI_CONDITIONAL_SPLIT - For a multivariate split activity, which is an activity that sends participants down * one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * RANDOM_SPLIT - For a random split activity, which is an activity that sends specified percentages of participants * down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * WAIT - For a wait activity, which is an activity that waits for a certain amount of time or until a specific date * and time before moving participants to the next activity in a journey. * </p> * </li> * </ul> * * @param activityType * The type of activity that the metric applies to. Possible values are:</p> * <ul> * <li> * <p> * CONDITIONAL_SPLIT - For a yes/no split activity, which is an activity that sends participants down one of * two paths in a journey. * </p> * </li> * <li> * <p> * HOLDOUT - For a holdout activity, which is an activity that stops a journey for a specified percentage of * participants. * </p> * </li> * <li> * <p> * MESSAGE - For an email activity, which is an activity that sends an email message to participants. * </p> * </li> * <li> * <p> * MULTI_CONDITIONAL_SPLIT - For a multivariate split activity, which is an activity that sends participants * down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * RANDOM_SPLIT - For a random split activity, which is an activity that sends specified percentages of * participants down one of as many as five paths in a journey. * </p> * </li> * <li> * <p> * WAIT - For a wait activity, which is an activity that waits for a certain amount of time or until a * specific date and time before moving participants to the next activity in a journey. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse withActivityType(String activityType) { setActivityType(activityType); return this; } /** * <p> * The unique identifier for the application that the metric applies to. * </p> * * @param applicationId * The unique identifier for the application that the metric applies to. */ public void setApplicationId(String applicationId) { this.applicationId = applicationId; } /** * <p> * The unique identifier for the application that the metric applies to. * </p> * * @return The unique identifier for the application that the metric applies to. */ public String getApplicationId() { return this.applicationId; } /** * <p> * The unique identifier for the application that the metric applies to. * </p> * * @param applicationId * The unique identifier for the application that the metric applies to. * @return Returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse withApplicationId(String applicationId) { setApplicationId(applicationId); return this; } /** * <p> * The unique identifier for the activity that the metric applies to. * </p> * * @param journeyActivityId * The unique identifier for the activity that the metric applies to. */ public void setJourneyActivityId(String journeyActivityId) { this.journeyActivityId = journeyActivityId; } /** * <p> * The unique identifier for the activity that the metric applies to. * </p> * * @return The unique identifier for the activity that the metric applies to. */ public String getJourneyActivityId() { return this.journeyActivityId; } /** * <p> * The unique identifier for the activity that the metric applies to. * </p> * * @param journeyActivityId * The unique identifier for the activity that the metric applies to. * @return Returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse withJourneyActivityId(String journeyActivityId) { setJourneyActivityId(journeyActivityId); return this; } /** * <p> * The unique identifier for the journey that the metric applies to. * </p> * * @param journeyId * The unique identifier for the journey that the metric applies to. */ public void setJourneyId(String journeyId) { this.journeyId = journeyId; } /** * <p> * The unique identifier for the journey that the metric applies to. * </p> * * @return The unique identifier for the journey that the metric applies to. */ public String getJourneyId() { return this.journeyId; } /** * <p> * The unique identifier for the journey that the metric applies to. * </p> * * @param journeyId * The unique identifier for the journey that the metric applies to. * @return Returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse withJourneyId(String journeyId) { setJourneyId(journeyId); return this; } /** * <p> * The date and time, in ISO 8601 format, when Amazon Pinpoint last evaluated the execution status of the activity * and updated the data for the metric. * </p> * * @param lastEvaluatedTime * The date and time, in ISO 8601 format, when Amazon Pinpoint last evaluated the execution status of the * activity and updated the data for the metric. */ public void setLastEvaluatedTime(String lastEvaluatedTime) { this.lastEvaluatedTime = lastEvaluatedTime; } /** * <p> * The date and time, in ISO 8601 format, when Amazon Pinpoint last evaluated the execution status of the activity * and updated the data for the metric. * </p> * * @return The date and time, in ISO 8601 format, when Amazon Pinpoint last evaluated the execution status of the * activity and updated the data for the metric. */ public String getLastEvaluatedTime() { return this.lastEvaluatedTime; } /** * <p> * The date and time, in ISO 8601 format, when Amazon Pinpoint last evaluated the execution status of the activity * and updated the data for the metric. * </p> * * @param lastEvaluatedTime * The date and time, in ISO 8601 format, when Amazon Pinpoint last evaluated the execution status of the * activity and updated the data for the metric. * @return Returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse withLastEvaluatedTime(String lastEvaluatedTime) { setLastEvaluatedTime(lastEvaluatedTime); return this; } /** * <p> * A JSON object that contains the results of the query. The results vary depending on the type of activity * (ActivityType). For information about the structure and contents of the results, see the <a * href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html">Amazon Pinpoint * Developer Guide</a>. * </p> * * @return A JSON object that contains the results of the query. The results vary depending on the type of activity * (ActivityType). For information about the structure and contents of the results, see the <a * href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html">Amazon * Pinpoint Developer Guide</a>. */ public java.util.Map<String, String> getMetrics() { return metrics; } /** * <p> * A JSON object that contains the results of the query. The results vary depending on the type of activity * (ActivityType). For information about the structure and contents of the results, see the <a * href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html">Amazon Pinpoint * Developer Guide</a>. * </p> * * @param metrics * A JSON object that contains the results of the query. The results vary depending on the type of activity * (ActivityType). For information about the structure and contents of the results, see the <a * href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html">Amazon * Pinpoint Developer Guide</a>. */ public void setMetrics(java.util.Map<String, String> metrics) { this.metrics = metrics; } /** * <p> * A JSON object that contains the results of the query. The results vary depending on the type of activity * (ActivityType). For information about the structure and contents of the results, see the <a * href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html">Amazon Pinpoint * Developer Guide</a>. * </p> * * @param metrics * A JSON object that contains the results of the query. The results vary depending on the type of activity * (ActivityType). For information about the structure and contents of the results, see the <a * href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html">Amazon * Pinpoint Developer Guide</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse withMetrics(java.util.Map<String, String> metrics) { setMetrics(metrics); return this; } /** * Add a single Metrics entry * * @see JourneyExecutionActivityMetricsResponse#withMetrics * @returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse addMetricsEntry(String key, String value) { if (null == this.metrics) { this.metrics = new java.util.HashMap<String, String>(); } if (this.metrics.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.metrics.put(key, value); return this; } /** * Removes all the entries added into Metrics. * * @return Returns a reference to this object so that method calls can be chained together. */ public JourneyExecutionActivityMetricsResponse clearMetricsEntries() { this.metrics = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getActivityType() != null) sb.append("ActivityType: ").append(getActivityType()).append(","); if (getApplicationId() != null) sb.append("ApplicationId: ").append(getApplicationId()).append(","); if (getJourneyActivityId() != null) sb.append("JourneyActivityId: ").append(getJourneyActivityId()).append(","); if (getJourneyId() != null) sb.append("JourneyId: ").append(getJourneyId()).append(","); if (getLastEvaluatedTime() != null) sb.append("LastEvaluatedTime: ").append(getLastEvaluatedTime()).append(","); if (getMetrics() != null) sb.append("Metrics: ").append(getMetrics()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof JourneyExecutionActivityMetricsResponse == false) return false; JourneyExecutionActivityMetricsResponse other = (JourneyExecutionActivityMetricsResponse) obj; if (other.getActivityType() == null ^ this.getActivityType() == null) return false; if (other.getActivityType() != null && other.getActivityType().equals(this.getActivityType()) == false) return false; if (other.getApplicationId() == null ^ this.getApplicationId() == null) return false; if (other.getApplicationId() != null && other.getApplicationId().equals(this.getApplicationId()) == false) return false; if (other.getJourneyActivityId() == null ^ this.getJourneyActivityId() == null) return false; if (other.getJourneyActivityId() != null && other.getJourneyActivityId().equals(this.getJourneyActivityId()) == false) return false; if (other.getJourneyId() == null ^ this.getJourneyId() == null) return false; if (other.getJourneyId() != null && other.getJourneyId().equals(this.getJourneyId()) == false) return false; if (other.getLastEvaluatedTime() == null ^ this.getLastEvaluatedTime() == null) return false; if (other.getLastEvaluatedTime() != null && other.getLastEvaluatedTime().equals(this.getLastEvaluatedTime()) == false) return false; if (other.getMetrics() == null ^ this.getMetrics() == null) return false; if (other.getMetrics() != null && other.getMetrics().equals(this.getMetrics()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getActivityType() == null) ? 0 : getActivityType().hashCode()); hashCode = prime * hashCode + ((getApplicationId() == null) ? 0 : getApplicationId().hashCode()); hashCode = prime * hashCode + ((getJourneyActivityId() == null) ? 0 : getJourneyActivityId().hashCode()); hashCode = prime * hashCode + ((getJourneyId() == null) ? 0 : getJourneyId().hashCode()); hashCode = prime * hashCode + ((getLastEvaluatedTime() == null) ? 0 : getLastEvaluatedTime().hashCode()); hashCode = prime * hashCode + ((getMetrics() == null) ? 0 : getMetrics().hashCode()); return hashCode; } @Override public JourneyExecutionActivityMetricsResponse clone() { try { return (JourneyExecutionActivityMetricsResponse) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.pinpoint.model.transform.JourneyExecutionActivityMetricsResponseMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
GerritCodeReview/gwtjsonrpc
src/main/java/com/google/gwtjsonrpc/client/impl/ser/ObjectSerializer.java
1544
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gwtjsonrpc.client.impl.ser; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwtjsonrpc.client.impl.JsonSerializer; import com.google.gwtjsonrpc.client.impl.ResultDeserializer; /** Base class for generated JsonSerializer implementations. */ public abstract class ObjectSerializer<T extends Object> extends JsonSerializer<T> implements ResultDeserializer<T> { @Override public void printJson(final StringBuilder sb, final Object o) { sb.append("{"); printJsonImpl(0, sb, o); sb.append("}"); } protected abstract int printJsonImpl(int field, StringBuilder sb, Object o); @Override public T fromResult(JavaScriptObject responseObject) { final JavaScriptObject result = objectResult(responseObject); return result == null ? null : fromJson(result); } static native JavaScriptObject objectResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/ ; }
apache-2.0
francisliu/hbase
hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/TRowMutations.java
18133
/** * Autogenerated by Thrift Compiler (0.13.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hbase.thrift2.generated; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) /** * A TRowMutations object is used to apply a number of Mutations to a single row. */ @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.13.0)", date = "2020-04-01") public class TRowMutations implements org.apache.thrift.TBase<TRowMutations, TRowMutations._Fields>, java.io.Serializable, Cloneable, Comparable<TRowMutations> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TRowMutations"); private static final org.apache.thrift.protocol.TField ROW_FIELD_DESC = new org.apache.thrift.protocol.TField("row", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField MUTATIONS_FIELD_DESC = new org.apache.thrift.protocol.TField("mutations", org.apache.thrift.protocol.TType.LIST, (short)2); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new TRowMutationsStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new TRowMutationsTupleSchemeFactory(); public @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer row; // required public @org.apache.thrift.annotation.Nullable java.util.List<TMutation> mutations; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ROW((short)1, "row"), MUTATIONS((short)2, "mutations"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ROW return ROW; case 2: // MUTATIONS return MUTATIONS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ROW, new org.apache.thrift.meta_data.FieldMetaData("row", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.MUTATIONS, new org.apache.thrift.meta_data.FieldMetaData("mutations", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TMutation.class)))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TRowMutations.class, metaDataMap); } public TRowMutations() { } public TRowMutations( java.nio.ByteBuffer row, java.util.List<TMutation> mutations) { this(); this.row = org.apache.thrift.TBaseHelper.copyBinary(row); this.mutations = mutations; } /** * Performs a deep copy on <i>other</i>. */ public TRowMutations(TRowMutations other) { if (other.isSetRow()) { this.row = org.apache.thrift.TBaseHelper.copyBinary(other.row); } if (other.isSetMutations()) { java.util.List<TMutation> __this__mutations = new java.util.ArrayList<TMutation>(other.mutations.size()); for (TMutation other_element : other.mutations) { __this__mutations.add(new TMutation(other_element)); } this.mutations = __this__mutations; } } public TRowMutations deepCopy() { return new TRowMutations(this); } @Override public void clear() { this.row = null; this.mutations = null; } public byte[] getRow() { setRow(org.apache.thrift.TBaseHelper.rightSize(row)); return row == null ? null : row.array(); } public java.nio.ByteBuffer bufferForRow() { return org.apache.thrift.TBaseHelper.copyBinary(row); } public TRowMutations setRow(byte[] row) { this.row = row == null ? (java.nio.ByteBuffer)null : java.nio.ByteBuffer.wrap(row.clone()); return this; } public TRowMutations setRow(@org.apache.thrift.annotation.Nullable java.nio.ByteBuffer row) { this.row = org.apache.thrift.TBaseHelper.copyBinary(row); return this; } public void unsetRow() { this.row = null; } /** Returns true if field row is set (has been assigned a value) and false otherwise */ public boolean isSetRow() { return this.row != null; } public void setRowIsSet(boolean value) { if (!value) { this.row = null; } } public int getMutationsSize() { return (this.mutations == null) ? 0 : this.mutations.size(); } @org.apache.thrift.annotation.Nullable public java.util.Iterator<TMutation> getMutationsIterator() { return (this.mutations == null) ? null : this.mutations.iterator(); } public void addToMutations(TMutation elem) { if (this.mutations == null) { this.mutations = new java.util.ArrayList<TMutation>(); } this.mutations.add(elem); } @org.apache.thrift.annotation.Nullable public java.util.List<TMutation> getMutations() { return this.mutations; } public TRowMutations setMutations(@org.apache.thrift.annotation.Nullable java.util.List<TMutation> mutations) { this.mutations = mutations; return this; } public void unsetMutations() { this.mutations = null; } /** Returns true if field mutations is set (has been assigned a value) and false otherwise */ public boolean isSetMutations() { return this.mutations != null; } public void setMutationsIsSet(boolean value) { if (!value) { this.mutations = null; } } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case ROW: if (value == null) { unsetRow(); } else { if (value instanceof byte[]) { setRow((byte[])value); } else { setRow((java.nio.ByteBuffer)value); } } break; case MUTATIONS: if (value == null) { unsetMutations(); } else { setMutations((java.util.List<TMutation>)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case ROW: return getRow(); case MUTATIONS: return getMutations(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case ROW: return isSetRow(); case MUTATIONS: return isSetMutations(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that == null) return false; if (that instanceof TRowMutations) return this.equals((TRowMutations)that); return false; } public boolean equals(TRowMutations that) { if (that == null) return false; if (this == that) return true; boolean this_present_row = true && this.isSetRow(); boolean that_present_row = true && that.isSetRow(); if (this_present_row || that_present_row) { if (!(this_present_row && that_present_row)) return false; if (!this.row.equals(that.row)) return false; } boolean this_present_mutations = true && this.isSetMutations(); boolean that_present_mutations = true && that.isSetMutations(); if (this_present_mutations || that_present_mutations) { if (!(this_present_mutations && that_present_mutations)) return false; if (!this.mutations.equals(that.mutations)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetRow()) ? 131071 : 524287); if (isSetRow()) hashCode = hashCode * 8191 + row.hashCode(); hashCode = hashCode * 8191 + ((isSetMutations()) ? 131071 : 524287); if (isSetMutations()) hashCode = hashCode * 8191 + mutations.hashCode(); return hashCode; } @Override public int compareTo(TRowMutations other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.valueOf(isSetRow()).compareTo(other.isSetRow()); if (lastComparison != 0) { return lastComparison; } if (isSetRow()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.row, other.row); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(isSetMutations()).compareTo(other.isSetMutations()); if (lastComparison != 0) { return lastComparison; } if (isSetMutations()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.mutations, other.mutations); if (lastComparison != 0) { return lastComparison; } } return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("TRowMutations("); boolean first = true; sb.append("row:"); if (this.row == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.row, sb); } first = false; if (!first) sb.append(", "); sb.append("mutations:"); if (this.mutations == null) { sb.append("null"); } else { sb.append(this.mutations); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (row == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'row' was not present! Struct: " + toString()); } if (mutations == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'mutations' was not present! Struct: " + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class TRowMutationsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TRowMutationsStandardScheme getScheme() { return new TRowMutationsStandardScheme(); } } private static class TRowMutationsStandardScheme extends org.apache.thrift.scheme.StandardScheme<TRowMutations> { public void read(org.apache.thrift.protocol.TProtocol iprot, TRowMutations struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ROW if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.row = iprot.readBinary(); struct.setRowIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // MUTATIONS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list134 = iprot.readListBegin(); struct.mutations = new java.util.ArrayList<TMutation>(_list134.size); @org.apache.thrift.annotation.Nullable TMutation _elem135; for (int _i136 = 0; _i136 < _list134.size; ++_i136) { _elem135 = new TMutation(); _elem135.read(iprot); struct.mutations.add(_elem135); } iprot.readListEnd(); } struct.setMutationsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, TRowMutations struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.row != null) { oprot.writeFieldBegin(ROW_FIELD_DESC); oprot.writeBinary(struct.row); oprot.writeFieldEnd(); } if (struct.mutations != null) { oprot.writeFieldBegin(MUTATIONS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.mutations.size())); for (TMutation _iter137 : struct.mutations) { _iter137.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class TRowMutationsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TRowMutationsTupleScheme getScheme() { return new TRowMutationsTupleScheme(); } } private static class TRowMutationsTupleScheme extends org.apache.thrift.scheme.TupleScheme<TRowMutations> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, TRowMutations struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; oprot.writeBinary(struct.row); { oprot.writeI32(struct.mutations.size()); for (TMutation _iter138 : struct.mutations) { _iter138.write(oprot); } } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, TRowMutations struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; struct.row = iprot.readBinary(); struct.setRowIsSet(true); { org.apache.thrift.protocol.TList _list139 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.mutations = new java.util.ArrayList<TMutation>(_list139.size); @org.apache.thrift.annotation.Nullable TMutation _elem140; for (int _i141 = 0; _i141 < _list139.size; ++_i141) { _elem140 = new TMutation(); _elem140.read(iprot); struct.mutations.add(_elem140); } } struct.setMutationsIsSet(true); } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
apache-2.0
fkeglevich/Raw-Dumper
app/src/main/java/com/fkeglevich/rawdumper/camera/feature/RangeFeature.java
1858
/* * Copyright 2018, Flávio Keglevich * * 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.fkeglevich.rawdumper.camera.feature; import com.fkeglevich.rawdumper.camera.async.direct.AsyncParameterSender; import com.fkeglevich.rawdumper.camera.data.DataRange; import com.fkeglevich.rawdumper.camera.parameter.Parameter; import com.fkeglevich.rawdumper.camera.parameter.ParameterCollection; import com.fkeglevich.rawdumper.camera.parameter.value.ValueValidator; /** * TODO: Add class header * * Created by Flávio Keglevich on 09/05/17. */ public abstract class RangeFeature<T extends Comparable<T>> extends WritableFeature<T, DataRange<T>> { private final AsyncParameterSender asyncParameterSender; RangeFeature(AsyncParameterSender asyncParameterSender, Parameter<T> featureParameter, ParameterCollection parameterCollection, ValueValidator<T, DataRange<T>> validator) { super(featureParameter, parameterCollection, validator); this.asyncParameterSender = asyncParameterSender; } public abstract void setValueAsProportion(double proportion); void setValueAsync(T value) { checkFeatureAvailability(this); if (!getValidator().isValid(value)) throw new IllegalArgumentException(); asyncParameterSender.sendParameterAsync(parameter, value); } }
apache-2.0
xukun0217/wayMQ
wayMQ-droid/src/ananas/waymq/droid/api/ICoreApi.java
168
package ananas.waymq.droid.api; public interface ICoreApi { IBaseDirectory getBaseDirectory(); IMemberManager getMemberManager(); void save(); void load(); }
apache-2.0
arquillian/arquillian-algeron
pact/provider/core/src/test/java/org/arquillian/algeron/pact/provider/core/StateTypeConverterTest.java
6653
package org.arquillian.algeron.pact.provider.core; import net.jcip.annotations.NotThreadSafe; import org.assertj.core.util.Arrays; import org.junit.Test; import java.net.URI; import java.net.URL; import static org.assertj.core.api.Assertions.assertThat; @NotThreadSafe public class StateTypeConverterTest { @Test public void should_convert_empty_string_to_empty_string_array() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); // when String[] convertedStringArray = typeConverter.convert("", String[].class); // then assertThat(convertedStringArray).isEmpty(); } @Test public void should_convert_blank_string_to_empty_string_array() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); // when String[] convertedStringArray = typeConverter.convert(" ", String[].class); // then assertThat(convertedStringArray).isEmpty(); } @Test public void should_convert_sequence_of_blank_strings_to_empty_string_array() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); String[] arrayOfEmptyStrings = Arrays.array("", "", "", "", ""); // when String[] convertedStringArray = typeConverter.convert(" , , , , ", String[].class); // then assertThat(convertedStringArray).isEqualTo(arrayOfEmptyStrings); } @Test public void should_convert_single_element_to_one_element_array() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); String[] singleElementArray = Arrays.array("one element"); // when String[] convertedStringArray = typeConverter.convert("one element", String[].class); // then assertThat(convertedStringArray).isEqualTo(singleElementArray); } @Test public void should_convert_single_element_with_delimiter_to_one_element_array() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); String[] singleElementArray = Arrays.array("one element"); // when String[] convertedStringArray = typeConverter.convert("one element,", String[].class); // then assertThat(convertedStringArray).isEqualTo(singleElementArray); } @Test public void should_convert_single_element_with_delimiters_to_one_element_array() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); String[] singleElementArray = Arrays.array("one element"); // when String[] convertedStringArray = typeConverter.convert("one element,,,,,,,", String[].class); // then assertThat(convertedStringArray).isEqualTo(singleElementArray); } @Test public void should_convert_blank_to_empty_string_when_appear_in_sequence_with_non_blanks() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); String[] expectedArray = Arrays.array("a", "", "test", "", "", "b"); // when String[] convertedStringArray = typeConverter.convert("a, , test , , , b ", String[].class); // then assertThat(convertedStringArray).isEqualTo(expectedArray); } @Test public void should_convert_string() throws Exception { // given String expectedString = "Hello"; StateTypeConverter typeConverter = new StateTypeConverter(); // when String convertedString = typeConverter.convert("Hello", String.class); // then assertThat(convertedString).isEqualTo(expectedString); } @Test public void should_convert_string_to_integer() throws Exception { // given Integer expectedInteger = Integer.valueOf(15); StateTypeConverter typeConverter = new StateTypeConverter(); // when Integer convertedInteger = typeConverter.convert("15", Integer.class); // then assertThat(convertedInteger).isEqualTo(expectedInteger); } @Test public void should_convert_string_to_double() throws Exception { // given Double expecteDouble = Double.valueOf("123"); StateTypeConverter typeConverter = new StateTypeConverter(); // when Double convertedDouble = typeConverter.convert("123", Double.class); // then assertThat(convertedDouble).isEqualTo(expecteDouble); } @Test public void should_convert_string_to_long() throws Exception { // given Long expectedLong = Long.valueOf(-456); StateTypeConverter typeConverter = new StateTypeConverter(); // when Long convertedLong = typeConverter.convert("-456", Long.class); // then assertThat(convertedLong).isEqualTo(expectedLong); } @Test public void should_convert_string_to_boolean() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); // when Boolean convertedBoolen = typeConverter.convert("True", Boolean.class); // then assertThat(convertedBoolen).isTrue(); } @Test public void should_convert_string_to_URL() throws Exception { // given URL expectedUrl = new URI("http://www.arquillian.org").toURL(); StateTypeConverter typeConverter = new StateTypeConverter(); // when URL convertedUrl = typeConverter.convert("http://www.arquillian.org", URL.class); // then assertThat(convertedUrl).isEqualTo(expectedUrl); } @Test public void should_convert_string_to_URI() throws Exception { // given URI expectedUri = new URI("http://www.arquillian.org"); StateTypeConverter typeConverter = new StateTypeConverter(); // when URI convertedUri = typeConverter.convert("http://www.arquillian.org", URI.class); // then assertThat(convertedUri).isEqualTo(expectedUri); } @Test(expected = IllegalArgumentException.class) public void should_throw_exception_for_unsupported_type() throws Exception { // given StateTypeConverter typeConverter = new StateTypeConverter(); // when typeConverter.convert("typeConverter", StateTypeConverter.class); // then // exception should be thrown } // ------------------------------------------------------------------------------------------- }
apache-2.0
vert-x3/vertx-jdbc-client
src/main/java/io/vertx/jdbcclient/impl/actions/JDBCPropertyAccessor.java
1633
/* * Copyright (c) 2011-2014 The original author or authors * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.jdbcclient.impl.actions; import java.sql.JDBCType; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import io.vertx.core.impl.logging.Logger; import io.vertx.core.impl.logging.LoggerFactory; public interface JDBCPropertyAccessor<T> { Logger LOG = LoggerFactory.getLogger(JDBCColumnDescriptor.class); T get() throws SQLException; static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor) { return create(accessor, null); } static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor, T fallbackIfUnsupported) { return () -> { try { return accessor.get(); } catch (SQLFeatureNotSupportedException e) { LOG.debug("Unsupported access properties in SQL metadata", e); return fallbackIfUnsupported; } }; } static JDBCPropertyAccessor<Integer> jdbcType(JDBCPropertyAccessor<Integer> accessor) { return create(accessor, JDBCType.OTHER.getVendorTypeNumber()); } }
apache-2.0
azusa/hatunatu
hatunatu-util/src/test/java/jp/fieldnotes/hatunatu/util/collection/EmptyIteratorTest.java
2329
/* * Copyright 2004-2012 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package jp.fieldnotes.hatunatu.util.collection; import jp.fieldnotes.hatunatu.util.exception.SUnsupportedOperationException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; /** * @author wyukawa * */ public class EmptyIteratorTest { /** * @see org.junit.rules.ExpectedException */ @Rule public ExpectedException exception = ExpectedException.none(); /** * Test method for * {@link EmptyIterator#EmptyIterator()}. */ @Test public void testEmptyIterator() { EmptyIterator<String> emptyIterator = new EmptyIterator<String>(); assertThat(emptyIterator, is(notNullValue())); } /** * Test method for {@link EmptyIterator#remove()} * . */ @Test public void testRemove() { exception.expect(SUnsupportedOperationException.class); exception.expectMessage(is("remove")); EmptyIterator<String> emptyIterator = new EmptyIterator<String>(); emptyIterator.remove(); } /** * Test method for * {@link EmptyIterator#hasNext()}. */ @Test public void testHasNext() { EmptyIterator<String> emptyIterator = new EmptyIterator<String>(); assertThat(emptyIterator.hasNext(), is(false)); } /** * Test method for {@link EmptyIterator#next()}. */ @Test public void testNext() { exception.expect(SUnsupportedOperationException.class); exception.expectMessage(is("next")); EmptyIterator<String> emptyIterator = new EmptyIterator<String>(); emptyIterator.next(); } }
apache-2.0
fishercoder1534/Leetcode
src/main/java/com/fishercoder/solutions/_42.java
1640
package com.fishercoder.solutions; public class _42 { public static class Solution1 { /** * O(n) time and O(1) space, awesome! * * 1. first scan to find the max height index * 2. then scan from left up to max index and find all the water units up to the max height * 3. then scan from right down to max index and find all the water units down to the max height * 4. return the sum of those above two * * reference: https://discuss.leetcode.com/topic/22976/my-accepted-java-solution */ public int trap(int[] height) { if (height == null || height.length <= 2) { return 0; } int max = height[0]; int maxIndex = 0; for (int i = 0; i < height.length; i++) { if (height[i] > max) { max = height[i]; maxIndex = i; } } int water = 0; int leftMax = height[0]; for (int i = 0; i < maxIndex; i++) { if (height[i] > leftMax) { leftMax = height[i]; } else { water += leftMax - height[i]; } } int rightMax = height[height.length - 1]; for (int i = height.length - 1; i > maxIndex; i--) { if (height[i] > rightMax) { rightMax = height[i]; } else { water += rightMax - height[i]; } } return water; } } }
apache-2.0
tafkacn/statsdclient
src/main/java/tafkacn/StatsdClient.java
14025
package tafkacn.statsdclient; import com.lmax.disruptor.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A java statsd client that makes use of LMAX disruptor for smart batching * of counter updates to a statsd server * @author raymond.mak */ public class StatsdClient { final static private byte COUNTER_METRIC_TYPE = 0; final static private byte GAUGE_METRIC_TYPE = 1; final static private byte HISTOGRAM_METRIC_TYPE = 2; final static private byte METER_METRIC_TYPE = 3; final static private byte TIMER_METRIC_TYPE = 4; final static private short HUNDRED_PERCENT = (short)10000; final static private String[] METRIC_TYPE_STRINGS = new String[] { "|c", "|g", "|h", "|m", "|ms", }; static private class CounterEvent { private byte metricsType; private short samplingRate = HUNDRED_PERCENT; // In hundredth of a percentage point, 10000 being 100% private String key; private long magnitude; public CounterEvent() { super(); } public byte getMetricsType() { return metricsType; } public void setMetricsType(byte value) { metricsType = value; } public short getSamplingRate() { return samplingRate; } public void setSamplingRate(short value) { samplingRate = value; } public String getKey() { return key; } public void setKey(String value) { key = value; } public long getMagnitude() { return magnitude; } public void setMagnitude(long value) { magnitude = value; } final static public EventFactory<CounterEvent> EVENT_FACTORY = new EventFactory<CounterEvent>() { @Override public CounterEvent newInstance() { return new CounterEvent(); } }; } final static private ThreadLocal<Random> threadLocalSampler = new ThreadLocal<Random>() { @Override public Random initialValue() { return new Random(System.currentTimeMillis()); } }; private class CounterEventHandler implements EventHandler<CounterEvent> { final static private int MAX_MESSAGE_SIZE = 1000; // Assuming MTU being 1500 for typical datacenter Eternet implementation, cap message size to 1000 bytes to avoid fragmentation private DatagramChannel datagramChannel; private SocketChannel socketChannel; private ByteBuffer counterMessageBuffer; private int messagesInBuffer = 0; private CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); private WritableByteChannel outputChannel; private String statsdHostName; private int statsdPort; private long tcpConnectionRetryInterval = Long.MAX_VALUE; private long lastSuccessfulFlushTimestamp; private int timeDelayInMillisAfterIncompleteFlush; public CounterEventHandler( String statsdHostName, int statsdPort, boolean useTcp, int tcpMessageSize, long tcpConnectionRetryInterval, int timeDelayInMillisAfterIncompleteFlush) throws IOException { this.statsdHostName = statsdHostName; this.statsdPort = statsdPort; this.timeDelayInMillisAfterIncompleteFlush = timeDelayInMillisAfterIncompleteFlush; if (useTcp) { this.counterMessageBuffer = ByteBuffer.allocate(tcpMessageSize); this.tcpConnectionRetryInterval = tcpConnectionRetryInterval; openSocket(); } else { this.counterMessageBuffer = ByteBuffer.allocate(MAX_MESSAGE_SIZE); this.datagramChannel = DatagramChannel.open(); this.datagramChannel.connect( new InetSocketAddress(statsdHostName, statsdPort)); this.outputChannel = datagramChannel; } } private void openSocket() throws IOException { this.socketChannel = SocketChannel.open(); this.socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); this.socketChannel.connect(new InetSocketAddress(statsdHostName, statsdPort)); this.outputChannel = socketChannel; this.socketChannel.shutdownInput(); } private void flush() throws IOException { onFlushMessageBuffer(); counterMessageBuffer.flip(); try { outputChannel.write(counterMessageBuffer); lastSuccessfulFlushTimestamp = System.currentTimeMillis(); } catch (Throwable e) { onFlushMessageFailure(e); if (socketChannel != null) { if (System.currentTimeMillis() - lastSuccessfulFlushTimestamp < tcpConnectionRetryInterval) { lastSuccessfulFlushTimestamp = System.currentTimeMillis(); if (socketChannel.isOpen()) { socketChannel.close(); } try { openSocket(); onReconnection(); } catch (Throwable innerException) {} } } } finally { counterMessageBuffer.clear(); messagesInBuffer = 0; } } private void addMessageToBuffer(String message) throws Exception { counterMessageBuffer.mark(); // Remember current position onCounterMessageReceived(); if (encoder.encode(CharBuffer.wrap(message), counterMessageBuffer, true) == CoderResult.OVERFLOW) { counterMessageBuffer.reset(); flush(); if (encoder.encode(CharBuffer.wrap(message), counterMessageBuffer, true) == CoderResult.OVERFLOW) { // Well the message is too big to fit in a single packet, throw it away counterMessageBuffer.clear(); onOversizedMessage(message); } else { messagesInBuffer++; } } else { messagesInBuffer++; } } @Override public void onEvent(CounterEvent t, long l, boolean bln) throws Exception { // Construct counter message String message = t.getKey().replace(":", "_") + ":" + Long.toString(t.getMagnitude()) + METRIC_TYPE_STRINGS[t.getMetricsType()] + (t.getSamplingRate() < HUNDRED_PERCENT ? String.format("|@0.%4d\n", t.getSamplingRate()/HUNDRED_PERCENT, t.getSamplingRate()%HUNDRED_PERCENT) : "\n"); addMessageToBuffer(message); if (bln && messagesInBuffer > 0) { flush(); if (timeDelayInMillisAfterIncompleteFlush > 0) { Thread.sleep(timeDelayInMillisAfterIncompleteFlush); } } } public void close() throws Exception { if (datagramChannel != null) { datagramChannel.close(); } if (socketChannel != null) { socketChannel.close(); } } } private RingBuffer<CounterEvent> ringBuffer; private ExecutorService eventProcessorExecutor; private BatchEventProcessor<CounterEvent> counterEventProcessor; private CounterEventHandler counterEventHandler; private short defaultSamplingRate; protected StatsdClient() {} public StatsdClient( int ringBufferSize, final String statsdHostName, final int statsdPort, final boolean useTcp, final int tcpMessageSize, final int tcpConnectionRetryInterval, final int timeDelayInMillisAfterIncompletFlush, short defaultSamplingRate) throws Exception { this(ringBufferSize, statsdHostName, statsdPort, useTcp, tcpMessageSize, tcpConnectionRetryInterval, timeDelayInMillisAfterIncompletFlush, defaultSamplingRate, new BlockingWaitStrategy()); } static private class NullClient extends StatsdClient { public NullClient() {} @Override public void sendCounterMessage(byte metricsType, short samplingRate, String key, long magnitude) {} } static final public StatsdClient NULL = new NullClient(); public StatsdClient( int ringBufferSize, final String statsdHostName, final int statsdPort, final boolean useTcp, final int tcpMessageSize, final int tcpConnectionRetryInterval, final int timeDelayInMillisAfterIncompletFlush, short defaultSamplingRate, WaitStrategy waitStrategy ) throws Exception { this.defaultSamplingRate = defaultSamplingRate; ringBuffer = new RingBuffer<>(CounterEvent.EVENT_FACTORY, new MultiThreadedClaimStrategy(ringBufferSize), waitStrategy); counterEventHandler = new CounterEventHandler(statsdHostName, statsdPort, useTcp, tcpMessageSize, tcpConnectionRetryInterval, timeDelayInMillisAfterIncompletFlush); counterEventProcessor = new BatchEventProcessor<>(ringBuffer, ringBuffer.newBarrier(), counterEventHandler); ringBuffer.setGatingSequences(counterEventProcessor.getSequence()); eventProcessorExecutor = Executors.newSingleThreadExecutor(); eventProcessorExecutor.submit(counterEventProcessor); } public void shutdown() throws Exception { if (counterEventProcessor != null) { counterEventProcessor.halt(); counterEventProcessor = null; } if (counterEventHandler != null) { counterEventHandler.close(); } if (eventProcessorExecutor != null) { eventProcessorExecutor.shutdown(); eventProcessorExecutor = null; } } public void incrementCounter(String key, long magnitude) { incrementCounter(key, magnitude, defaultSamplingRate); } public void incrementCounter(String key, long magnitude, short samplingRate) { sendCounterMessage(COUNTER_METRIC_TYPE, samplingRate, key, magnitude); } public void updateGauge(String key, long magnitude) { updateGauge(key, magnitude, defaultSamplingRate); } public void updateGauge(String key, long magnitude, short samplingRate) { sendCounterMessage(GAUGE_METRIC_TYPE, samplingRate, key, magnitude); } public void updateHistogram(String key, long magnitude) { updateHistogram(key, magnitude, defaultSamplingRate); } public void updateHistogram(String key, long magnitude, short samplingRate) { sendCounterMessage(HISTOGRAM_METRIC_TYPE, samplingRate, key, magnitude); } public void updateMeter(String key, long magnitude) { updateMeter(key, magnitude, defaultSamplingRate); } public void updateMeter(String key, long magnitude, short samplingRate) { sendCounterMessage(METER_METRIC_TYPE, samplingRate, key, magnitude); } public void updateTimer(String key, long magnitude) { updateTimer(key, magnitude, defaultSamplingRate); } public void updateTimer(String key, long magnitude, short samplingRate) { sendCounterMessage(TIMER_METRIC_TYPE, samplingRate, key, magnitude); } // Extension points for intercepting interesting events in the statsd client // such as a counter message being picked up by the consumer thread and // when the message buffer is flushed down the wire. protected void onCounterMessageReceived() {} protected void onFlushMessageBuffer() {} protected void onFlushMessageFailure(Throwable exception) {} protected void onReconnection() {} protected void onOversizedMessage(String message) {} protected void onRingBufferOverflow() {} public void sendCounterMessage(byte metricsType, short samplingRate, String key, long magnitude) { if (samplingRate < HUNDRED_PERCENT && threadLocalSampler.get().nextInt(HUNDRED_PERCENT) >= samplingRate) { return; } try { long sequence = ringBuffer.tryNext(1); CounterEvent event = ringBuffer.get(sequence); event.setMetricsType(metricsType); event.setSamplingRate(samplingRate); event.setKey(key); event.setMagnitude(magnitude); ringBuffer.publish(sequence); } catch (InsufficientCapacityException e) { onRingBufferOverflow(); } } }
apache-2.0
tourmalinelabs/AndroidTLKitExample
app/src/main/java/com/tourmaline/example/activities/MainActivity.java
19865
/* ****************************************************************************** * Copyright 2017 Tourmaline Labs, Inc. All rights reserved. * Confidential & Proprietary - Tourmaline Labs, Inc. ("TLI") * * The party receiving this software directly from TLI (the "Recipient") * may use this software as reasonably necessary solely for the purposes * set forth in the agreement between the Recipient and TLI (the * "Agreement"). The software may be used in source code form solely by * the Recipient's employees (if any) authorized by the Agreement. Unless * expressly authorized in the Agreement, the Recipient may not sublicense, * assign, transfer or otherwise provide the source code to any third * party. Tourmaline Labs, Inc. retains all ownership rights in and * to the software * * This notice supersedes any other TLI notices contained within the software * except copyright notices indicating different years of publication for * different portions of the software. This notice does not supersede the * application of any third party copyright notice to that third party's * code. ******************************************************************************/ package com.tourmaline.example.activities; import android.Manifest; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.os.PowerManager; import android.provider.Settings; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.GooglePlayServicesUtil; import com.tourmaline.context.CompletionListener; import com.tourmaline.context.Engine; import com.tourmaline.example.ExampleApplication; import com.tourmaline.example.R; import com.tourmaline.example.helpers.Monitoring; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private static final int PERMISSIONS_REQUEST_BACKGROUND = 210; private static final int PERMISSIONS_REQUEST_FOREGROUND = 211; private LinearLayout apiLayout; private TextView engStateTextView; private Button startAutomaticButton; private Button startManualButton; private Button stopButton; private LinearLayout alertLayout; private TextView alertGpsTextView; private TextView alertLocationTextView; private TextView alertMotionTextView; private TextView alertPowerTextView; private TextView alertBatteryTextView; private TextView alertSdkUpToDateTextView; private Monitoring.State targetMonitoringState; private boolean paused = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.activity_main); apiLayout = findViewById(R.id.api_layout); engStateTextView = findViewById(R.id.engine_State); startAutomaticButton = findViewById(R.id.start_button_automatic); startManualButton = findViewById(R.id.start_button_manual); stopButton = findViewById(R.id.stop_button); alertLayout = findViewById(R.id.alert_layout); alertGpsTextView = findViewById(R.id.alert_gps); alertLocationTextView = findViewById(R.id.alert_location); alertMotionTextView = findViewById(R.id.alert_motion); alertPowerTextView = findViewById(R.id.alert_power); alertBatteryTextView = findViewById(R.id.alert_battery); alertSdkUpToDateTextView = findViewById(R.id.alert_sdk); startAutomaticButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tryToStartMonitoring(Monitoring.State.AUTOMATIC); } }); startManualButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { tryToStartMonitoring(Monitoring.State.MANUAL); } }); stopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { stopMonitoring(); } }); final Button locationsButton = findViewById(R.id.locations_button); locationsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Intent intent = new Intent(MainActivity.this, LocationsActivity.class); startActivity(intent); } }); final Button drivesButton = findViewById(R.id.drives_button); drivesButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Intent intent = new Intent(MainActivity.this, DrivesActivity.class); startActivity(intent); } }); final Button telematicsButton = findViewById(R.id.telematics_button); telematicsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Intent intent = new Intent(MainActivity.this, TelematicsActivity.class); startActivity(intent); } }); registerEngineAlerts(); final Monitoring.State monitoring = Monitoring.getState(getApplicationContext()); makeUIChangesOnEngineMonitoring(monitoring); tryToStartMonitoring(monitoring); } @Override protected void onResume() { super.onResume(); paused = false; setAlerts(); } @Override protected void onPause() { paused = true; super.onPause(); } @Override protected void onDestroy() { unregisterEngineAlerts(); super.onDestroy(); } private void tryToStartMonitoring(final Monitoring.State monitoring) { if(monitoring == Monitoring.State.STOPPED) { stopMonitoring(); return; } final int googlePlayStat = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this); if (googlePlayStat == ConnectionResult.SUCCESS) { //check GooglePlayServices targetMonitoringState = monitoring; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED) { //very old platform allow the permission from the manifest (no user request is needed) startMonitoring(targetMonitoringState); return; } //Implicit background location ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_BACKGROUND); } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) { //The system popup will show "Always Allow" for the location permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.ACTIVITY_RECOGNITION}, PERMISSIONS_REQUEST_BACKGROUND); } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { //Need to ask Foreground then Background location permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACTIVITY_RECOGNITION}, PERMISSIONS_REQUEST_FOREGROUND); } } else { Log.i(TAG, "Google play status is " + googlePlayStat); stopMonitoring(); GooglePlayServicesUtil.showErrorDialogFragment(googlePlayStat, this, null, 0, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) {} }); } } private void startMonitoring(final Monitoring.State monitoring) { if(monitoring == Monitoring.State.STOPPED) { stopMonitoring(); return; } presentBatteryOptimisationSettings(); if (!Engine.IsInitialized()) { //check Engine State ((ExampleApplication)getApplication()).initEngine((monitoring==Monitoring.State.AUTOMATIC), new CompletionListener() { @Override public void OnSuccess() { makeUIChangesOnEngineMonitoring(monitoring); Monitoring.setState(getApplicationContext(), monitoring); } @Override public void OnFail(int i, String s) { Toast.makeText(MainActivity.this, "Error starting the Engine: " + i + " -> " + s, Toast.LENGTH_LONG).show(); stopMonitoring(); } }); } else { final Monitoring.State currentMonitoring = Monitoring.getState(getApplicationContext()); if(currentMonitoring==monitoring) { makeUIChangesOnEngineMonitoring(monitoring); } else { makeUIChangesOnEngineMonitoring(currentMonitoring); Toast.makeText(MainActivity.this, "Error can't switch monitoring state without stopping ", Toast.LENGTH_LONG).show(); } } } private void stopMonitoring() { ((ExampleApplication)getApplication()).destroyEngine(new CompletionListener() { @Override public void OnSuccess() { makeUIChangesOnEngineMonitoring(Monitoring.State.STOPPED); Monitoring.setState(getApplicationContext(), Monitoring.State.STOPPED); } @Override public void OnFail(int i, String s) { Toast.makeText(MainActivity.this, "Error destroying the Engine: " + i + " -> " + s, Toast.LENGTH_LONG).show(); } }); } private boolean permissionGranted(@NonNull String[] permissions, @NonNull int[] grantResults) { boolean permissionGranted = true; for ( int i = 0; i < grantResults.length; ++i ) { if( grantResults[i] != PackageManager.PERMISSION_GRANTED) { Log.e(TAG, "Failed to get grant results for " + permissions[i]); permissionGranted = false; } } return permissionGranted; } private boolean permissionGranted(@NonNull String permission, @NonNull String[] permissions, @NonNull int[] grantResults) { for ( int i = 0; i < grantResults.length; ++i ) { if( permission.equals(permissions[i]) && grantResults[i] == PackageManager.PERMISSION_GRANTED) { return true; } } return false; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(permissionGranted(permissions, grantResults) ) { Log.i( TAG, "Permissions granted for requestCode " + requestCode); } else { Log.i( TAG, "Permissions missing for requestCode " + requestCode); } if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { if (requestCode == PERMISSIONS_REQUEST_FOREGROUND) { if (permissionGranted(Manifest.permission.ACCESS_FINE_LOCATION, permissions, grantResults)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, PERMISSIONS_REQUEST_BACKGROUND); return; } startMonitoring(targetMonitoringState); } } if(requestCode == PERMISSIONS_REQUEST_BACKGROUND) { startMonitoring(targetMonitoringState); } } public boolean presentBatteryOptimisationSettings() { Log.d(TAG, "Battery settings"); PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M || powerManager.isIgnoringBatteryOptimizations(getPackageName())) { return false; } //android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + getPackageName())); if(intent.resolveActivity(getPackageManager()) == null) { intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); if(intent.resolveActivity(getPackageManager()) == null) { return false; } } startActivity(intent); return true; } private void makeUIChangesOnEngineMonitoring(final Monitoring.State monitoring) { runOnUiThread( new Runnable() { @Override public void run() { switch (monitoring) { case STOPPED: { apiLayout.setVisibility(View.GONE); alertLayout.setVisibility(View.GONE); engStateTextView.setText(getResources().getString(R.string.not_monitoring)); startAutomaticButton.setEnabled(true); startManualButton.setEnabled(true); stopButton.setEnabled(false); break; } case AUTOMATIC: { apiLayout.setVisibility(View.VISIBLE); alertLayout.setVisibility(View.VISIBLE); engStateTextView.setText(getResources().getString(R.string.automatic_monitoring)); startAutomaticButton.setEnabled(false); startManualButton.setEnabled(false); stopButton.setEnabled(true); break; } case MANUAL: { apiLayout.setVisibility(View.VISIBLE); alertLayout.setVisibility(View.VISIBLE); engStateTextView.setText(getResources().getString(R.string.manual_monitoring)); startAutomaticButton.setEnabled(false); startManualButton.setEnabled(false); stopButton.setEnabled(true); Toast.makeText(MainActivity.this, "No drive will be detected until started by you! (click on DRIVES)", Toast.LENGTH_LONG).show(); break; } } } } ); } private BroadcastReceiver receiver; private void setAlerts() { if(paused) return; final ExampleApplication app = (ExampleApplication) getApplication(); showAlertGps(!app.isGpsEnable()); showAlertLocation(!app.isLocationPermissionGranted()); showAlertMotion(!app.isActivityRecognitionPermissionGranted()); showAlertBattery(app.isBatteryOptimisationEnable()); showAlertPower(app.isPowerSavingEnable()); showAlertSdkUpToDate(!app.isSdkUpToDate()); } private void registerEngineAlerts() { final LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent i) { int state = i.getIntExtra("state", Engine.INIT_SUCCESS); switch (state) { case Engine.GPS_ENABLED: case Engine.GPS_DISABLED: case Engine.LOCATION_PERMISSION_GRANTED: case Engine.LOCATION_PERMISSION_DENIED: case Engine.ACTIVITY_RECOGNITION_PERMISSION_GRANTED: case Engine.ACTIVITY_RECOGNITION_PERMISSION_DENIED: case Engine.POWER_SAVE_MODE_DISABLED: case Engine.POWER_SAVE_MODE_ENABLED: case Engine.BATTERY_OPTIMIZATION_DISABLED: case Engine.BATTERY_OPTIMIZATION_ENABLED: case Engine.BATTERY_OPTIMIZATION_UNKNOWN: case Engine.SDK_UP_TO_DATE: case Engine.SDK_UPDATE_AVAILABLE: case Engine.SDK_UPDATE_MANDATORY: { setAlerts(); break; } default: break; } setAlerts(); } }; mgr.registerReceiver(receiver, new IntentFilter(Engine.ACTION_LIFECYCLE)); } private void unregisterEngineAlerts() { if(receiver!=null) { final LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this); mgr.unregisterReceiver(receiver); } } private void showAlertGps(boolean show) { if(show) { alertGpsTextView.setText("GPS *** OFF"); alertGpsTextView.setTextColor(getResources().getColor(R.color.red)); } else { alertGpsTextView.setText("GPS *** ON"); alertGpsTextView.setTextColor(getResources().getColor(R.color.blue)); } } private void showAlertLocation(boolean show) { if(show) { alertLocationTextView.setText("Location permission *** OFF"); alertLocationTextView.setTextColor(getResources().getColor(R.color.red)); } else { alertLocationTextView.setText("Location permission *** ON"); alertLocationTextView.setTextColor(getResources().getColor(R.color.blue)); } } private void showAlertMotion(boolean show) { if(show) { alertMotionTextView.setText("Motion permission *** OFF"); alertMotionTextView.setTextColor(getResources().getColor(R.color.red)); } else { alertMotionTextView.setText("Motion permission *** ON"); alertMotionTextView.setTextColor(getResources().getColor(R.color.blue)); } } private void showAlertPower(boolean show) { if(show) { alertPowerTextView.setText("Power saving mode *** ON"); alertPowerTextView.setTextColor(getResources().getColor(R.color.red)); } else { alertPowerTextView.setText("Power saving mode *** OFF"); alertPowerTextView.setTextColor(getResources().getColor(R.color.blue)); } } private void showAlertBattery(boolean show) { if(show) { alertBatteryTextView.setText("Battery optimisation *** ON"); alertBatteryTextView.setTextColor(getResources().getColor(R.color.red)); } else { alertBatteryTextView.setText("Battery optimisation *** OFF"); alertBatteryTextView.setTextColor(getResources().getColor(R.color.blue)); } } private void showAlertSdkUpToDate(boolean show) { if(show) { alertSdkUpToDateTextView.setText("SDK up to date *** NO"); alertSdkUpToDateTextView.setTextColor(getResources().getColor(R.color.red)); } else { alertSdkUpToDateTextView.setText("SDK up to date *** YES"); alertSdkUpToDateTextView.setTextColor(getResources().getColor(R.color.blue)); } } }
apache-2.0
ysc/superword
src/main/java/org/apdplat/superword/tools/Pronunciation.java
9799
/* * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.apdplat.superword.tools; import org.apache.commons.lang.StringUtils; import org.apdplat.superword.tools.WordLinker.Dictionary; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Created by ysc on 12/5/15. */ public class Pronunciation { private static final Logger LOGGER = LoggerFactory.getLogger(Pronunciation.class); public static final String ICIBA_CSS_PATH = "div.base-speak span"; public static final String YOUDAO_CSS_PATH = "span.pronounce"; public static final String OXFORD_CSS_PATH = "header.entryHeader div.headpron"; public static final String WEBSTER_CSS_PATH = "div.word-attributes span.pr"; public static final String COLLINS_CSS_PATH = ""; public static final String CAMBRIDGE_CSS_PATH = ""; public static final String MACMILLAN_CSS_PATH = ""; public static final String HERITAGE_CSS_PATH = ""; public static final String WIKTIONARY_CSS_PATH = ""; public static final String WORDNET_CSS_PATH = ""; public static final String RANDOMHOUSE_CSS_PATH = ""; private static final String ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; private static final String ENCODING = "gzip, deflate"; private static final String LANGUAGE = "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"; private static final String CONNECTION = "keep-alive"; private static final String HOST = "www.iciba.com"; private static final String REFERER = "http://www.iciba.com/"; private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0"; public static String getPronunciationString(Dictionary dictionary, String word, String joinString) { return concat(getPronunciation(dictionary, word), joinString); } public static String concat(List<String> list, String joinString){ if(list.isEmpty()){ return ""; } StringBuilder string = new StringBuilder(); list.forEach(d -> string.append(d).append(joinString)); int len = string.length()-joinString.length(); if(len < 1){ return ""; } string.setLength(len); return string.toString(); } public static List<String> getPronunciation(Dictionary dictionary, String word){ switch (dictionary){ case ICIBA: return getPronunciationForICIBA(word); case YOUDAO: return getPronunciationForYOUDAO(word); case COLLINS: return getPronunciationForCOLLINS(word); case WEBSTER: return getPronunciationForWEBSTER(word); case OXFORD: return getPronunciationForOXFORD(word); case CAMBRIDGE: return getPronunciationForCAMBRIDGE(word); case MACMILLAN: return getPronunciationForMACMILLAN(word); case HERITAGE: return getPronunciationForHERITAGE(word); case WIKTIONARY: return getPronunciationForWIKTIONARY(word); case WORDNET: return getPronunciationForWORDNET(word); case RANDOMHOUSE: return getPronunciationForRANDOMHOUSE(word); } return getPronunciationForICIBA(word); } public static List<String> getPronunciationForICIBA(String word){ return parsePronunciation(WordLinker.ICIBA + word, ICIBA_CSS_PATH, word, Dictionary.ICIBA); } public static List<String> getPronunciationForYOUDAO(String word){ return parsePronunciation(WordLinker.YOUDAO + word, YOUDAO_CSS_PATH, word, Dictionary.YOUDAO); } public static List<String> getPronunciationForCOLLINS(String word){ return parsePronunciation(WordLinker.COLLINS + word, COLLINS_CSS_PATH, word, Dictionary.COLLINS); } public static List<String> getPronunciationForWEBSTER(String word){ return parsePronunciation(WordLinker.WEBSTER + word, WEBSTER_CSS_PATH, word, Dictionary.WEBSTER); } public static List<String> getPronunciationForOXFORD(String word){ return parsePronunciation(WordLinker.OXFORD + word, OXFORD_CSS_PATH, word, Dictionary.OXFORD); } public static List<String> getPronunciationForCAMBRIDGE(String word){ return parsePronunciation(WordLinker.CAMBRIDGE + word, CAMBRIDGE_CSS_PATH, word, Dictionary.CAMBRIDGE); } public static List<String> getPronunciationForMACMILLAN(String word){ return parsePronunciation(WordLinker.MACMILLAN + word, MACMILLAN_CSS_PATH, word, Dictionary.MACMILLAN); } public static List<String> getPronunciationForHERITAGE(String word){ return parsePronunciation(WordLinker.HERITAGE + word, HERITAGE_CSS_PATH, word, Dictionary.HERITAGE); } public static List<String> getPronunciationForWIKTIONARY(String word){ return parsePronunciation(WordLinker.WIKTIONARY + word, WIKTIONARY_CSS_PATH, word, Dictionary.WIKTIONARY); } public static List<String> getPronunciationForWORDNET(String word){ return parsePronunciation(WordLinker.WORDNET + word, WORDNET_CSS_PATH, word, Dictionary.WORDNET); } public static List<String> getPronunciationForRANDOMHOUSE(String word){ return parsePronunciation(WordLinker.RANDOMHOUSE + word, RANDOMHOUSE_CSS_PATH, word, Dictionary.RANDOMHOUSE); } public static List<String> parsePronunciation(String url, String cssPath, String word, Dictionary dictionary){ String wordPronunciation = MySQLUtils.getWordPronunciation(word, dictionary.name()); if(StringUtils.isNotBlank(wordPronunciation)) { return Arrays.asList(wordPronunciation.split(" \\| ")); } String html = getContent(url); List<String> list = parsePronunciationFromHtml(html, cssPath, word, dictionary); if(!list.isEmpty()){ MySQLUtils.saveWordPronunciation(word, dictionary.name(), concat(list, " | ")); } return list; } public static List<String> parsePronunciationFromHtml(String html, String cssPath, String word, Dictionary dictionary){ List<String> list = new ArrayList<>(); try { for (Element element : Jsoup.parse(html).select(cssPath)) { String pronunciation = element.text(); if (StringUtils.isNotBlank(pronunciation)) { pronunciation = pronunciation.replace("Pronunciation:", ""); pronunciation = pronunciation.trim(); if(!list.contains(pronunciation)) { list.add(pronunciation); } } } } catch (Exception e){ LOGGER.error("解析音标出错:" + word, e); } return list; } public static String getContent(String url) { long start = System.currentTimeMillis(); String html = _getContent(url, 1000); LOGGER.info("获取拼音耗时: {}", TimeUtils.getTimeDes(System.currentTimeMillis()-start)); int times = 0; while(StringUtils.isNotBlank(html) && html.contains("非常抱歉,来自您ip的请求异常频繁")){ //使用新的IP地址 ProxyIp.toNewIp(); html = _getContent(url); if(++times > 2){ break; } } return html; } private static String _getContent(String url, int timeout) { Future<String> future = ThreadPool.EXECUTOR_SERVICE.submit(()->_getContent(url)); try { Thread.sleep(timeout); return future.get(1, TimeUnit.NANOSECONDS); } catch (Throwable e) { LOGGER.error("获取网页异常", e); } return ""; } private static String _getContent(String url) { Connection conn = Jsoup.connect(url) .header("Accept", ACCEPT) .header("Accept-Encoding", ENCODING) .header("Accept-Language", LANGUAGE) .header("Connection", CONNECTION) .header("Referer", REFERER) .header("Host", HOST) .header("User-Agent", USER_AGENT) .timeout(1000) .ignoreContentType(true); String html = ""; try { html = conn.post().html(); html = html.replaceAll("[\n\r]", ""); }catch (Exception e){ LOGGER.error("获取URL:" + url + "页面出错", e); } return html; } public static void main(String[] args) { System.out.println(getPronunciationString(Dictionary.ICIBA, "resume", " | ")); System.out.println(getPronunciationString(Dictionary.YOUDAO, "resume", " | ")); System.out.println(getPronunciationString(Dictionary.OXFORD, "resume", " | ")); System.out.println(getPronunciationString(Dictionary.WEBSTER, "resume", " | ")); } }
apache-2.0
rlugojr/incubator-eagle
eagle-security/eagle-security-hbase-securitylog/src/main/java/org/apache/eagle/security/hbase/parse/HbaseAuditLogKafkaDeserializer.java
2222
/* * 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.eagle.security.hbase.parse; import org.apache.eagle.dataproc.impl.storm.kafka.SpoutKafkaMessageDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Properties; import java.util.TreeMap; public class HbaseAuditLogKafkaDeserializer implements SpoutKafkaMessageDeserializer { private static Logger LOG = LoggerFactory.getLogger(HbaseAuditLogKafkaDeserializer.class); private Properties props; public HbaseAuditLogKafkaDeserializer(Properties props){ this.props = props; } @Override public Object deserialize(byte[] arg0) { String logLine = new String(arg0); HbaseAuditLogParser parser = new HbaseAuditLogParser(); try{ HbaseAuditLogObject entity = parser.parse(logLine); if(entity == null) return null; Map<String, Object> map = new TreeMap<String, Object>(); map.put("action", entity.action); map.put("host", entity.host); map.put("status", entity.status); map.put("request", entity.request); map.put("scope", entity.scope); map.put("user", entity.user); map.put("timestamp", entity.timestamp); return map; }catch(Exception ex){ LOG.error("Failing parse audit log:" + logLine, ex); return null; } } }
apache-2.0
mdanielwork/intellij-community
java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java
33484
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl; import com.intellij.codeInsight.AnnotationTargetUtil; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.lang.ASTNode; import com.intellij.lang.FileASTNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.filters.ElementFilter; import com.intellij.psi.impl.light.LightClassReference; import com.intellij.psi.impl.light.LightJavaModule; import com.intellij.psi.impl.source.DummyHolder; import com.intellij.psi.impl.source.PsiClassReferenceType; import com.intellij.psi.impl.source.PsiImmediateClassType; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.scope.ElementClassHint; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.scope.processor.FilterScopeProcessor; import com.intellij.psi.scope.util.PsiScopesUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.PackageScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PairFunction; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.Map; public class PsiImplUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiImplUtil"); private PsiImplUtil() { } @NotNull public static PsiMethod[] getConstructors(@NotNull PsiClass aClass) { List<PsiMethod> result = null; for (PsiMethod method : aClass.getMethods()) { if (method.isConstructor() && method.getName().equals(aClass.getName())) { if (result == null) result = ContainerUtil.newSmartList(); result.add(method); } } return result == null ? PsiMethod.EMPTY_ARRAY : result.toArray(PsiMethod.EMPTY_ARRAY); } @Nullable public static PsiAnnotationMemberValue findDeclaredAttributeValue(@NotNull PsiAnnotation annotation, @NonNls @Nullable String attributeName) { PsiNameValuePair attribute = AnnotationUtil.findDeclaredAttribute(annotation, attributeName); return attribute == null ? null : attribute.getValue(); } @Nullable public static PsiAnnotationMemberValue findAttributeValue(@NotNull PsiAnnotation annotation, @Nullable @NonNls String attributeName) { final PsiAnnotationMemberValue value = findDeclaredAttributeValue(annotation, attributeName); if (value != null) return value; if (attributeName == null) attributeName = "value"; final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); if (referenceElement != null) { PsiElement resolved = referenceElement.resolve(); if (resolved != null) { PsiMethod[] methods = ((PsiClass)resolved).findMethodsByName(attributeName, false); for (PsiMethod method : methods) { if (PsiUtil.isAnnotationMethod(method)) { return ((PsiAnnotationMethod)method).getDefaultValue(); } } } } return null; } @NotNull public static PsiTypeParameter[] getTypeParameters(@NotNull PsiTypeParameterListOwner owner) { final PsiTypeParameterList typeParameterList = owner.getTypeParameterList(); if (typeParameterList != null) { return typeParameterList.getTypeParameters(); } return PsiTypeParameter.EMPTY_ARRAY; } @NotNull public static PsiJavaCodeReferenceElement[] namesToPackageReferences(@NotNull PsiManager manager, @NotNull String[] names) { PsiJavaCodeReferenceElement[] refs = new PsiJavaCodeReferenceElement[names.length]; for (int i = 0; i < names.length; i++) { String name = names[i]; try { refs[i] = JavaPsiFacade.getElementFactory(manager.getProject()).createPackageReferenceElement(name); } catch (IncorrectOperationException e) { LOG.error(e); } } return refs; } public static int getParameterIndex(@NotNull PsiParameter parameter, @NotNull PsiParameterList parameterList) { PsiElement parameterParent = parameter.getParent(); assert parameterParent == parameterList : parameterList +"; "+parameterParent; PsiParameter[] parameters = parameterList.getParameters(); for (int i = 0; i < parameters.length; i++) { PsiParameter paramInList = parameters[i]; if (parameter.equals(paramInList)) return i; } String name = parameter.getName(); PsiParameter suspect = null; int i; for (i = parameters.length - 1; i >= 0; i--) { PsiParameter paramInList = parameters[i]; if (Comparing.equal(name, paramInList.getName())) { suspect = paramInList; break; } } String message = parameter + ":" + parameter.getClass() + " not found among parameters: " + Arrays.asList(parameters) + "." + " parameterList' parent: " + parameterList.getParent() + ";" + " parameter.isValid()=" + parameter.isValid() + ";" + " parameterList.isValid()= " + parameterList.isValid() + ";" + " parameterList stub: " + (parameterList instanceof StubBasedPsiElement ? ((StubBasedPsiElement)parameterList).getStub() : "---") + "; " + " parameter stub: "+(parameter instanceof StubBasedPsiElement ? ((StubBasedPsiElement)parameter).getStub() : "---") + ";" + " suspect: " + suspect +" (index="+i+"); " + (suspect==null?null:suspect.getClass()) + " suspect stub: "+(suspect instanceof StubBasedPsiElement ? ((StubBasedPsiElement)suspect).getStub() : suspect == null ? "-null-" : "---"+suspect.getClass()) + ";" + " parameter.equals(suspect) = " + parameter.equals(suspect) + "; " + " parameter.getNode() == suspect.getNode(): " + (parameter.getNode() == (suspect==null ? null : suspect.getNode())) + "; " + "." ; LOG.error(message); return i; } public static int getTypeParameterIndex(@NotNull PsiTypeParameter typeParameter, @NotNull PsiTypeParameterList typeParameterList) { PsiTypeParameter[] typeParameters = typeParameterList.getTypeParameters(); for (int i = 0; i < typeParameters.length; i++) { if (typeParameter.equals(typeParameters[i])) return i; } LOG.error(typeParameter + " in " + typeParameterList); return -1; } @NotNull public static Object[] getReferenceVariantsByFilter(@NotNull PsiJavaCodeReferenceElement reference, @NotNull ElementFilter filter) { FilterScopeProcessor processor = new FilterScopeProcessor(filter); PsiScopesUtil.resolveAndWalk(processor, reference, null, true); return processor.getResults().toArray(); } public static boolean processDeclarationsInMethod(@NotNull final PsiMethod method, @NotNull final PsiScopeProcessor processor, @NotNull final ResolveState state, PsiElement lastParent, @NotNull final PsiElement place) { if (lastParent instanceof DummyHolder) lastParent = lastParent.getFirstChild(); boolean fromBody = lastParent instanceof PsiCodeBlock; PsiTypeParameterList typeParameterList = method.getTypeParameterList(); return processDeclarationsInMethodLike(method, processor, state, place, fromBody, typeParameterList); } public static boolean processDeclarationsInLambda(@NotNull final PsiLambdaExpression lambda, @NotNull final PsiScopeProcessor processor, @NotNull final ResolveState state, final PsiElement lastParent, @NotNull final PsiElement place) { final boolean fromBody = lastParent != null && lastParent == lambda.getBody(); return processDeclarationsInMethodLike(lambda, processor, state, place, fromBody, null); } private static boolean processDeclarationsInMethodLike(@NotNull final PsiParameterListOwner element, @NotNull final PsiScopeProcessor processor, @NotNull final ResolveState state, @NotNull final PsiElement place, final boolean fromBody, @Nullable final PsiTypeParameterList typeParameterList) { processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, element); if (typeParameterList != null) { final ElementClassHint hint = processor.getHint(ElementClassHint.KEY); if (hint == null || hint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) { if (!typeParameterList.processDeclarations(processor, state, null, place)) return false; } } if (fromBody) { final PsiParameter[] parameters = element.getParameterList().getParameters(); for (PsiParameter parameter : parameters) { if (!processor.execute(parameter, state)) return false; } } return true; } public static boolean processDeclarationsInResourceList(@NotNull final PsiResourceList resourceList, @NotNull final PsiScopeProcessor processor, @NotNull final ResolveState state, final PsiElement lastParent) { final ElementClassHint hint = processor.getHint(ElementClassHint.KEY); if (hint != null && !hint.shouldProcess(ElementClassHint.DeclarationKind.VARIABLE)) return true; for (PsiResourceListElement resource : resourceList) { if (resource == lastParent) break; if (resource instanceof PsiResourceVariable && !processor.execute(resource, state)) return false; } return true; } public static boolean hasTypeParameters(@NotNull PsiTypeParameterListOwner owner) { final PsiTypeParameterList typeParameterList = owner.getTypeParameterList(); return typeParameterList != null && typeParameterList.getTypeParameters().length != 0; } @NotNull public static PsiType[] typesByReferenceParameterList(@NotNull PsiReferenceParameterList parameterList) { PsiTypeElement[] typeElements = parameterList.getTypeParameterElements(); return typesByTypeElements(typeElements); } @NotNull public static PsiType[] typesByTypeElements(@NotNull PsiTypeElement[] typeElements) { PsiType[] types = PsiType.createArray(typeElements.length); for (int i = 0; i < types.length; i++) { types[i] = typeElements[i].getType(); } if (types.length == 1 && types[0] instanceof PsiDiamondType) { return ((PsiDiamondType)types[0]).resolveInferredTypes().getTypes(); } return types; } @NotNull public static PsiType getType(@NotNull PsiClassObjectAccessExpression classAccessExpression) { GlobalSearchScope resolveScope = classAccessExpression.getResolveScope(); PsiManager manager = classAccessExpression.getManager(); final PsiClass classClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Class", resolveScope); if (classClass == null) { return new PsiClassReferenceType(new LightClassReference(manager, "Class", "java.lang.Class", resolveScope), null); } if (!PsiUtil.isLanguageLevel5OrHigher(classAccessExpression)) { //Raw java.lang.Class return JavaPsiFacade.getElementFactory(manager.getProject()).createType(classClass); } PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; PsiType operandType = classAccessExpression.getOperand().getType(); if (operandType instanceof PsiPrimitiveType && !PsiType.NULL.equals(operandType)) { if (PsiType.VOID.equals(operandType)) { operandType = JavaPsiFacade.getElementFactory(manager.getProject()) .createTypeByFQClassName("java.lang.Void", classAccessExpression.getResolveScope()); } else { operandType = ((PsiPrimitiveType)operandType).getBoxedType(classAccessExpression); } } final PsiTypeParameter[] typeParameters = classClass.getTypeParameters(); if (typeParameters.length == 1) { substitutor = substitutor.put(typeParameters[0], operandType); } return new PsiImmediateClassType(classClass, substitutor); } @Nullable public static PsiAnnotation findAnnotation(@Nullable PsiAnnotationOwner annotationOwner, @NotNull String qualifiedName) { if (annotationOwner == null) return null; PsiAnnotation[] annotations = annotationOwner.getAnnotations(); if (annotations.length == 0) return null; String shortName = StringUtil.getShortName(qualifiedName); for (PsiAnnotation annotation : annotations) { PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); if (referenceElement != null && shortName.equals(referenceElement.getReferenceName())) { if (qualifiedName.equals(annotation.getQualifiedName())) { return annotation; } } } return null; } /** @deprecated use {@link AnnotationTargetUtil#findAnnotationTarget(PsiAnnotation, PsiAnnotation.TargetType...)} (to be removed ion IDEA 17) */ @Deprecated public static PsiAnnotation.TargetType findApplicableTarget(@NotNull PsiAnnotation annotation, @NotNull PsiAnnotation.TargetType... types) { return AnnotationTargetUtil.findAnnotationTarget(annotation, types); } /** @deprecated use {@link AnnotationTargetUtil#findAnnotationTarget(PsiClass, PsiAnnotation.TargetType...)} (to be removed ion IDEA 17) */ @Deprecated public static PsiAnnotation.TargetType findApplicableTarget(@NotNull PsiClass annotationType, @NotNull PsiAnnotation.TargetType... types) { return AnnotationTargetUtil.findAnnotationTarget(annotationType, types); } /** @deprecated use {@link AnnotationTargetUtil#getTargetsForLocation(PsiAnnotationOwner)} (to be removed ion IDEA 17) */ @Deprecated @NotNull public static PsiAnnotation.TargetType[] getTargetsForLocation(@Nullable PsiAnnotationOwner owner) { return AnnotationTargetUtil.getTargetsForLocation(owner); } @Nullable public static ASTNode findDocComment(@NotNull CompositeElement element) { TreeElement node = element.getFirstChildNode(); while (node != null && isWhitespaceOrComment(node) && !(node.getPsi() instanceof PsiDocComment)) { node = node.getTreeNext(); } return node == null || node.getElementType() != JavaDocElementType.DOC_COMMENT ? null : node; } /** * Types should be proceed by the callers themselves */ @Deprecated public static PsiType normalizeWildcardTypeByPosition(@NotNull PsiType type, @NotNull PsiExpression expression) { PsiUtilCore.ensureValid(expression); PsiUtil.ensureValidType(type); PsiExpression topLevel = expression; while (topLevel.getParent() instanceof PsiArrayAccessExpression && ((PsiArrayAccessExpression)topLevel.getParent()).getArrayExpression() == topLevel) { topLevel = (PsiExpression)topLevel.getParent(); } if (topLevel instanceof PsiArrayAccessExpression && !PsiUtil.isAccessedForWriting(topLevel)) { return PsiUtil.captureToplevelWildcards(type, expression); } final PsiType normalized = doNormalizeWildcardByPosition(type, expression, topLevel); LOG.assertTrue(normalized.isValid(), type); if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(topLevel)) { return PsiUtil.captureToplevelWildcards(normalized, expression); } return normalized; } private static PsiType doNormalizeWildcardByPosition(PsiType type, @NotNull PsiExpression expression, @NotNull PsiExpression topLevel) { if (type instanceof PsiWildcardType) { final PsiWildcardType wildcardType = (PsiWildcardType)type; if (PsiUtil.isAccessedForWriting(topLevel)) { return wildcardType.isSuper() ? wildcardType.getBound() : PsiCapturedWildcardType.create(wildcardType, expression); } else { if (wildcardType.isExtends()) { return wildcardType.getBound(); } return PsiType.getJavaLangObject(expression.getManager(), expression.getResolveScope()); } } if (type instanceof PsiArrayType) { final PsiType componentType = ((PsiArrayType)type).getComponentType(); final PsiType normalizedComponentType = doNormalizeWildcardByPosition(componentType, expression, topLevel); if (normalizedComponentType != componentType) { return normalizedComponentType.createArrayType(); } } return type; } @NotNull public static SearchScope getMemberUseScope(@NotNull PsiMember member) { PsiFile file = member.getContainingFile(); PsiElement topElement = file == null ? member : file; Project project = topElement.getProject(); final GlobalSearchScope maximalUseScope = ResolveScopeManager.getInstance(project).getUseScope(topElement); if (isInServerPage(file)) return maximalUseScope; PsiClass aClass = member.getContainingClass(); if (aClass instanceof PsiAnonymousClass && !(aClass instanceof PsiEnumConstantInitializer && member instanceof PsiMethod && member.hasModifierProperty(PsiModifier.PUBLIC) && ((PsiMethod)member).findSuperMethods().length > 0)) { //member from anonymous class can be called from outside the class PsiElement methodCallExpr = PsiUtil.isLanguageLevel8OrHigher(aClass) ? PsiTreeUtil.getTopmostParentOfType(aClass, PsiStatement.class) : PsiTreeUtil.getParentOfType(aClass, PsiMethodCallExpression.class); return new LocalSearchScope(methodCallExpr != null ? methodCallExpr : aClass); } PsiModifierList modifierList = member.getModifierList(); int accessLevel = modifierList == null ? PsiUtil.ACCESS_LEVEL_PUBLIC : PsiUtil.getAccessLevel(modifierList); if (accessLevel == PsiUtil.ACCESS_LEVEL_PUBLIC || accessLevel == PsiUtil.ACCESS_LEVEL_PROTECTED) { if (member instanceof PsiMethod && ((PsiMethod)member).isConstructor()) { PsiClass containingClass = member.getContainingClass(); if (containingClass != null) { //constructors cannot be overridden so their use scope can't be wider than their class's return containingClass.getUseScope(); } } return maximalUseScope; // class use scope doesn't matter, since another very visible class can inherit from aClass } if (accessLevel == PsiUtil.ACCESS_LEVEL_PRIVATE) { PsiClass topClass = PsiUtil.getTopLevelClass(member); return topClass != null ? new LocalSearchScope(topClass) : file == null ? maximalUseScope : new LocalSearchScope(file); } if (file instanceof PsiJavaFile) { PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(((PsiJavaFile)file).getPackageName()); if (aPackage != null) { SearchScope scope = PackageScope.packageScope(aPackage, false); return scope.intersectWith(maximalUseScope); } } return maximalUseScope; } public static boolean isInServerPage(@Nullable final PsiElement element) { return getServerPageFile(element) != null; } @Nullable private static ServerPageFile getServerPageFile(final PsiElement element) { final PsiFile psiFile = PsiUtilCore.getTemplateLanguageFile(element); return psiFile instanceof ServerPageFile ? (ServerPageFile)psiFile : null; } public static PsiElement setName(@NotNull PsiElement element, @NotNull String name) throws IncorrectOperationException { PsiManager manager = element.getManager(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); PsiIdentifier newNameIdentifier = factory.createIdentifier(name); return element.replace(newNameIdentifier); } public static boolean isDeprecatedByAnnotation(@NotNull PsiModifierListOwner owner) { return AnnotationUtil.findAnnotation(owner, CommonClassNames.JAVA_LANG_DEPRECATED) != null; } public static boolean isDeprecatedByDocTag(@NotNull PsiJavaDocumentedElement owner) { PsiDocComment docComment = owner.getDocComment(); return docComment != null && docComment.findTagByName("deprecated") != null; } @Nullable public static PsiJavaDocumentedElement findDocCommentOwner(@NotNull PsiDocComment comment) { PsiElement parent = comment.getParent(); if (parent instanceof PsiJavaDocumentedElement) { PsiJavaDocumentedElement owner = (PsiJavaDocumentedElement)parent; if (owner.getDocComment() == comment) { return owner; } } return null; } @Nullable public static PsiAnnotationMemberValue setDeclaredAttributeValue(@NotNull PsiAnnotation psiAnnotation, @Nullable String attributeName, @Nullable PsiAnnotationMemberValue value, @NotNull PairFunction<? super Project, ? super String, ? extends PsiAnnotation> annotationCreator) { PsiAnnotationMemberValue existing = psiAnnotation.findDeclaredAttributeValue(attributeName); if (value == null) { if (existing == null) { return null; } existing.getParent().delete(); } else { if (existing != null) { ((PsiNameValuePair)existing.getParent()).setValue(value); } else { PsiNameValuePair[] attributes = psiAnnotation.getParameterList().getAttributes(); if (attributes.length == 1) { PsiNameValuePair attribute = attributes[0]; if (attribute.getName() == null) { PsiAnnotationMemberValue defValue = attribute.getValue(); assert defValue != null : attribute; attribute.replace(createNameValuePair(defValue, PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME + "=", annotationCreator)); } } boolean allowNoName = attributes.length == 0 && ("value".equals(attributeName) || null == attributeName); final String namePrefix = allowNoName ? "" : attributeName + "="; psiAnnotation.getParameterList().addBefore(createNameValuePair(value, namePrefix, annotationCreator), null); } } return psiAnnotation.findDeclaredAttributeValue(attributeName); } private static PsiNameValuePair createNameValuePair(@NotNull PsiAnnotationMemberValue value, @NotNull String namePrefix, @NotNull PairFunction<? super Project, ? super String, ? extends PsiAnnotation> annotationCreator) { return annotationCreator.fun(value.getProject(), "@A(" + namePrefix + value.getText() + ")").getParameterList().getAttributes()[0]; } @Nullable public static ASTNode skipWhitespaceAndComments(final ASTNode node) { return TreeUtil.skipWhitespaceAndComments(node, true); } @Nullable public static ASTNode skipWhitespaceCommentsAndTokens(final ASTNode node, @NotNull TokenSet alsoSkip) { return TreeUtil.skipWhitespaceCommentsAndTokens(node, alsoSkip, true); } public static boolean isWhitespaceOrComment(ASTNode element) { return TreeUtil.isWhitespaceOrComment(element); } @Nullable public static ASTNode skipWhitespaceAndCommentsBack(final ASTNode node) { if (node == null) return null; if (!isWhitespaceOrComment(node)) return node; ASTNode parent = node.getTreeParent(); ASTNode prev = node; while (prev instanceof CompositeElement) { if (!isWhitespaceOrComment(prev)) return prev; prev = prev.getTreePrev(); } if (prev == null) return null; ASTNode firstChildNode = parent.getFirstChildNode(); ASTNode lastRelevant = null; while (firstChildNode != prev) { if (!isWhitespaceOrComment(firstChildNode)) lastRelevant = firstChildNode; firstChildNode = firstChildNode.getTreeNext(); } return lastRelevant; } @Nullable public static ASTNode findStatementChild(@NotNull CompositePsiElement statement) { if (DebugUtil.CHECK_INSIDE_ATOMIC_ACTION_ENABLED) { ApplicationManager.getApplication().assertReadAccessAllowed(); } for (ASTNode element = statement.getFirstChildNode(); element != null; element = element.getTreeNext()) { if (element.getPsi() instanceof PsiStatement) return element; } return null; } @NotNull public static PsiStatement[] getChildStatements(@NotNull CompositeElement psiCodeBlock) { ApplicationManager.getApplication().assertReadAccessAllowed(); // no lock is needed because all chameleons are expanded already int count = 0; for (ASTNode child1 = psiCodeBlock.getFirstChildNode(); child1 != null; child1 = child1.getTreeNext()) { if (child1.getPsi() instanceof PsiStatement) { count++; } } PsiStatement[] result = PsiStatement.ARRAY_FACTORY.create(count); if (count == 0) return result; int idx = 0; for (ASTNode child = psiCodeBlock.getFirstChildNode(); child != null && idx < count; child = child.getTreeNext()) { PsiElement element = child.getPsi(); if (element instanceof PsiStatement) { result[idx++] = (PsiStatement)element; } } return result; } public static boolean isVarArgs(@NotNull PsiMethod method) { PsiParameter[] parameters = method.getParameterList().getParameters(); return parameters.length > 0 && parameters[parameters.length - 1].isVarArgs(); } public static PsiElement handleMirror(PsiElement element) { return element instanceof PsiMirrorElement ? ((PsiMirrorElement)element).getPrototype() : element; } @Nullable public static PsiModifierList findNeighbourModifierList(@NotNull PsiJavaCodeReferenceElement ref) { PsiElement parent = PsiTreeUtil.skipParentsOfType(ref, PsiJavaCodeReferenceElement.class); if (parent instanceof PsiTypeElement) { PsiElement grandParent = parent.getParent(); if (grandParent instanceof PsiModifierListOwner) { return ((PsiModifierListOwner)grandParent).getModifierList(); } } return null; } public static boolean isTypeAnnotation(@Nullable PsiElement element) { return element instanceof PsiAnnotation && AnnotationTargetUtil.isTypeAnnotation((PsiAnnotation)element); } public static void collectTypeUseAnnotations(@NotNull PsiModifierList modifierList, @NotNull List<? super PsiAnnotation> annotations) { for (PsiAnnotation annotation : modifierList.getAnnotations()) { if (AnnotationTargetUtil.isTypeAnnotation(annotation)) { annotations.add(annotation); } } } private static final Key<Boolean> TYPE_ANNO_MARK = Key.create("type.annotation.mark"); public static void markTypeAnnotations(@NotNull PsiTypeElement typeElement) { PsiElement left = PsiTreeUtil.skipSiblingsBackward(typeElement, PsiComment.class, PsiWhiteSpace.class, PsiTypeParameterList.class); if (left instanceof PsiModifierList) { for (PsiAnnotation annotation : ((PsiModifierList)left).getAnnotations()) { if (AnnotationTargetUtil.isTypeAnnotation(annotation)) { annotation.putUserData(TYPE_ANNO_MARK, Boolean.TRUE); } } } } public static void deleteTypeAnnotations(@NotNull PsiTypeElement typeElement) { PsiElement left = PsiTreeUtil.skipSiblingsBackward(typeElement, PsiComment.class, PsiWhiteSpace.class, PsiTypeParameterList.class); if (left instanceof PsiModifierList) { for (PsiAnnotation annotation : ((PsiModifierList)left).getAnnotations()) { if (TYPE_ANNO_MARK.get(annotation) == Boolean.TRUE) { annotation.delete(); } } } } public static boolean isLeafElementOfType(@Nullable PsiElement element, @NotNull IElementType type) { return element instanceof LeafElement && ((LeafElement)element).getElementType() == type; } public static boolean isLeafElementOfType(PsiElement element, @NotNull TokenSet tokenSet) { return element instanceof LeafElement && tokenSet.contains(((LeafElement)element).getElementType()); } public static PsiType buildTypeFromTypeString(@NotNull final String typeName, @NotNull final PsiElement context, @NotNull final PsiFile psiFile) { final PsiManager psiManager = psiFile.getManager(); if (typeName.indexOf('<') != -1 || typeName.indexOf('[') != -1 || typeName.indexOf('.') == -1) { try { return JavaPsiFacade.getElementFactory(psiManager.getProject()).createTypeFromText(typeName, context); } catch(Exception ignored) { } // invalid syntax will produce unresolved class type } PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(typeName, context.getResolveScope()); PsiType resultType; if (aClass == null) { final LightClassReference ref = new LightClassReference( psiManager, PsiNameHelper.getShortClassName(typeName), typeName, PsiSubstitutor.EMPTY, psiFile ); resultType = new PsiClassReferenceType(ref, null); } else { PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiManager.getProject()); PsiSubstitutor substitutor = factory.createRawSubstitutor(aClass); resultType = factory.createType(aClass, substitutor); } return resultType; } @NotNull public static <T extends PsiJavaCodeReferenceElement> JavaResolveResult[] multiResolveImpl(@NotNull T element, boolean incompleteCode, @NotNull ResolveCache.PolyVariantContextResolver<? super T> resolver) { FileASTNode fileElement = SharedImplUtil.findFileElement(element.getNode()); if (fileElement == null) { PsiUtilCore.ensureValid(element); LOG.error("fileElement == null!"); return JavaResolveResult.EMPTY_ARRAY; } PsiFile psiFile = SharedImplUtil.getContainingFile(fileElement); PsiManager manager = psiFile == null ? null : psiFile.getManager(); if (manager == null) { PsiUtilCore.ensureValid(element); LOG.error("getManager() == null!"); return JavaResolveResult.EMPTY_ARRAY; } boolean valid = psiFile.isValid(); if (!valid) { PsiUtilCore.ensureValid(element); LOG.error("psiFile.isValid() == false!"); return JavaResolveResult.EMPTY_ARRAY; } if (element instanceof PsiMethodReferenceExpression) { // method refs: do not cache results during parent conflict resolving, acceptable checks, etc final Map<PsiElement, PsiType> map = LambdaUtil.ourFunctionTypes.get(); if (map != null && map.containsKey(element)) { return (JavaResolveResult[])resolver.resolve(element, psiFile, incompleteCode); } } return multiResolveImpl(manager.getProject(), psiFile, element, incompleteCode, resolver); } @NotNull public static <T extends PsiJavaCodeReferenceElement> JavaResolveResult[] multiResolveImpl(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull T element, boolean incompleteCode, @NotNull ResolveCache.PolyVariantContextResolver<? super T> resolver) { ResolveResult[] results = ResolveCache.getInstance(project).resolveWithCaching(element, resolver, true, incompleteCode, psiFile); return results.length == 0 ? JavaResolveResult.EMPTY_ARRAY : (JavaResolveResult[])results; } public static VirtualFile getModuleVirtualFile(@NotNull PsiJavaModule module) { return module instanceof LightJavaModule ? ((LightJavaModule)module).getRootVirtualFile() : module.getContainingFile().getVirtualFile(); } }
apache-2.0
hkuhn42/bottery
bottery.core/src/main/java/rocks/bottery/bot/crypto/AESHelper.java
3630
/** * Copyright (C) 2016-2018 Harald Kuhn * * 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 rocks.bottery.bot.crypto; import java.io.InputStream; import java.security.KeyStore; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; /** * Utility for AES encrypt and decrypt * * keeps a transient copy of the key from the keystore for performance * * The password for the keystore and entry are always the same. It is retrieved from the system property * KEYSTORE_PASSWORD * * TO encrypt a value use this classes main method like this * * java ... AESHelper secretText -DKEYSTORE_PASSWORD=password * * @author hkuhn */ public class AESHelper { private static final String KEYSTORE_PASSWORD = "KEYSTORE_PASSWORD"; static final String ENCODING = "ISO-8859-1"; static final String KEYSTORE = "Bot.jks"; static final String ALIAS = "BotKey"; private static transient SecretKeySpec key; /** * Decrypt a string encrypted with this util * * @param value * the encrypted value * @return the decrypted value * @throws Exception * if something went wrong :) */ static String decrypt(String value) throws Exception { byte[] input = Base64.getDecoder().decode(value); byte[] result = doChiper(ALIAS, KEYSTORE, input, Cipher.DECRYPT_MODE); return new String(result, ENCODING); } /** * Encrypt a string * * @param value * the string to encrypt * @return the encrypted value * @throws Exception * if something went wrong :) */ static String encrypt(String value) throws Exception { byte[] input = value.getBytes(ENCODING); byte[] result = doChiper(ALIAS, KEYSTORE, input, Cipher.ENCRYPT_MODE); return Base64.getEncoder().encodeToString(result); } static byte[] doChiper(String alias, String keystore, byte[] value, int mode) throws Exception { Cipher cipher = Cipher.getInstance("AES"); SecretKeySpec spec = loadKey(alias, keystore); cipher.init(mode, spec); return cipher.doFinal(value); } static SecretKeySpec loadKey(String alias, String keystore) throws Exception { if (key != null) { return key; } InputStream is = null; try { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(keystore); } catch (Exception e) { e.printStackTrace(); } String password = System.getProperty(KEYSTORE_PASSWORD); if (password == null || password.length() < 1) { throw new NullPointerException("password for keystore:" + keystore + " was not found"); } KeyStore ks = KeyStore.getInstance("JCEKS"); ks.load(is, password.toCharArray()); is.close(); key = (SecretKeySpec) ks.getKey(alias, password.toCharArray()); return key; } public static void main(String[] args) throws Exception { String encrypted = AESHelper.encrypt(args[0]); System.out.println(encrypted); String reborn = AESHelper.decrypt(encrypted); System.out.println(reborn); } }
apache-2.0
nomencurator/taxonaut
src/main/java/org/nomencurator/io/QueryManager.java
1410
/* * QueryManager.java: an interface to manage multiple ObjectExchangers * * Copyright (c) 2006, 2014, 2015, 2016 Nozomi `James' Ytow * All rights reserved. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nomencurator.io; import java.util.Collection; import org.nomencurator.model.NamedObject; /** * {@code QueryManager} manages queries to multiple * {@code DataExchanger}s * * @version 02 July 2016 * @author Nozomi `James' Ytow */ public interface QueryManager <T extends NamedObject<?>, X extends ObjectExchanger<T>// //P extends QueryParameter<T> //Q extends ObjectQuery<T> > { public MultiplexQuery<T> getQuery(QueryParameter<T> parameter); public boolean addSource(X source); public boolean removeSource(X source); public boolean setSynchronous(boolean synchronous); public boolean isSynchronous(); }
apache-2.0
Appendium/objectlabkit
datecalc-common/src/main/java/net/objectlab/kit/datecalc/common/TenorCode.java
3699
/* * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. * * Based in London, we are world leaders in the design and development * of bespoke applications for the securities financing markets. * * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a> * ___ _ _ _ _ _ * / _ \| |__ (_) ___ ___| |_| | __ _| |__ * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ * |__/ * * www.ObjectLab.co.uk * * $Id$ * * Copyright 2006 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 net.objectlab.kit.datecalc.common; /** * enum of Tenor Codes held by a {@link Tenor} * * @author Benoit Xhenseval * */ public enum TenorCode { OVERNIGHT("ON", false), SPOT("SP", false), TOM_NEXT("TN", false), SPOT_NEXT("SN", false), DAY("D", true), WEEK("W", true), MONTH("M", true), YEAR("Y", true); private final String code; private final boolean acceptUnits; private TenorCode(final String code, final boolean acceptUnits) { this.code = code; this.acceptUnits = acceptUnits; } // ----------------------------------------------------------------------- // // ObjectLab, world leaders in the design and development of bespoke // applications for the securities financing markets. // www.ObjectLab.co.uk // // ----------------------------------------------------------------------- /** * @return the string representation of this <code>TenorCode</code> */ public String getCode() { return code; } /** * @param code * string representation of the <code>TenorCode</code> * @return a <code>TenorCode</code> represented by the string argument */ public static TenorCode fromCode(final String code) { for (final TenorCode ct : TenorCode.values()) { if (ct.getCode().equals(code)) { return ct; } } return null; } /** * @return true if the TenorCode can have units e.g. 1 Day, 3 Week but not 6 OVERNIGHT or 5 SPOT/SP */ public boolean acceptUnits() { return acceptUnits; } } /* * ObjectLab, http://www.objectlab.co.uk/open is sponsoring the ObjectLab Kit. * * Based in London, we are world leaders in the design and development * of bespoke applications for the securities financing markets. * * <a href="http://www.objectlab.co.uk/open">Click here to learn more about us</a> * ___ _ _ _ _ _ * / _ \| |__ (_) ___ ___| |_| | __ _| |__ * | | | | '_ \| |/ _ \/ __| __| | / _` | '_ \ * | |_| | |_) | | __/ (__| |_| |__| (_| | |_) | * \___/|_.__// |\___|\___|\__|_____\__,_|_.__/ * |__/ * * www.ObjectLab.co.uk */
apache-2.0
deephacks/confit
tck/src/main/java/org/deephacks/confit/test/validation/BinaryTreeUtils.java
11067
/** * 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.deephacks.confit.test.validation; import org.deephacks.confit.model.Bean; import org.deephacks.confit.model.BeanId; import java.io.PrintStream; import java.util.Arrays; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; public class BinaryTreeUtils { public static Set<Bean> getTree(Integer root, List<Integer> children) { Node rootNode = new Node(root); for (int i : children) { rootNode.insert(i); } Set<Bean> beans = new HashSet<>(); rootNode.traverse(beans, null); return beans; } public static Bean getBean(int i, Set<Bean> beans) { for (Bean bean : beans) { if (new Integer(bean.getId().getInstanceId()).intValue() == i) { return bean; } } return null; } public static class Node { int value = 0; public Node left; public Node right; Node(int value) { this.value = value; } public Bean traverse(Set<Bean> beans, Bean parent) { Bean current = Bean.create(BeanId.create(value + "", "binarytree")); current.setProperty("value", value + ""); if (parent != null) { current.setReference("parent", parent.getId()); } if (left != null) { Bean leftBean = left.traverse(beans, current); current.setReference("left", leftBean.getId()); } if (right != null) { Bean rightBean = right.traverse(beans, current); current.setReference("right", rightBean.getId()); } beans.add(current); return current; } public void insert(int insert) { if (value == insert) { return; } if (value > insert) { if (left != null) { left.insert(insert); } else { left = new Node(insert); } } else { if (right != null) { right.insert(insert); } else { right = new Node(insert); } } } public Node delete(int delete) { if (value == delete) { if (left != null && right != null) { Node x = right; while (x.left != null) { x = x.left; } value = x.value; x.value = delete; right = right.delete(delete); return this; } else if (left != null) { return left; } else if (right != null) { return right; } else { return null; } } else if (value > delete) { left = (left == null) ? null : left.delete(delete); return this; } else { right = (right == null) ? null : right.delete(delete); return this; } } public String toString() { return value + ""; } } public static void printPretty(BinaryTree root) { TreePrinter.printPretty(root, 1, 0, new TreePrinter.PaddedWriter(System.out)); } private static class TreePrinter { // Search for the deepest part of the tree private static <T> int maxHeight(BinaryTree t) { if (t == null) return 0; int leftHeight = maxHeight(t.getLeft()); int rightHeight = maxHeight(t.getRight()); return (leftHeight > rightHeight) ? leftHeight + 1 : rightHeight + 1; } // Pretty formatting of a binary tree to the output stream public static <T> void printPretty(BinaryTree tree, int level, int indentSpace, PaddedWriter out) { int h = maxHeight(tree); int BinaryTreesInThisLevel = 1; int branchLen = 2 * ((int) Math.pow(2.0, h) - 1) - (3 - level) * (int) Math.pow(2.0, h - 1); int BinaryTreeSpaceLen = 2 + (level + 1) * (int) Math.pow(2.0, h); int startLen = branchLen + (3 - level) + indentSpace; Deque<BinaryTree> BinaryTreesQueue = new LinkedList<BinaryTree>(); BinaryTreesQueue.offerLast(tree); for (int r = 1; r < h; r++) { printBranches(branchLen, BinaryTreeSpaceLen, startLen, BinaryTreesInThisLevel, BinaryTreesQueue, out); branchLen = branchLen / 2 - 1; BinaryTreeSpaceLen = BinaryTreeSpaceLen / 2 + 1; startLen = branchLen + (3 - level) + indentSpace; printBinaryTrees(branchLen, BinaryTreeSpaceLen, startLen, BinaryTreesInThisLevel, BinaryTreesQueue, out); for (int i = 0; i < BinaryTreesInThisLevel; i++) { BinaryTree currBinaryTree = BinaryTreesQueue.pollFirst(); if (currBinaryTree != null) { BinaryTreesQueue.offerLast(currBinaryTree.getLeft()); BinaryTreesQueue.offerLast(currBinaryTree.getRight()); } else { BinaryTreesQueue.offerLast(null); BinaryTreesQueue.offerLast(null); } } BinaryTreesInThisLevel *= 2; } printBranches(branchLen, BinaryTreeSpaceLen, startLen, BinaryTreesInThisLevel, BinaryTreesQueue, out); printLeaves(indentSpace, level, BinaryTreesInThisLevel, BinaryTreesQueue, out); } private static <T> void printBranches(int branchLen, int BinaryTreeSpaceLen, int startLen, int BinaryTreesInThisLevel, Deque<BinaryTree> BinaryTreesQueue, PaddedWriter out) { Iterator<BinaryTree> iterator = BinaryTreesQueue.iterator(); for (int i = 0; i < BinaryTreesInThisLevel / 2; i++) { if (i == 0) { out.setw(startLen - 1); } else { out.setw(BinaryTreeSpaceLen - 2); } out.write(); BinaryTree next = iterator.next(); if (next != null) { out.write("/"); } else { out.write(" "); } out.setw(2 * branchLen + 2); out.write(); next = iterator.next(); if (next != null) { out.write("\\"); } else { out.write(" "); } } out.endl(); } // Print the branches and BinaryTree (eg, ___10___ ) private static <T> void printBinaryTrees(int branchLen, int BinaryTreeSpaceLen, int startLen, int BinaryTreesInThisLevel, Deque<BinaryTree> BinaryTreesQueue, PaddedWriter out) { Iterator<BinaryTree> iterator = BinaryTreesQueue.iterator(); BinaryTree currentBinaryTree; for (int i = 0; i < BinaryTreesInThisLevel; i++) { currentBinaryTree = iterator.next(); if (i == 0) { out.setw(startLen); } else { out.setw(BinaryTreeSpaceLen); } out.write(); if (currentBinaryTree != null && currentBinaryTree.getLeft() != null) { out.setfill('_'); } else { out.setfill(' '); } out.setw(branchLen + 2); if (currentBinaryTree != null) { out.write(currentBinaryTree.toString()); } else { out.write(); } if (currentBinaryTree != null && currentBinaryTree.getRight() != null) { out.setfill('_'); } else { out.setfill(' '); } out.setw(branchLen); out.write(); out.setfill(' '); } out.endl(); } // Print the leaves only (just for the bottom row) private static <T> void printLeaves(int indentSpace, int level, int BinaryTreesInThisLevel, Deque<BinaryTree> BinaryTreesQueue, PaddedWriter out) { Iterator<BinaryTree> iterator = BinaryTreesQueue.iterator(); BinaryTree currentBinaryTree; for (int i = 0; i < BinaryTreesInThisLevel; i++) { currentBinaryTree = iterator.next(); if (i == 0) { out.setw(indentSpace + 2); } else { out.setw(2 * level + 2); } if (currentBinaryTree != null) { out.write(currentBinaryTree.toString()); } else { out.write(); } } out.endl(); } public static class PaddedWriter { private int width = 0; private char fillChar = ' '; private final PrintStream writer; public PaddedWriter(PrintStream writer) { this.writer = writer; } void setw(int i) { width = i; } void setfill(char c) { fillChar = c; } void write(String str) { write(str.toCharArray()); } void write(char[] buf) { if (buf.length < width) { char[] pad = new char[width - buf.length]; Arrays.fill(pad, fillChar); writer.print(pad); } writer.print(buf); setw(0); } void write() { char[] pad = new char[width]; Arrays.fill(pad, fillChar); writer.print(pad); setw(0); } void endl() { writer.println(); setw(0); } } } }
apache-2.0
akexorcist/Example-SamsungSDK
PassApp/app/src/test/java/com/akexorcist/passapp/ExampleUnitTest.java
315
package com.akexorcist.passapp; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
henryco/OPalette
app/src/main/java/net/henryco/opalette/application/MainActivity.java
22644
/* * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * Copyright 2017 Henryk Timur Domagalski * */ package net.henryco.opalette.application; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.NotificationManager; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.preference.PreferenceManager; import android.support.v7.widget.Toolbar; import android.text.InputType; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.ToggleButton; import com.google.firebase.analytics.FirebaseAnalytics; import net.henryco.opalette.R; import net.henryco.opalette.api.glES.glSurface.renderers.universal.OPallUniRenderer; import net.henryco.opalette.api.glES.glSurface.renderers.universal.UniRenderer; import net.henryco.opalette.api.glES.glSurface.view.OPallSurfaceView; import net.henryco.opalette.api.utils.OPallAnimated; import net.henryco.opalette.api.utils.Utils; import net.henryco.opalette.api.utils.dialogs.OPallAlertDialog; import net.henryco.opalette.api.utils.lambda.consumers.OPallConsumer; import net.henryco.opalette.api.utils.requester.Request; import net.henryco.opalette.api.utils.requester.RequestSender; import net.henryco.opalette.api.utils.views.OPallViewInjector; import net.henryco.opalette.application.conf.GodConfig; import net.henryco.opalette.application.programs.ProgramPipeLine; import net.henryco.opalette.application.proto.AppMainProto; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity implements AppMainProto, ProgramPipeLine.AppProgramProtocol { private FirebaseAnalytics firebaseAnalytics; private final RequestSender stateRequester = new RequestSender(); private Fragment actualFragment = null; private boolean optionsSwitched = false; private ToggleButton imageToggle, paletteToggle, filterToggle; private ToggleButton[] toggleGroup; private View imageContainer, paletteContainer, filterContainer; private View[] containerGroup; private MenuItem topBarButton; private MenuItem topOptButton; private final List<Runnable> topBarButtonActions = new ArrayList<>(); private final int topBarButtonId = 2137; private final int topOptButtonId = 7321; private final Runnable topBarButtonDefaultAction = () -> stateRequester.sendRequest(new Request(get_bitmap_from_program)); @Nullable @Override public FirebaseAnalytics getFireBase() { return firebaseAnalytics; } @Override public void setResultBitmap(Bitmap bitmap) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); ImageView imageView = new ImageView(this); imageView.setImageBitmap(bitmap); String name = GodConfig.genDefaultImgFileName(); new OPallAlertDialog() .title("") .content(imageView) .positive(getResources().getString(R.string.save), () -> { View v = new LinearLayout(this); OPallViewInjector.inject(this, new OPallViewInjector<AppMainProto>(v, R.layout.textline) { @Override protected void onInject(AppMainProto context, View view) { TextView imageNameLine = (TextView) view.findViewById(R.id.lineText); imageNameLine.setInputType(InputType.TYPE_CLASS_TEXT); imageNameLine.setText(name); new OPallAlertDialog() .title(getResources().getString(R.string.save_as)) .content(v) .positive(getResources().getString(R.string.save), () -> { Utils.saveBitmapAction(bitmap, imageNameLine.getText().toString(), context.getActivityContext()); createSaveSuccessNotification(context.getActivityContext(), name); }).negative(getResources().getString(R.string.cancel)) .show(getSupportFragmentManager(), "Bitmap save"); } }); }) .negative(getResources().getString(R.string.share), () -> Utils.shareBitmapAction( bitmap, name, this, preferences.getBoolean(GodConfig.PREF_KEY_SAVE_AFTER, false), () -> createSaveSuccessNotification(this, name))) .neutral(getResources().getString(R.string.cancel)) .show(getSupportFragmentManager(), "Bitmap preview"); } private static int notifications = 1; private static void createSaveSuccessNotification(Context context, String name) { String title = context.getResources().getString(R.string.notification_save_success); NotificationCompat.Builder b = new NotificationCompat.Builder(context); b.setAutoCancel(true) .setVibrate(new long[]{0}) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.opalette_logo) .setTicker("") .setContentTitle(title) .setContentText(name) .setContentInfo(""); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(notifications++, b.build()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); if (preferences.getBoolean(GodConfig.PREF_KEY_ANALYTICS_ENABLE, false)) { Utils.log("ANALYTICS ENABLE"); firebaseAnalytics = FirebaseAnalytics.getInstance(this); } else firebaseAnalytics = null; Utils.log("SAVE AFTER SHARE stat: "+preferences.getBoolean(GodConfig.PREF_KEY_SAVE_AFTER, false)); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); imageToggle = (ToggleButton) toolbar.findViewById(R.id.toolbarButtonImage); paletteToggle = (ToggleButton) toolbar.findViewById(R.id.toolbarButtonPalette); filterToggle = (ToggleButton) toolbar.findViewById(R.id.toolbarButtonFilter); toggleGroup = new ToggleButton[]{imageToggle, paletteToggle, filterToggle}; imageContainer = findViewById(R.id.imageOptionsContainer); paletteContainer = findViewById(R.id.paletteOptionsContainer); filterContainer = findViewById(R.id.filterOptionsContainer); containerGroup = new View[]{imageContainer, paletteContainer, filterContainer}; imageToggle.setOnClickListener(this::toggleImage); paletteToggle.setOnClickListener(this::togglePalette); filterToggle.setOnClickListener(this::toggleFilter); if (getSupportActionBar() != null){ getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.DARK)); findViewById(R.id.fragmentSuperContainer).setElevation(0); } OPallUniRenderer renderer = new UniRenderer(this, new ProgramPipeLine()); stateRequester.addRequestListener(renderer); OPallSurfaceView oPallSurfaceView = (OPallSurfaceView) findViewById(R.id.opallView); oPallSurfaceView.setDimProportions(OPallSurfaceView.DimensionProcessors.RELATIVE_SQUARE); oPallSurfaceView.setRenderer(renderer); oPallSurfaceView.addToGLContextQueue(gl -> stateRequester.sendNonSyncRequest(new Request(send_bitmap_to_program, StartUpActivity.BitmapPack.get())) ); switchToScrollOptionsView(); } private void checkToggle(ToggleButton button) { for (ToggleButton b: toggleGroup) { if (b == button) button.setChecked(true); else b.setChecked(false); } } private void showContainer(View view) { for (View v: containerGroup) { if (v == view) view.setVisibility(View.VISIBLE); else v.setVisibility(View.GONE); } } private void toggleImage(View v) { OPallAnimated.pressButton75_225(this, v, () -> { if (imageToggle.isChecked()) showContainer(imageContainer); checkToggle(imageToggle); }); } private void togglePalette(View v) { OPallAnimated.pressButton75_225(this, v, () -> { if (paletteToggle.isChecked()) showContainer(paletteContainer); checkToggle(paletteToggle); }); } private void toggleFilter(View v) { OPallAnimated.pressButton75_225(this, v, () -> { if (filterToggle.isChecked()) showContainer(filterContainer); checkToggle(filterToggle); }); } @Override public void switchToFragmentOptions(Fragment fragment) { if (!optionsSwitched) { wipeTopBarButton(); if (fragment != null) { FragmentTransaction fragmentTransaction = getFragmentManager() .beginTransaction().add(R.id.fragmentContainer, fragment); fragmentTransaction.commit(); } findViewById(R.id.scrollOptionsView).setVisibility(View.GONE); findViewById(R.id.fragmentSuperContainer).setVisibility(View.VISIBLE); for (ToggleButton t: toggleGroup) t.setVisibility(View.GONE); optionsSwitched = true; actualFragment = fragment; } } @Override public void switchToScrollOptionsView() { if (actualFragment != null) { getFragmentManager().beginTransaction().remove(actualFragment).commit(); } findViewById(R.id.scrollOptionsView).setVisibility(View.VISIBLE); findViewById(R.id.fragmentSuperContainer).setVisibility(View.GONE); for (ToggleButton t: toggleGroup) t.setVisibility(View.VISIBLE); optionsSwitched = false; actualFragment = null; restoreTopBarButton(); } @Override public OPallSurfaceView getRenderSurface() { return (OPallSurfaceView) findViewById(R.id.opallView); } @Override public AppCompatActivity getActivityContext() { return this; } @Override public boolean onCreateOptionsMenu(Menu menu) { topBarButton = menu.add(0, topBarButtonId, 0, ""); topBarButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); topOptButton = menu.add(Menu.NONE, topOptButtonId, Menu.NONE, ""); topOptButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); restoreTopBarButton(); return super.onCreateOptionsMenu(menu); } @Override public void setTopControlButton(OPallConsumer<MenuItem> buttonConsumer, Runnable ... actions) { Collections.addAll(topBarButtonActions, actions); buttonConsumer.consume(topOptButton); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { if (!optionsSwitched) startBackDialog(); else switchToScrollOptionsView(); } else if (item.getItemId() == topBarButtonId || item.getItemId() == topOptButtonId) for (Runnable action : topBarButtonActions) action.run(); return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (!optionsSwitched) { if (imageToggle.isChecked()) startBackDialog(); else { showContainer(imageContainer); checkToggle(imageToggle); } } else switchToScrollOptionsView(); } private void closeActivity() { super.onBackPressed(); finish(); } private void startBackDialog() { new OPallAlertDialog() .title(getResources().getString(R.string.dialog_are_u_sure)) .message(getResources().getString(R.string.dialog_exit_msg)) .negative(getResources().getString(R.string.dialog_exit_decline)) .positive(getResources().getString(R.string.dialog_exit_accept), this::closeActivity) .show(getSupportFragmentManager(), "ExitDialog"); } private void restoreTopBarButton() { if (topBarButton != null) { topBarButtonActions.clear(); topBarButtonActions.add(topBarButtonDefaultAction); topBarButton.setVisible(true).setEnabled(true); topBarButton.setIcon(R.drawable.ic_share_white_24dp); topOptButton.setVisible(false).setEnabled(false); } } private void wipeTopBarButton() { if (topBarButton != null) { topBarButton.setEnabled(false).setVisible(false); topBarButtonActions.clear(); } } }
apache-2.0
lsmaira/gradle
subprojects/core/src/main/java/org/gradle/caching/internal/tasks/TaskOutputCachingBuildCacheKey.java
1067
/* * 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.caching.internal.tasks; import org.gradle.caching.BuildCacheKey; import org.gradle.util.Path; import javax.annotation.Nullable; public interface TaskOutputCachingBuildCacheKey extends BuildCacheKey { Path getTaskPath(); BuildCacheKeyInputs getInputs(); @Nullable byte[] getHashCodeBytes(); /** * Whether this key can be used to retrieve or store task output entries. */ boolean isValid(); }
apache-2.0
mogoweb/365browser
app/src/main/java/org/chromium/blink/mojom/MediaSessionPlaybackState.java
1196
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by: // mojo/public/tools/bindings/mojom_bindings_generator.py // For: // third_party/WebKit/public/platform/modules/mediasession/media_session.mojom // package org.chromium.blink.mojom; import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.mojo.bindings.DeserializationException; public final class MediaSessionPlaybackState { public static final int NONE = 0; public static final int PAUSED = NONE + 1; public static final int PLAYING = PAUSED + 1; private static final boolean IS_EXTENSIBLE = false; public static boolean isKnownValue(int value) { switch (value) { case 0: case 1: case 2: return true; } return false; } public static void validate(int value) { if (IS_EXTENSIBLE || isKnownValue(value)) return; throw new DeserializationException("Invalid enum value."); } private MediaSessionPlaybackState() {} }
apache-2.0
boundary/boundary-event-sdk
src/main/java/com/boundary/sdk/event/service/db/ServiceChecksDatabase.java
9687
// Copyright 2014-2015 Boundary, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.boundary.sdk.event.service.db; import java.util.List; import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.boundary.camel.component.ping.PingConfiguration; import com.boundary.camel.component.port.PortConfiguration; import com.boundary.camel.component.ssh.SshxConfiguration; import com.boundary.sdk.event.service.ServiceCheckRequest; import com.boundary.sdk.event.service.ServiceTest; import com.boundary.sdk.event.service.ping.PingServiceModel; import com.boundary.sdk.event.service.port.PortServiceModel; import com.boundary.sdk.event.service.ssh.SshxServiceModel; import com.boundary.sdk.event.service.url.UrlServiceDatabase; public class ServiceChecksDatabase implements Processor { //TODO: Separate class for handling constants private static final String PING = "ping"; private static final String PORT = "port"; private static final String SSH = "ssh"; private static final String URL = "url"; private static Logger LOG = LoggerFactory.getLogger(ServiceChecksDatabase.class); public ServiceChecksDatabase() { // TODO Auto-generated constructor stub } private void sendTestData(Exchange exchange) { Message message = exchange.getIn(); String sdnDirectorHost = "192.168.137.11"; String sdnDirectorName = "SDN Director"; ServiceCheckRequest request = new ServiceCheckRequest(); PingConfiguration sdnDirectorPingTest = new PingConfiguration(); sdnDirectorPingTest.setHost(sdnDirectorHost); PingServiceModel sdnDirectorPingModel = new PingServiceModel(); PortConfiguration sdnDirectorPortTest8080 = new PortConfiguration(); sdnDirectorPortTest8080.setHost(sdnDirectorHost); sdnDirectorPortTest8080.setPort(8080); PortServiceModel sdnDirectorPortModel8080 = new PortServiceModel(); SshxConfiguration plumgridProcessTest = new SshxConfiguration(); plumgridProcessTest.setHost(sdnDirectorHost); plumgridProcessTest.setCommand("status plumgrid"); plumgridProcessTest.setTimeout(10000); plumgridProcessTest.setUsername("plumgrid"); plumgridProcessTest.setPassword("plumgrid"); SshxServiceModel plumgridProcessModel = new SshxServiceModel(); plumgridProcessModel.setExpectedOutput("^plumgrid start/running, process\\s+\\d+"); SshxConfiguration plumgridSalProcessTest = new SshxConfiguration(); plumgridSalProcessTest.setHost(sdnDirectorHost); plumgridSalProcessTest.setCommand("status plumgrid-sal"); plumgridSalProcessTest.setTimeout(10000); plumgridSalProcessTest.setUsername("plumgrid"); plumgridSalProcessTest.setPassword("plumgrid"); SshxServiceModel plumgridSalProcessTestModel = new SshxServiceModel(); plumgridSalProcessTestModel.setExpectedOutput("^plumgrid-sal start/running, process\\s\\d+"); SshxConfiguration nginxProcessTest = new SshxConfiguration(); nginxProcessTest.setHost(sdnDirectorHost); nginxProcessTest.setCommand("status nginx"); nginxProcessTest.setTimeout(10000); nginxProcessTest.setUsername("plumgrid"); nginxProcessTest.setPassword("plumgrid"); SshxServiceModel nginxProcessModel = new SshxServiceModel(); nginxProcessModel.setExpectedOutput("^nginx start/running, process\\s\\d+"); ServiceTest<PingConfiguration,PingServiceModel> pingSDNDirector= new ServiceTest<PingConfiguration,PingServiceModel>( "host status","ping",sdnDirectorName,request.getRequestId(),sdnDirectorPingTest,sdnDirectorPingModel); request.addServiceTest(pingSDNDirector); ServiceTest<PortConfiguration,PortServiceModel> portSDNDirector8080 = new ServiceTest<PortConfiguration,PortServiceModel>( "8080 port status","port",sdnDirectorName,request.getRequestId(),sdnDirectorPortTest8080,sdnDirectorPortModel8080); request.addServiceTest(portSDNDirector8080); ServiceTest<SshxConfiguration,SshxServiceModel> sshPlumgridProcess = new ServiceTest<SshxConfiguration,SshxServiceModel>( "plumgrid process status","ssh",sdnDirectorName,request.getRequestId(),plumgridProcessTest,plumgridProcessModel); request.addServiceTest(sshPlumgridProcess); ServiceTest<SshxConfiguration,SshxServiceModel> sshPlumgridSalProcess = new ServiceTest<SshxConfiguration,SshxServiceModel>( "plumgrid-sal process status","ssh",sdnDirectorName,request.getRequestId(),plumgridProcessTest,plumgridProcessModel); request.addServiceTest(sshPlumgridSalProcess); ServiceTest<SshxConfiguration,SshxServiceModel> sshNginxProcess = new ServiceTest<SshxConfiguration,SshxServiceModel>( "nginx process status","ssh",sdnDirectorName,request.getRequestId(),plumgridProcessTest,plumgridProcessModel); request.addServiceTest(sshNginxProcess); message.setBody(request); } private void createPingServiceTest(ServiceCheckRequest request, Map<String,Object> row) { String pingHost = row.get("pingHost").toString(); int pingTimeout = Integer.parseInt(row.get("pingTimeout").toString()); PingConfiguration pingConfiguration = new PingConfiguration(); pingConfiguration.setHost(pingHost); pingConfiguration.setTimeout(pingTimeout); String serviceName = row.get("serviceName").toString(); String serviceTestName = row.get("serviceTestName").toString(); String serviceTypeName = row.get("serviceTypeName").toString(); PingServiceModel pingServiceModel = new PingServiceModel(); ServiceTest<PingConfiguration,PingServiceModel> pingServiceTest = new ServiceTest<PingConfiguration,PingServiceModel>(serviceTestName,serviceTypeName,serviceName, request.getRequestId(),pingConfiguration,pingServiceModel); request.addServiceTest(pingServiceTest); } private void createPortServiceTest(ServiceCheckRequest request, Map<String,Object> row) { String portHost = row.get("portHost").toString(); int port = Integer.parseInt(row.get("portPort").toString()); int portTimeout = Integer.parseInt(row.get("portTimeout").toString()); PortConfiguration portConfiguration = new PortConfiguration(); portConfiguration.setHost(portHost); portConfiguration.setPort(port); portConfiguration.setTimeout(portTimeout); String serviceName = row.get("serviceName").toString(); String serviceTestName = row.get("serviceTestName").toString(); String serviceTypeName = row.get("serviceTypeName").toString(); PortServiceModel portServiceModel = new PortServiceModel(); ServiceTest<PortConfiguration,PortServiceModel> portServicetest = new ServiceTest<PortConfiguration,PortServiceModel>(serviceTestName,serviceTypeName,serviceName, request.getRequestId(),portConfiguration,portServiceModel); request.addServiceTest(portServicetest); } private void createSshServiceTest(ServiceCheckRequest request, Map<String,Object> row) { String sshHost = row.get("sshHost").toString(); int sshPort = Integer.parseInt(row.get("sshPort").toString()); int sshTimeout = Integer.parseInt(row.get("sshTimeout").toString()); String sshUserName = row.get("sshUserName").toString(); String sshPassword = row.get("sshPassword").toString(); String sshCommand = row.get("sshCommand").toString(); SshxConfiguration sshConfiguration = new SshxConfiguration(); sshConfiguration.setHost(sshHost); sshConfiguration.setPort(sshPort); sshConfiguration.setTimeout(sshTimeout); sshConfiguration.setUsername(sshUserName); sshConfiguration.setPassword(sshPassword); sshConfiguration.setCommand(sshCommand); String serviceName = row.get("serviceName").toString(); String serviceTestName = row.get("serviceTestName").toString(); String serviceTypeName = row.get("serviceTypeName").toString(); SshxServiceModel sshServiceModel = new SshxServiceModel(); String expectedOutput = row.get("sshExpectedOutput").toString(); sshServiceModel.setExpectedOutput(expectedOutput); ServiceTest<SshxConfiguration,SshxServiceModel> sshServicetest = new ServiceTest<SshxConfiguration,SshxServiceModel>(serviceTestName,serviceTypeName,serviceName, request.getRequestId(),sshConfiguration,sshServiceModel); request.addServiceTest(sshServicetest); } private void createUrlServiceTest(ServiceCheckRequest request, Map<String,Object> row) { UrlServiceDatabase serviceUrl = new UrlServiceDatabase(); serviceUrl.populate(request,row); } @Override public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); ServiceCheckRequest request = new ServiceCheckRequest(); List<Map<String, Object>> list = message.getBody(List.class); for (Map<String,Object> row : list) { LOG.debug("Service Test Data: " + row.toString()); String serviceTestType = row.get("serviceTypeName").toString(); switch (serviceTestType) { case PING: createPingServiceTest(request,row); break; case PORT: createPortServiceTest(request,row); break; case SSH: createSshServiceTest(request,row); break; case URL: createUrlServiceTest(request,row); break; } } //TODO: How to handle if there are no service tests message.setBody(request); } }
apache-2.0
bazelbuild/intellij
aspect/tools/tests/unittests/com/google/idea/blaze/aspect/JarFilterTest.java
6677
/* * Copyright 2017 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.idea.blaze.aspect; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.idea.blaze.aspect.JarFilter.JarFilterOptions; import java.io.File; import java.io.FileOutputStream; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link JarFilter} */ @RunWith(JUnit4.class) public class JarFilterTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testFilterMethod() throws Exception { List<String> prefixes = ImmutableList.of("com/google/foo/Foo", "com/google/bar/Bar", "com/google/baz/Baz"); assertThat(JarFilter.shouldKeepClass(prefixes, "com/google/foo/Foo.class")).isTrue(); assertThat(JarFilter.shouldKeepClass(prefixes, "com/google/foo/Foo$Inner.class")).isTrue(); assertThat(JarFilter.shouldKeepClass(prefixes, "com/google/bar/Bar.class")).isTrue(); assertThat(JarFilter.shouldKeepClass(prefixes, "com/google/foo/Foo/NotFoo.class")).isFalse(); assertThat(JarFilter.shouldKeepClass(prefixes, "wrong/com/google/foo/Foo.class")).isFalse(); } @Test public void fullIntegrationTest() throws Exception { File fooJava = folder.newFile("Foo.java"); Files.write("package com.google.foo; class Foo { class Inner {} }".getBytes(UTF_8), fooJava); File barJava = folder.newFile("Bar.java"); Files.write("package com.google.foo.bar; class Bar {}".getBytes(UTF_8), barJava); File srcJar = folder.newFile("gen.srcjar"); try (ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(srcJar))) { zo.putNextEntry(new ZipEntry("com/google/foo/gen/Gen.java")); zo.write("package gen; class Gen {}".getBytes(UTF_8)); zo.closeEntry(); zo.putNextEntry(new ZipEntry("com/google/foo/gen/Gen2.java")); zo.write("package gen; class Gen2 {}".getBytes(UTF_8)); zo.closeEntry(); } File src3Jar = folder.newFile("gen3.srcjar"); try (ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(src3Jar))) { zo.putNextEntry(new ZipEntry("com/google/foo/gen/Gen3.java")); zo.write("package gen; class Gen3 {}".getBytes(UTF_8)); zo.closeEntry(); } File filterJar = folder.newFile("foo.jar"); try (ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(filterJar))) { zo.putNextEntry(new ZipEntry("com/google/foo/Foo.class")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("com/google/foo/Foo$Inner.class")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("com/google/foo/bar/Bar.class")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("gen/Gen.class")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("gen/Gen2.class")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("gen/Gen3.class")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("com/google/foo/Foo2.class")); zo.closeEntry(); } File filterSrcJar = folder.newFile("foo-src.jar"); try (ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(filterSrcJar))) { zo.putNextEntry(new ZipEntry("com/google/foo/Foo.java")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("com/google/foo/bar/Bar.java")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("gen/Gen.java")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("gen/Gen2.java")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("gen/Gen3.java")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("com/google/foo/Foo2.java")); zo.closeEntry(); zo.putNextEntry(new ZipEntry("com/google/foo/bar/Bar2.java")); zo.closeEntry(); } File filteredJar = folder.newFile("foo-filtered-gen.jar"); File filteredSourceJar = folder.newFile("foo-filtered-gen-src.jar"); String[] args = new String[] { "--keep_java_file", fooJava.getPath(), "--keep_java_file", barJava.getPath(), "--keep_source_jar", srcJar.getPath(), "--keep_source_jar", src3Jar.getPath(), "--filter_jar", filterJar.getPath(), "--filter_source_jar", filterSrcJar.getPath(), "--filtered_jar", filteredJar.getPath(), "--filtered_source_jar", filteredSourceJar.getPath() }; JarFilterOptions options = JarFilter.parseArgs(args); JarFilter.main(options); List<String> filteredJarNames = Lists.newArrayList(); try (ZipFile zipFile = new ZipFile(filteredJar)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); filteredJarNames.add(zipEntry.getName()); } } List<String> filteredSourceJarNames = Lists.newArrayList(); try (ZipFile zipFile = new ZipFile(filteredSourceJar)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); filteredSourceJarNames.add(zipEntry.getName()); } } assertThat(filteredJarNames) .containsExactly( "com/google/foo/Foo.class", "com/google/foo/Foo$Inner.class", "com/google/foo/bar/Bar.class", "gen/Gen.class", "gen/Gen2.class", "gen/Gen3.class"); assertThat(filteredSourceJarNames) .containsExactly( "com/google/foo/Foo.java", "com/google/foo/bar/Bar.java", "gen/Gen.java", "gen/Gen2.java", "gen/Gen3.java"); } }
apache-2.0
Liuxyly/Java_Learning
Java_Adv/src/org/collention/CollentionsDemo.java
874
package org.collention; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; enum Week { } public class CollentionsDemo { public static void main(String[] args) { List<Dog> dogs = new ArrayList<>(); dogs.add(new Dog("亚亚", "拉布拉多")); dogs.add(new Dog("偶偶", "雪纳瑞")); dogs.add(new Dog("飞飞", "拉布拉多")); dogs.add(new Dog("美美", "雪纳瑞")); // List<String> names = Arrays.asList("Tan", "Zhen", "Yu"); // Collections.sort(names, (String a, String b) -> a.compareTo(b)); Collections.sort(dogs, (Dog o1, Dog o2) ->{ return Collator.getInstance(Locale.CHINA).compare(o1.getName(), o2.getName()); }); dogs.forEach((Dog dog) -> {System.out.println(dog.getName() + "--->" + dog.getSt());}); } }
apache-2.0
droidranger/xygapp
xyg-library/src/main/java/com/ranger/xyg/library/config/AppConfigLib.java
662
package com.ranger.xyg.library.config; import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; /** * Created by xyg on 2017/6/14. */ public class AppConfigLib { public static int sScreenWidth; public static int sScreenHeight; public static void initScreen(Context context) { WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(outMetrics); sScreenWidth = outMetrics.widthPixels; sScreenHeight = outMetrics.heightPixels; } }
apache-2.0
AndrewZurn/sju-compsci-archive
CS200s/CS217b/OriginalFiles/lejos/robotics/navigation/CompassPilot.java
9741
package lejos.robotics.navigation; import lejos.robotics.RegulatedMotor; import lejos.robotics.DirectionFinder; import lejos.util.Delay; /* * WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS. * DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT. */ /** * A Pilot that keeps track of direction using a CompassSensor. * @deprecated This class will disappear in NXJ version 1.0. Compass should be added to a PoseProvider. * @see lejos.robotics.localization.PoseProvider#getPose() */ // TODO: Note @deprecated message above, I'm not sure PoseProvider is exactly right place to point users to yet. // Need to explain this more when we are sure how this will replace CompassPilot. - BB @Deprecated public class CompassPilot extends DifferentialPilot { protected DirectionFinder compass; protected Regulator regulator = new Regulator(); // inner regulator for thread protected float _heading; // desired heading protected float _estimatedHeading = 0; //estimated heading protected boolean _traveling = false; // state variable used by regulator protected float _distance; // set by travel() used by r egulator to stop protected byte _direction;// direction of travel = sign of _distance protected float _heading0 = 0;// heading when rotate immediate is called /** *returns returns true if the robot is travelling for a specific distance; **/ public boolean isTraveling() { return _traveling; } /** * Allocates a CompasPilot object, and sets the physical parameters of the NXT robot. <br> * Assumes Motor.forward() causes the robot to move forward); * Parameters * @param compass : a compass sensor; * @param wheelDiameter Diameter of the tire, in any convenient units. (The diameter in mm is usually printed on the tire). * @param trackWidth Distance between center of right tire and center of left tire, in same units as wheelDiameter * @param leftMotor * @param rightMotor */ public CompassPilot(DirectionFinder compass, float wheelDiameter, float trackWidth, RegulatedMotor leftMotor, RegulatedMotor rightMotor) { this(compass, wheelDiameter, trackWidth, leftMotor, rightMotor, false); } /** * Allocates a CompasPilot object, and sets the physical parameters of the NXT robot. <br> * Assumes Motor.forward() causes the robot to move forward); * Parameters * @param compass : a compass sensor; * @param wheelDiameter Diameter of the tire, in any convenient units. (The diameter in mm is usually printed on the tire). * @param trackWidth Distance between center of right tire and center of left tire, in same units as wheelDiameter * @param leftMotor * @param rightMotor * @param reverse if true of motor.forward() drives the robot backwards */ public CompassPilot(DirectionFinder compass, float wheelDiameter, float trackWidth, RegulatedMotor leftMotor, RegulatedMotor rightMotor, boolean reverse) { super(wheelDiameter, trackWidth, leftMotor, rightMotor, reverse); this.compass = compass; regulator.setDaemon(true); regulator.start(); } /** * Return the compass * @return the compass */ public DirectionFinder getCompass() { return compass; } /** * Returns the change in robot heading since the last call of reset() * normalized to be within -180 and _180 degrees */ public float getAngleIncrement() { return normalize(getCompassHeading() - _heading0); } /** * Returns direction of desired robot facing */ public float getHeading() { return _estimatedHeading; } /** * Method returns the current compass heading * @return Compass heading in degrees. */ public float getCompassHeading() { return normalize(compass.getDegreesCartesian()); } /** * sets direction of desired robot facing in degrees */ public void setHeading(float angle) { _heading = angle; } /** * Rotates the robot 360 degrees while calibrating the compass * resets compass zero to heading at end of calibration */ public synchronized void calibrate() { setRotateSpeed(50); compass.startCalibration(); super.rotate(360, false); compass.stopCalibration(); } public void resetCartesianZero() { compass.resetCartesianZero(); _heading = 0; } /** * Determines the difference between actual compass direction and desired heading in degrees * @return error (in degrees) */ public float getHeadingError() { float err = compass.getDegreesCartesian() - _heading; // Handles the wrap-around problem: return normalize(err); } /** * Moves the NXT robot a specific distance. A positive value moves it forwards and * a negative value moves it backwards. The robot steers to maintain its compass heading. * @param distance The positive or negative distance to move the robot, same units as _wheelDiameter * @param immediateReturn iff true, the method returns immediately. */ public void travel(float distance, boolean immediateReturn) { movementStart(immediateReturn); _type = Move.MoveType.TRAVEL; super.travel(distance,true); _distance = distance; _direction = 1; if(_distance < 0 ) _direction = -1; _traveling = true; if (immediateReturn) { return; } while (isMoving()) { Thread.yield(); // regulator will call stop when distance is reached } } /** * Moves the NXT robot a specific distance;<br> * A positive distance causes forward motion; negative distance moves backward. * Robot steers to maintain its compass heading; * @param distance of robot movement. Unit of measure for distance must be same as wheelDiameter and trackWidth **/ public void travel(float distance) { travel(distance, false); } /** * robot rotates to the specified compass heading; * @param immediateReturn - if true, method returns immediately. * Robot stops when specified angle is reached or when stop() is called */ public void rotate(float angle, boolean immediateReturn) { movementStart(immediateReturn); _type = Move.MoveType.ROTATE; float heading0 = getCompassHeading(); super.rotate(angle, immediateReturn); // takes care of movement start if (immediateReturn) return; _heading = normalize(_heading +angle); _traveling = false; float error = getHeadingError(); while (Math.abs(error) > 2) { super.rotate(-error, false); error = getHeadingError(); } _heading0 = heading0;//needed for currect angle increment } /** * Rotates the NXT robot through a specific angle; Rotates left if angle is positive, right if negative, * Returns when angle is reached. * Wheels turn in opposite directions producing a zero radius turn. * @param angle degrees. Positive angle rotates to the left (clockwise); negative to the right. <br>Requires correct values for wheel diameter and track width. */ public void rotate(float angle) { rotate(angle, false); } public void reset() { _left.resetTachoCount(); _right.resetTachoCount(); _heading0 = getCompassHeading(); super.reset(); } // methods required to give regulator access to Pilot superclass protected void stopNow() { stop(); } /** * Stops the robot soon after the method is executed. (It takes time for the motors * to slow to a halt) */ public void stop() { super.stop(); _traveling = false; while (isMoving()) { super.stop(); Thread.yield(); } } protected float normalize(float angle) { while (angle > 180)angle -= 360; while (angle < -180)angle += 360; return angle; } /** * inner class to regulate heading during travel move * Proportional control of steering ; error is an average of heading change * from tacho counts and from compass change * @author Roger Glassey */ class Regulator extends Thread { public void run() { while (true) { while (!_traveling) { Thread.yield(); } { // travel started float toGo = _distance; // reamining trave distance float gain = -3f * _direction; float error = 0; float e0 = 0; float incr0 = 0; _estimatedHeading = _heading0; do // travel in progress { // use weighted average of heading from tacho count and compass // weights should be based on variance of compass error and tacho count error float incr = getAngleIncrement(); _estimatedHeading += (incr - incr0); //change in heading from tacho counts incr0 = incr; _estimatedHeading = normalize( 0.5f *normalize(compass.getDegreesCartesian()) + 0.5f*_estimatedHeading); error = normalize( _estimatedHeading - _heading); toGo =(_distance - getMovementIncrement()); if(Math.abs(error - e0) > 2) //only steer if large change in error > 2 deg { steerPrep(gain * error); e0 = error; } Delay.msDelay(12); // another arbitrary constant Thread.yield(); } while (Math.abs(toGo) > 3 ); // travel completed (almost) int delta = Math.round(toGo*_leftDegPerDistance); _left.rotate(delta,true); delta = Math.round(toGo*_rightDegPerDistance); _outside.rotate(delta); while(_left.isMoving())Thread.yield(); _traveling = false; } } } } }
apache-2.0
TZClub/OMIPlatform
oip-service/src/main/java/tz/gzu/oip/admin/controller/ResourcesController.java
5006
package tz.gzu.oip.admin.controller; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import tz.gzu.oip.admin.dto.ResourcesDto; import tz.gzu.oip.dm.bo.ops.MenusDto; import tz.gzu.oip.dm.bo.ops.ResourcesMenuDto; import tz.gzu.oip.dm.po.AuthorityResources; import tz.gzu.oip.dm.po.Resources; import tz.gzu.oip.dm.service.ops.AuthorityResourcesService; import tz.gzu.oip.dm.service.ops.ResourcesService; import tz.gzu.oip.security.jwt.support.SimpleResponse; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Date; import java.util.List; /* * * @author yuit 吴正荣 * * @create 17-10-18 * */ @RestController @RequestMapping("resources") public class ResourcesController { @Autowired private ResourcesService resourcesService; @Autowired private AuthorityResourcesService authorityResourcesService; private Logger logger = Logger.getLogger(getClass()); /** * 获取菜单 * * @param authentication 授权用户 * @return */ @GetMapping("/menus") public List<ResourcesMenuDto> menus(Authentication authentication) { return resourcesService.findMenusByName(authentication.getName()); } /** * 获取所有的菜单 * * @return */ @GetMapping("allMenus/{auid}") public List<ResourcesMenuDto> allMenus(@PathVariable String auid) throws InvocationTargetException, IllegalAccessException { List<ResourcesMenuDto> all = this.resourcesService.findAllMenus(); List<ResourcesMenuDto> userHave = this.resourcesService.finMenusByAuId(auid); for (ResourcesMenuDto item : userHave) { for (ResourcesMenuDto allItem : all) { if (item.getId().trim().equals(allItem.getId().trim())) { for (MenusDto child : item.getChildren()) { for (MenusDto _child : allItem.getChildren()) { if (child.getCid().trim().equals(_child.getCid().trim())) { _child.setHave(true); break; } } } break; } } } return all; } @PostMapping("modifyMenusByAuId/{auid}") @Transactional(propagation = Propagation.REQUIRED) public void modifyMenusByAuId(@PathVariable String auid, @RequestBody List<AuthorityResources> items) { List<String> rids = new ArrayList<>(); List<ResourcesMenuDto> menuDtos = this.resourcesService.finMenusByAuId(auid); for (ResourcesMenuDto item : menuDtos) { if (item.getChildren() == null) { rids.add(item.getId()); } } if (rids.size() < 1) { this.authorityResourcesService.deleteResourcesByRId(null, auid); } else { // 先删除该角色所拥有的菜单 this.authorityResourcesService.deleteResourcesByRId(rids, auid); } if (items.size() > 0) { this.authorityResourcesService.insertMenus(items); } } /** * 获取所有资源 * * @return */ @GetMapping("/{cPage}/{pSize}") public ResourcesDto allResources(@PathVariable int cPage, @PathVariable int pSize) { List<Resources> menuDtos = resourcesService.findAllResources(cPage, pSize); int total = resourcesService.count(); return new ResourcesDto(menuDtos, total); } @GetMapping("/menusParent") public List<Resources> menusParent() { return this.resourcesService.findAllMenuParent(); } /** * 添加资源 * * @param resources * @return */ @PutMapping public SimpleResponse addResources(@RequestBody Resources resources) { int flg = 0; resources.setTime(new Date()); if (resources != null) { flg = this.resourcesService.insert(resources); } if (flg > 0) { // this.authority_resourcesService.insert() return new SimpleResponse("添加成功"); } else { return new SimpleResponse("服务器内部错误"); } } /** * 通过Id删除资源 * * @param id */ @DeleteMapping("/{id}") public void deleteResource(@PathVariable String id) { this.resourcesService.deleteResourceById(id); } /** * 更新资源 * * @param resources */ @PostMapping public void modifyResources(@RequestBody Resources resources) { resources.setTime(new Date()); this.resourcesService.update(resources); } }
apache-2.0
Asimov4/elasticsearch
src/main/java/org/elasticsearch/common/lucene/search/XBooleanFilter.java
13959
package org.elasticsearch.common.lucene.search; /* * 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. */ import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.FilterClause; import org.apache.lucene.search.BitsFilteredDocIdSet; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.DocIdSet; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.Filter; import org.apache.lucene.util.BitDocIdSet; import org.apache.lucene.util.Bits; import org.apache.lucene.util.CollectionUtil; import org.elasticsearch.common.lucene.docset.AllDocIdSet; import org.elasticsearch.common.lucene.docset.AndDocIdSet; import org.elasticsearch.common.lucene.docset.DocIdSets; import org.elasticsearch.common.lucene.docset.NotDocIdSet; import org.elasticsearch.common.lucene.docset.OrDocIdSet.OrBits; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * Similar to {@link org.apache.lucene.queries.BooleanFilter}. * <p/> * Our own variance mainly differs by the fact that we pass the acceptDocs down to the filters * and don't filter based on them at the end. Our logic is a bit different, and we filter based on that * at the top level filter chain. */ public class XBooleanFilter extends Filter implements Iterable<FilterClause> { private static final Comparator<DocIdSetIterator> COST_DESCENDING = new Comparator<DocIdSetIterator>() { @Override public int compare(DocIdSetIterator o1, DocIdSetIterator o2) { return Long.compare(o2.cost(), o1.cost()); } }; private static final Comparator<DocIdSetIterator> COST_ASCENDING = new Comparator<DocIdSetIterator>() { @Override public int compare(DocIdSetIterator o1, DocIdSetIterator o2) { return Long.compare(o1.cost(), o2.cost()); } }; final List<FilterClause> clauses = new ArrayList<>(); /** * Returns the a DocIdSetIterator representing the Boolean composition * of the filters that have been added. */ @Override public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException { final int maxDoc = context.reader().maxDoc(); // the 0-clauses case is ambiguous because an empty OR filter should return nothing // while an empty AND filter should return all docs, so we handle this case explicitely if (clauses.isEmpty()) { return null; } // optimize single case... if (clauses.size() == 1) { FilterClause clause = clauses.get(0); DocIdSet set = clause.getFilter().getDocIdSet(context, acceptDocs); if (clause.getOccur() == Occur.MUST_NOT) { if (DocIdSets.isEmpty(set)) { return new AllDocIdSet(maxDoc); } else { return new NotDocIdSet(set, maxDoc); } } // SHOULD or MUST, just return the set... if (DocIdSets.isEmpty(set)) { return null; } return set; } // We have several clauses, try to organize things to make it easier to process List<DocIdSetIterator> shouldIterators = new ArrayList<>(); List<Bits> shouldBits = new ArrayList<>(); boolean hasShouldClauses = false; List<DocIdSetIterator> requiredIterators = new ArrayList<>(); List<DocIdSetIterator> excludedIterators = new ArrayList<>(); List<Bits> requiredBits = new ArrayList<>(); List<Bits> excludedBits = new ArrayList<>(); for (FilterClause clause : clauses) { DocIdSet set = clause.getFilter().getDocIdSet(context, null); DocIdSetIterator it = null; Bits bits = null; if (DocIdSets.isEmpty(set) == false) { it = set.iterator(); if (it != null) { bits = set.bits(); } } switch (clause.getOccur()) { case SHOULD: hasShouldClauses = true; if (it == null) { // continue, but we recorded that there is at least one should clause // so that if all iterators are null we know that nothing matches this // filter since at least one SHOULD clause needs to match } else if (bits != null && DocIdSets.isBroken(it)) { shouldBits.add(bits); } else { shouldIterators.add(it); } break; case MUST: if (it == null) { // no documents matched a clause that is compulsory, then nothing matches at all return null; } else if (bits != null && DocIdSets.isBroken(it)) { requiredBits.add(bits); } else { requiredIterators.add(it); } break; case MUST_NOT: if (it == null) { // ignore } else if (bits != null && DocIdSets.isBroken(it)) { excludedBits.add(bits); } else { excludedIterators.add(it); } break; default: throw new AssertionError(); } } // Since BooleanFilter requires that at least one SHOULD clause matches, // transform the SHOULD clauses into a MUST clause if (hasShouldClauses) { if (shouldIterators.isEmpty() && shouldBits.isEmpty()) { // we had should clauses, but they all produced empty sets // yet BooleanFilter requires that at least one clause matches // so it means we do not match anything return null; } else if (shouldIterators.size() == 1 && shouldBits.isEmpty()) { requiredIterators.add(shouldIterators.get(0)); } else { // apply high-cardinality should clauses first CollectionUtil.timSort(shouldIterators, COST_DESCENDING); BitDocIdSet.Builder shouldBuilder = null; for (DocIdSetIterator it : shouldIterators) { if (shouldBuilder == null) { shouldBuilder = new BitDocIdSet.Builder(maxDoc); } shouldBuilder.or(it); } if (shouldBuilder != null && shouldBits.isEmpty() == false) { // we have both iterators and bits, there is no way to compute // the union efficiently, so we just transform the iterators into // bits // add first since these are fast bits shouldBits.add(0, shouldBuilder.build().bits()); shouldBuilder = null; } if (shouldBuilder == null) { // only bits assert shouldBits.size() >= 1; if (shouldBits.size() == 1) { requiredBits.add(shouldBits.get(0)); } else { requiredBits.add(new OrBits(shouldBits.toArray(new Bits[shouldBits.size()]))); } } else { assert shouldBits.isEmpty(); // only iterators, we can add the merged iterator to the list of required iterators requiredIterators.add(shouldBuilder.build().iterator()); } } } else { assert shouldIterators.isEmpty(); assert shouldBits.isEmpty(); } // From now on, we don't have to care about SHOULD clauses anymore since we upgraded // them to required clauses (if necessary) // cheap iterators first to make intersection faster CollectionUtil.timSort(requiredIterators, COST_ASCENDING); CollectionUtil.timSort(excludedIterators, COST_ASCENDING); // Intersect iterators BitDocIdSet.Builder res = null; for (DocIdSetIterator iterator : requiredIterators) { if (res == null) { res = new BitDocIdSet.Builder(maxDoc); res.or(iterator); } else { res.and(iterator); } } for (DocIdSetIterator iterator : excludedIterators) { if (res == null) { res = new BitDocIdSet.Builder(maxDoc, true); } res.andNot(iterator); } // Transform the excluded bits into required bits if (excludedBits.isEmpty() == false) { Bits excluded; if (excludedBits.size() == 1) { excluded = excludedBits.get(0); } else { excluded = new OrBits(excludedBits.toArray(new Bits[excludedBits.size()])); } requiredBits.add(new NotDocIdSet.NotBits(excluded)); } // The only thing left to do is to intersect 'res' with 'requiredBits' // the main doc id set that will drive iteration DocIdSet main; if (res == null) { main = new AllDocIdSet(maxDoc); } else { main = res.build(); } // apply accepted docs and compute the bits to filter with // accepted docs are added first since they are fast and will help not computing anything on deleted docs if (acceptDocs != null) { requiredBits.add(0, acceptDocs); } // the random-access filter that we will apply to 'main' Bits filter; if (requiredBits.isEmpty()) { filter = null; } else if (requiredBits.size() == 1) { filter = requiredBits.get(0); } else { filter = new AndDocIdSet.AndBits(requiredBits.toArray(new Bits[requiredBits.size()])); } return BitsFilteredDocIdSet.wrap(main, filter); } /** * Adds a new FilterClause to the Boolean Filter container * * @param filterClause A FilterClause object containing a Filter and an Occur parameter */ public void add(FilterClause filterClause) { clauses.add(filterClause); } public final void add(Filter filter, Occur occur) { add(new FilterClause(filter, occur)); } /** * Returns the list of clauses */ public List<FilterClause> clauses() { return clauses; } /** * Returns an iterator on the clauses in this query. It implements the {@link Iterable} interface to * make it possible to do: * <pre class="prettyprint">for (FilterClause clause : booleanFilter) {}</pre> */ public final Iterator<FilterClause> iterator() { return clauses().iterator(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (obj.getClass() != this.getClass())) { return false; } final XBooleanFilter other = (XBooleanFilter) obj; return clauses.equals(other.clauses); } @Override public int hashCode() { return 657153718 ^ clauses.hashCode(); } /** * Prints a user-readable version of this Filter. */ @Override public String toString(String field) { final StringBuilder buffer = new StringBuilder("BooleanFilter("); final int minLen = buffer.length(); for (final FilterClause c : clauses) { if (buffer.length() > minLen) { buffer.append(' '); } buffer.append(c); } return buffer.append(')').toString(); } static class ResultClause { public final DocIdSet docIdSet; public final Bits bits; public final FilterClause clause; DocIdSetIterator docIdSetIterator; ResultClause(DocIdSet docIdSet, Bits bits, FilterClause clause) { this.docIdSet = docIdSet; this.bits = bits; this.clause = clause; } /** * @return An iterator, but caches it for subsequent usage. Don't use if iterator is consumed in one invocation. */ DocIdSetIterator iterator() throws IOException { if (docIdSetIterator != null) { return docIdSetIterator; } else { return docIdSetIterator = docIdSet.iterator(); } } } static boolean iteratorMatch(DocIdSetIterator docIdSetIterator, int target) throws IOException { assert docIdSetIterator != null; int current = docIdSetIterator.docID(); if (current == DocIdSetIterator.NO_MORE_DOCS || target < current) { return false; } else { if (current == target) { return true; } else { return docIdSetIterator.advance(target) == target; } } } }
apache-2.0
magro/jboss-as-quickstart
deltaspike-partialbean-basic/src/main/java/org/jboss/as/quickstart/deltaspike/partialbean/ExamplePartialBeanImplementation.java
1893
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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.jboss.as.quickstart.deltaspike.partialbean; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import javax.enterprise.context.ApplicationScoped; /** * This class implements a dynamic DeltaSpike Partial Bean. It is bound to * one or more abstract classes or interfaces via the Binding Annotation * (@ExamplePartialBeanBinding below). * * All abstract, unimplemented methods from those beans will be implemented * via the invoke method. * */ @ExamplePartialBeanBinding @ApplicationScoped public class ExamplePartialBeanImplementation implements InvocationHandler { /** * In our example, this method will be invoked when the "sayHello" method is called. * * @param proxy The object upon which the method is being invoked. * @param method The method being invoked (sayHello in this QuickStart) * @param args The arguments being passed in to the invoked method */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return "Hello " + args[0]; } }
apache-2.0
MegatronKing/SVG-Android
docs/notification/java/ic_bluetooth_audio.java
3221
package com.github.megatronking.svg.iconlibs; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import com.github.megatronking.svg.support.SVGRenderer; /** * AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * SVG-Generator. It should not be modified by hand. */ public class ic_bluetooth_audio extends SVGRenderer { public ic_bluetooth_audio(Context context) { super(context); mAlpha = 1.0f; mWidth = dip2px(24.0f); mHeight = dip2px(24.0f); } @Override public void render(Canvas canvas, int w, int h, ColorFilter filter) { final float scaleX = w / 24.0f; final float scaleY = h / 24.0f; mPath.reset(); mRenderPath.reset(); mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}); mFinalPathMatrix.postScale(scaleX, scaleY); mPath.moveTo(14.24f, 12.01f); mPath.rLineTo(2.32f, 2.32f); mPath.rCubicTo(0.28f, -0.72f, 0.44f, -1.51f, 0.44f, -2.33f); mPath.rCubicTo(0.0f, -0.82f, -0.16f, -1.59f, -0.43f, -2.31f); mPath.rLineTo(-2.33f, 2.32f); mPath.close(); mPath.moveTo(14.24f, 12.01f); mPath.rMoveTo(5.29f, -5.3f); mPath.rLineTo(-1.26f, 1.26f); mPath.rCubicTo(0.63f, 1.21f, 0.98f, 2.57f, 0.98f, 4.02f); mPath.rCubicTo(0.0f, 1.4499998f, -0.36f, 2.82f, -0.98f, 4.02f); mPath.rLineTo(1.2f, 1.2f); mPath.rCubicTo(0.97f, -1.54f, 1.54f, -3.36f, 1.54f, -5.31f); mPath.rCubicTo(-0.01f, -1.89f, -0.55f, -3.67f, -1.48f, -5.19f); mPath.close(); mPath.moveTo(19.529999f, 6.71f); mPath.rMoveTo(-3.82f, 1.0f); mPath.lineTo(10.0f, 2.0f); mPath.lineTo(9.0f, 2.0f); mPath.rLineTo(0f, 7.59f); mPath.lineTo(4.41f, 5.0f); mPath.lineTo(3.0f, 6.41f); mPath.lineTo(8.59f, 12.0f); mPath.lineTo(3.0f, 17.59f); mPath.lineTo(4.41f, 19.0f); mPath.lineTo(9.0f, 14.41f); mPath.lineTo(9.0f, 22.0f); mPath.rLineTo(1.0f, 0f); mPath.rLineTo(5.71f, -5.71f); mPath.rLineTo(-4.3f, -4.29f); mPath.rLineTo(4.3f, -4.29f); mPath.close(); mPath.moveTo(15.709999f, 7.71f); mPath.moveTo(11.0f, 5.83f); mPath.rLineTo(1.88f, 1.88f); mPath.lineTo(11.0f, 9.59f); mPath.lineTo(11.0f, 5.83f); mPath.close(); mPath.moveTo(11.0f, 5.83f); mPath.rMoveTo(1.88f, 10.46f); mPath.lineTo(11.0f, 18.17f); mPath.rLineTo(0f, -3.76f); mPath.rLineTo(1.88f, 1.88f); mPath.close(); mPath.moveTo(12.88f, 16.29f); mRenderPath.addPath(mPath, mFinalPathMatrix); if (mFillPaint == null) { mFillPaint = new Paint(); mFillPaint.setStyle(Paint.Style.FILL); mFillPaint.setAntiAlias(true); } mFillPaint.setColor(applyAlpha(-16777216, 1.0f)); mFillPaint.setColorFilter(filter); canvas.drawPath(mRenderPath, mFillPaint); } }
apache-2.0
leangen/GraphQL-SPQR
src/test/java/io/leangen/graphql/services/UserService.java
5197
package io.leangen.graphql.services; import io.leangen.graphql.annotations.GraphQLArgument; import io.leangen.graphql.annotations.GraphQLComplexity; import io.leangen.graphql.annotations.GraphQLContext; import io.leangen.graphql.annotations.GraphQLId; import io.leangen.graphql.annotations.GraphQLMutation; import io.leangen.graphql.annotations.GraphQLQuery; import io.leangen.graphql.domain.Address; import io.leangen.graphql.domain.Education; import io.leangen.graphql.domain.Street; import io.leangen.graphql.domain.User; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; /** * Created by bojan.tomic on 3/5/16. */ public class UserService<T> { private Collection<Address> addresses = new ArrayList<>(); public UserService() { Address address1 = new Address(); address1.setTypes(Arrays.asList("residential", "home")); Street street11 = new Street("Fakestreet", 300); Street street12 = new Street("Realstreet", 123); address1.getStreets().add(street11); address1.getStreets().add(street12); Address address2 = new Address(); address2.setTypes(Collections.singletonList("office")); Street street21 = new Street("Oneway street", 100); Street street22 = new Street("Twowaystreet", 200); address2.getStreets().add(street21); address2.getStreets().add(street22); this.addresses.add(address1); this.addresses.add(address2); } @GraphQLQuery(name = "users") public List<User<String>> getUsersById(@GraphQLArgument(name = "id") @GraphQLId Integer id) { User<String> user = new User<>(); user.id = id; user.name = "Tatko"; user.uuid = UUID.randomUUID(); user.registrationDate = new Date(); user.addresses = addresses; User<String> user2 = new User<>(); user2.id = id + 1; user2.name = "Tzar"; user2.uuid = UUID.randomUUID(); user2.registrationDate = new Date(); user2.addresses = addresses; return Arrays.asList(user, user2); } @GraphQLQuery(name = "users") public List<User<String>> getUsersByEducation(@GraphQLArgument(name = "education") Education education) { return getUsersById(1); } // @GraphQLQuery(name = "user") // public <G> G getUsersByMagic(@GraphQLArgument(name = "magic") int magic) { // return (G)getUserById(magic); // } @GraphQLQuery(name = "users") public List<User<String>> getUsersByAnyEducation(@GraphQLArgument(name = "educations") List<? super T> educations) { return getUsersById(1); } @GraphQLQuery(name = "usersArr") @SuppressWarnings("unchecked") public User<String>[] getUsersByAnyEducationArray(@GraphQLArgument(name = "educations") T[] educations) { List<User<String>> users = getUsersById(1); return users.toArray(new User[0]); } @GraphQLQuery(name = "users") @GraphQLComplexity("2 * childScore") @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public List<User<String>> getUsersByRegDate(@GraphQLArgument(name = "regDate") Optional<Date> date) { return getUsersById(1); } @GraphQLQuery(name = "usersByDate") @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public List<User<String>> getUsersByDate(@GraphQLArgument(name = "regDate") Optional<Date> date) { return getUsersById(1); } @GraphQLMutation(name = "updateUsername") public User<String> updateUsername(@GraphQLContext User<String> user, @GraphQLArgument(name = "username") String username) { user.name = username; return user; } //TODO figure out how to deal with void returns :: return source object instead? // @GraphQLMutation(name="user") // public void updateTitle(@GraphQLContext User user, String title) { // user.title = title; // } @GraphQLQuery(name = "user") public User<String> getUserById(@GraphQLId(relayId = true) Integer wonkyName) { User<String> user = new User<>(); user.id = 1; user.name = "One Dude"; user.title = "The One"; user.uuid = UUID.randomUUID(); user.registrationDate = new Date(); user.addresses = addresses; return user; } @GraphQLQuery(name = "users") public List<User<String>> getUserByUuid(@GraphQLArgument(name = "uuid") UUID uuid) { return getUsersById(1); } @GraphQLQuery(name = "zmajs") public Collection<String> extraFieldAll(@GraphQLContext User<String> source) { return Arrays.asList("zmaj", "azdaha"); } @GraphQLQuery(name = "me") public Map<String, String> getCurrentUser() { Map<String, String> user = new HashMap<>(); user.put("id", "1000"); user.put("name", "Dyno"); return user; } @GraphQLMutation(name = "upMe") public Map<String, String> getUpdateCurrentUser(@GraphQLArgument(name = "updates") Map<String, String> updates) { return updates; } }
apache-2.0
sopeco/LPE-Common
org.lpe.common.jmeter/src/org/lpe/common/jmeter/JMeterWrapper.java
7278
/** * Copyright 2014 SAP 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 org.lpe.common.jmeter; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import org.lpe.common.jmeter.IO.DynamicPipedInputStream; import org.lpe.common.jmeter.IO.FilePoller; import org.lpe.common.jmeter.config.JMeterWorkloadConfig; import org.lpe.common.util.system.LpeSystemUtils; /** * Wrapper class which handles the connection to JMeter console process. * * The JMeterWrapper instance is capable of running several loadtests, the log of all gets combined. * * It should be possible to let several JMeter instances run their tests in parallel * * @author Jonas Kunz */ public final class JMeterWrapper { /** * location of the JMeter bin folder */ private Process jmeterProcess; private DynamicPipedInputStream logStream; /** * Singleton instance. */ private static JMeterWrapper instance; private JMeterWrapper() { // create the stream to provide log from JMETER logStream = new DynamicPipedInputStream(); } private static int getUniqueLogID() { return (int) System.currentTimeMillis(); } /** * @return singleton instance. */ public static synchronized JMeterWrapper getInstance() { if (instance == null) { instance = new JMeterWrapper(); } return instance; } /** * Starts a load test and then returns immediately. To wait for the test to finish use {@link waitForLoadTestFinish} * or poll {@link isLoadTestRunning} * * @param config The test configuration * @throws IOException if starting load fails */ public synchronized void startLoadTest(final JMeterWorkloadConfig config) throws IOException { // check whether a loadTest is already running if (jmeterProcess != null) { throw new RuntimeException("An Jmeter Process is already running, can only run one process per wrapperinstance"); } // create log file File logFile = createLogFile(config); List<String> cmd = buildCmdLine(config, logFile); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(new File(config.getPathToJMeterRootFolder())); // output needs to be redirected pb.redirectOutput(new File(config.getPathToJMeterRootFolder().concat("\\" + config.getDefaultOutputFile()))); // the error stream must be piped, otherwise noone takes the messages and JMeter waits to infinity // till someone receives the messages! pb.redirectErrorStream(true); jmeterProcess = pb.start(); // poll the log file final FilePoller poll = new FilePoller(logFile, logStream, true); if (config.getCreateLogFlag()) { poll.startPolling(); } final JMeterWrapper thisWrapper = this; // add a Thread that waits for the Process to terminate who then // notifies all other waiting Threads LpeSystemUtils.submitTask(new Runnable() { public void run() { try { jmeterProcess.waitFor(); // notify the log-thread that the process has ended and wait // for // polling to finish if (config.getCreateLogFlag()) { poll.endPolling(); } } catch (InterruptedException e) { throw new RuntimeException(e); } synchronized (thisWrapper) { jmeterProcess = null; thisWrapper.notifyAll(); } } }); } /** * Creates a new log file based on the passed configuration. * * @param config the {@link JMeterWorkloadConfig}, only the logfile flag is requested * @return the log file, <code>null</code> possible * @throws IOException on file creation fail */ private File createLogFile(JMeterWorkloadConfig config) throws IOException { File logFile = null; if (config.getCreateLogFlag()) { int logID = getUniqueLogID(); String logFilename = config.getPathToJMeterRootFolder() + "\\" + config.getLogFilePrefix() + logID; logFile = new File(logFilename); if (logFile.exists()) { logFile.delete(); } logFile.createNewFile(); } return logFile; } /** * Builds the command line to execute a Apache JMeter load script with the passed configuration. If the lof flag has * been set, the output will be redirected to the passed log file.<br /> * See more about JMeter command line configuration: http://jmeter.apache.org/usermanual/get-started.html. * * @param config the configuration for JMeter * @param logFile {@link File} which will get the JMeter output, if the configuration has the * @return List of the translated configuration into command line arguments */ private List<String> buildCmdLine(final JMeterWorkloadConfig config, File logFile) { List<String> cmd = new ArrayList<String>(); cmd.add("java"); cmd.add("-jar"); cmd.add("bin\\ApacheJMeter.jar"); cmd.add("-n"); // JMeter in non-gui mode cmd.add("-t"); // load script fiel path cmd.add("\"" + config.getPathToScript() + "\""); if (config.getCreateLogFlag()) { cmd.add("-j"); cmd.add(logFile.getAbsolutePath()); } // now add all the JMeter variables cmd.add("-Jp_durationSeconds=" + config.getExperimentDuration()); cmd.add("-Jp_numUsers=" + config.getNumUsers()); cmd.add("-Jp_thinkTimeMinMS=" + config.getThinkTimeMinimum()); cmd.add("-Jp_thinkTimeMaxMS=" + config.getThinkTimeMaximum()); double rampUpSecondsPerUser = config.getRampUpInterval() / config.getRampUpNumUsersPerInterval(); double coolDownSecondsPerUser = config.getCoolDownInterval() / config.getCoolDownNumUsersPerInterval(); cmd.add("-Jp_rampUpSecondsPerUser=" + rampUpSecondsPerUser); cmd.add("-Jp_rampDownSecondsPerUser=" + coolDownSecondsPerUser); if (config.getSamplingFileFlag()) { cmd.add("-Jp_resultFile=" + config.getPathToSamplingFile()); } // add custom properties Properties additionalProps = config.getAdditionalProperties(); for (Entry<Object, Object> property : additionalProps.entrySet()) { cmd.add("-J" + property.getKey() + "=" + property.getValue()); } return cmd; } /** * Returns the stream instance which belongs to this wrapper. It contains the log of the loadtests ran * * @return the stream instance - must not be closed */ public InputStream getLogStream() { return logStream; } /** * Checks whether a load test is running at the moment. * * @return <tt>true</tt> if running, <tt>false</tt> if not */ public boolean isLoadTestRunning() { return (jmeterProcess != null); } /** * Waits for the current loadtest to finish. If no loadtest is running, the method returns immediately. * * @throws InterruptedException if the Thread is interrupted */ public synchronized void waitForLoadTestFinish() throws InterruptedException { while (jmeterProcess != null) { this.wait(); } } }
apache-2.0
jecuendet/maven4openxava
dist/openxava/workspace/OpenXavaTest/pojo-src/org/openxava/test/model/Subfamily.java
2516
package org.openxava.test.model; import javax.persistence.*; import javax.persistence.Entity; import org.hibernate.annotations.*; import org.openxava.annotations.*; /** * * @author Javier Paniza */ @Entity @View(members= "number;" + "data {" + " familyNumber;" + " family;" + " description;" + " remarks" + "}" ) @Tab(name="CompleteSelect", properties="number, description, family", /* For JPA */ baseCondition = // JPA query using e as alias for main entity. Since v4.5 "select e.number, e.description, f.description " + "from Subfamily e, Family f " + "where e.familyNumber = f.number" /* For Hypersonic baseCondition = // With SQL until v4.4.x "select ${number}, ${description}, FAMILY.DESCRIPTION " + "from XAVATEST.SUBFAMILY, XAVATEST.FAMILY " + "where SUBFAMILY.FAMILY = FAMILY.NUMBER" */ /* For AS/400 baseCondition = // With SQL until v4.4.x "select ${number}, ${description}, XAVATEST.FAMILY.DESCRIPTION " + "from XAVATEST.SUBFAMILY, XAVATEST.FAMILY " + "where XAVATEST.SUBFAMILY.FAMILY = XAVATEST.FAMILY.NUMBER" */ ) public class Subfamily { @Id @GeneratedValue(generator="system-uuid") @Hidden @GenericGenerator(name="system-uuid", strategy = "uuid") private String oid; @Column(length=3) @Required @Stereotype("ZEROS_FILLED") private int number; @Required @Stereotype("FAMILY") @Column(name="FAMILY") private int familyNumber; @Column(length=40) @Required private String description; @Column(length=400) @Stereotype("MEMO") @org.hibernate.annotations.Type(type="org.openxava.types.NotNullStringType") private String remarks; @Transient @Column(length=40) @Hidden private String family; // Only for column description in tab public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getFamilyNumber() { return familyNumber; } public void setFamilyNumber(int familyNumber) { this.familyNumber = familyNumber; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getFamily() { return family; } public void setFamily(String family) { this.family = family; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/transform/ChangePasswordRequestMarshaller.java
2157
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.identitymanagement.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.identitymanagement.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * ChangePasswordRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ChangePasswordRequestMarshaller implements Marshaller<Request<ChangePasswordRequest>, ChangePasswordRequest> { public Request<ChangePasswordRequest> marshall(ChangePasswordRequest changePasswordRequest) { if (changePasswordRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } Request<ChangePasswordRequest> request = new DefaultRequest<ChangePasswordRequest>(changePasswordRequest, "AmazonIdentityManagement"); request.addParameter("Action", "ChangePassword"); request.addParameter("Version", "2010-05-08"); request.setHttpMethod(HttpMethodName.POST); if (changePasswordRequest.getOldPassword() != null) { request.addParameter("OldPassword", StringUtils.fromString(changePasswordRequest.getOldPassword())); } if (changePasswordRequest.getNewPassword() != null) { request.addParameter("NewPassword", StringUtils.fromString(changePasswordRequest.getNewPassword())); } return request; } }
apache-2.0
revdaalex/learn_java
chapter3/LSP/ChapterI/src/main/java/ru/revdaalex/lsp/chapterI/storage/Warehouse.java
900
package ru.revdaalex.lsp.chapterI.storage; import ru.revdaalex.lsp.chapterI.food.Food; import ru.revdaalex.lsp.chapterI.interfaces.Storage; import java.util.ArrayList; /** * Warehouse class. * Created by revdaalex on 04.07.2016. */ public class Warehouse implements Storage { /** * ArrayList Warehouse. */ private final ArrayList<Food> warehouse = new ArrayList<Food>(); /** * Implements interface method add in Warehouse. * @param food */ public void add(Food food) { this.warehouse.add(food); } /** * Implements interface method sortQuality in Warehouse. * @param food * @return */ public boolean sortQuality(Food food) { if (food.getExpiryDateInPercents() < 25){ return true; } return false; } public ArrayList<Food> getFood() { return warehouse; } }
apache-2.0
DanielPitts/net.virtualinfinity.telnet
src/main/java/net/virtualinfinity/telnet/Session.java
820
package net.virtualinfinity.telnet; import net.virtualinfinity.nio.EventLoop; import java.io.Closeable; /** * Provides access to the public aspects of the telnet session. * * @see SessionListener * @see ClientStarter#connect(EventLoop, String, SessionListener) * @see ClientStarter#connect(EventLoop, String, int, SessionListener) * * @author <a href='mailto:Daniel@coloraura.com'>Daniel Pitts</a> */ public interface Session extends Closeable { /** * @return an helper for managing the state of options on this session. */ Options options(); /** * @return the output data stream. */ OutputChannel outputChannel(); /** * @return the SubNegotiationOutputChannel for option sub-negotiation. */ SubNegotiationOutputChannel subNegotiationOutputChannel(); }
apache-2.0
CSCSI/Triana
triana-gui/src/main/java/org/trianacode/gui/windows/ComboDialog.java
6839
/* * The University of Wales, Cardiff Triana Project Software License (Based * on the Apache Software License Version 1.1) * * Copyright (c) 2007 University of Wales, Cardiff. All rights reserved. * * Redistribution and use of the software 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. * * 3. The end-user documentation included with the redistribution, if any, * must include the following acknowledgment: "This product includes * software developed by the University of Wales, Cardiff for the Triana * Project (http://www.trianacode.org)." Alternately, this * acknowledgment may appear in the software itself, if and wherever * such third-party acknowledgments normally appear. * * 4. The names "Triana" and "University of Wales, Cardiff" must not be * used to endorse or promote products derived from this software * without prior written permission. For written permission, please * contact triana@trianacode.org. * * 5. Products derived from this software may not be called "Triana," nor * may Triana appear in their name, without prior written permission of * the University of Wales, Cardiff. * * 6. This software may not be sold, used or incorporated into any product * for sale to third parties. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 UNIVERSITY OF WALES, CARDIFF OR ITS 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. * * ------------------------------------------------------------------------ * * This software consists of voluntary contributions made by many * individuals on behalf of the Triana Project. For more information on the * Triana Project, please see. http://www.trianacode.org. * * This license is based on the BSD license as adopted by the Apache * Foundation and is governed by the laws of England and Wales. * */ package org.trianacode.gui.windows; import org.trianacode.gui.util.Env; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A dialog for selecting an item from a list * * @author Ian Wang * @version $Revision: 4048 $ */ public class ComboDialog extends JDialog implements ActionListener { /** * the main list */ private JComboBox combo = new JComboBox(new DefaultComboBoxModel()); /** * the label prompt */ private JLabel label = new JLabel(); /** * the ok and cancel buttons */ private JButton ok = new JButton(Env.getString("OK")); private JButton cancel = new JButton(Env.getString("Cancel")); /** * a flag indicating whether the ok button was clicked */ private boolean approve = false; /** * Constructs a modal combo dialog offering the specified item choices */ public ComboDialog(String[] items, Frame parent) { super(parent); initialise(items, false); } /** * Constructs a modal combo dialog offering the specified item choices */ public ComboDialog(String[] items, Dialog parent) { super(parent); initialise(items, false); } /** * Constructs a modal combo dialog offering the specified item choices * * @param title the dialog title * @param editable a flag indicating whether the combo is editable */ public ComboDialog(String[] items, Frame parent, String title, boolean editable) { super(parent, title, true); initialise(items, editable); } /** * Constructs a modal combo dialog offering the specified item choices * * @param title the dialog title * @param editable a flag indicating whether the combo is editable */ public ComboDialog(String[] items, Dialog parent, String title, boolean editable) { super(parent, title, true); initialise(items, editable); } /** * Initialises the dialog */ private void initialise(String[] items, boolean editable) { getContentPane().setLayout(new BorderLayout()); DefaultComboBoxModel model = (DefaultComboBoxModel) combo.getModel(); combo.setEditable(editable); combo.setPrototypeDisplayValue("01234567890123456789"); for (int count = 0; count < items.length; count++) { model.addElement(items[count]); } JPanel listpanel = new JPanel(new BorderLayout(3, 0)); listpanel.add(label, BorderLayout.WEST); listpanel.add(combo, BorderLayout.CENTER); listpanel.setBorder(new EmptyBorder(3, 3, 3, 3)); getContentPane().add(listpanel, BorderLayout.CENTER); JPanel buttonpanel = new JPanel(); buttonpanel.add(ok); buttonpanel.add(cancel); ok.addActionListener(this); cancel.addActionListener(this); getContentPane().add(buttonpanel, BorderLayout.SOUTH); pack(); } /** * Sets the user prompt */ public void setLabel(String prompt) { label.setText(prompt); pack(); } /** * @return the user prompt */ public String getLabel() { return label.getText(); } /** * @return true if the ok button was clicked */ public boolean isApproved() { return approve; } /** * @return an array of the selected items, or null if the cancel button was clicked */ public String getSelectedItem() { if (!approve) { return null; } else { return (String) combo.getSelectedItem(); } } public void actionPerformed(ActionEvent event) { if (event.getSource() == ok) { approve = true; } setVisible(false); dispose(); } }
apache-2.0
tonit/karafonexam2
jaas/config/src/main/java/org/apache/karaf/jaas/config/impl/OsgiKeystoreManager.java
4137
/* * 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.karaf.jaas.config.impl; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocketFactory; import org.apache.karaf.jaas.config.KeystoreInstance; import org.apache.karaf.jaas.config.KeystoreIsLocked; import org.apache.karaf.jaas.config.KeystoreManager; /** * Implementation of KeystoreManager */ public class OsgiKeystoreManager implements KeystoreManager { private List<KeystoreInstance> keystores = new CopyOnWriteArrayList<KeystoreInstance>(); public void register(KeystoreInstance keystore, Map<String,?> properties) { keystores.add(keystore); } public void unregister(KeystoreInstance keystore, Map<String,?> properties) { keystores.remove(keystore); } public KeystoreInstance getKeystore(String name) { KeystoreInstance keystore = null; for (KeystoreInstance ks : keystores) { if (ks.getName().equals(name)) { if (keystore == null || keystore.getRank() < ks.getRank()) { keystore = ks; } } } return keystore; } public SSLContext createSSLContext(String provider, String protocol, String algorithm, String keyStore, String keyAlias, String trustStore) throws GeneralSecurityException { KeystoreInstance keyInstance = getKeystore(keyStore); if (keyInstance != null && keyInstance.isKeystoreLocked()) { throw new KeystoreIsLocked("Keystore '" + keyStore + "' is locked"); } if (keyInstance != null && keyInstance.isKeyLocked(keyAlias)) { throw new KeystoreIsLocked("Key '" + keyAlias + "' in keystore '" + keyStore + "' is locked"); } KeystoreInstance trustInstance = trustStore == null ? null : getKeystore(trustStore); if (trustInstance != null && trustInstance.isKeystoreLocked()) { throw new KeystoreIsLocked("Keystore '" + trustStore + "' is locked"); } SSLContext context; if (provider == null) { context = SSLContext.getInstance(protocol); } else { context = SSLContext.getInstance(protocol, provider); } context.init(keyInstance == null ? null : keyInstance.getKeyManager(algorithm, keyAlias), trustInstance == null ? null : trustInstance.getTrustManager(algorithm), new SecureRandom()); return context; } public SSLServerSocketFactory createSSLServerFactory(String provider, String protocol, String algorithm, String keyStore, String keyAlias, String trustStore) throws GeneralSecurityException { SSLContext context = createSSLContext(provider, protocol, algorithm, keyStore, keyAlias, trustStore); return context.getServerSocketFactory(); } public SSLSocketFactory createSSLFactory(String provider, String protocol, String algorithm, String keyStore, String keyAlias, String trustStore) throws GeneralSecurityException { SSLContext context = createSSLContext(provider, protocol, algorithm, keyStore, keyAlias, trustStore); return context.getSocketFactory(); } }
apache-2.0
GwtMaterialDesign/gwt-material-table
src/main/java/gwt/material/design/client/data/events/RowsVisibleHandler.java
860
/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2017 GwtMaterialDesign * %% * 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 gwt.material.design.client.data.events; import com.google.gwt.event.shared.EventHandler; public interface RowsVisibleHandler extends EventHandler { void onRowsVisible(RowsVisibleEvent event); }
apache-2.0
joewalnes/idea-community
plugins/copyright/src/com/maddyhome/idea/copyright/pattern/VelocityHelper.java
4033
/* * 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.maddyhome.idea.copyright.pattern; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import com.maddyhome.idea.copyright.CopyrightManager; import org.apache.commons.collections.ExtendedProperties; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.log.SimpleLog4JLogSystem; import java.io.StringWriter; public class VelocityHelper { public static String evaluate(PsiFile file, Project project, Module module, String template) { VelocityEngine engine = getEngine(); VelocityContext vc = new VelocityContext(); vc.put("today", new DateInfo()); if (file != null) vc.put("file", new FileInfo(file)); if (project != null) vc.put("project", new ProjectInfo(project)); if (module != null) vc.put("module", new ModuleInfo(module)); vc.put("username", System.getProperty("user.name")); try { StringWriter sw = new StringWriter(); boolean stripLineBreak = false; if (template.endsWith("$")) { template += getVelocitySuffix(); stripLineBreak = true; } engine.evaluate(vc, sw, CopyrightManager.class.getName(), template); final String result = sw.getBuffer().toString(); return stripLineBreak ? StringUtil.trimEnd(result, getVelocitySuffix()) : result; } catch (Exception e) { return ""; } } private static String getVelocitySuffix() { return "\n"; } public static void verify(String text) throws Exception { VelocityEngine engine = getEngine(); VelocityContext vc = new VelocityContext(); vc.put("today", new DateInfo()); StringWriter sw = new StringWriter(); if (text.endsWith("$")) { text += getVelocitySuffix(); } engine.evaluate(vc, sw, CopyrightManager.class.getName(), text); } private static synchronized VelocityEngine getEngine() { if (instance == null) { try { VelocityEngine engine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.addProperty(VelocityEngine.RESOURCE_LOADER, "file"); extendedProperties.addProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); extendedProperties.addProperty("file.resource.loader.path", PathManager.getPluginsPath() + "/Copyright/resources"); extendedProperties.addProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, SimpleLog4JLogSystem.class.getName()); extendedProperties .addProperty("runtime.log.logsystem.log4j.category", CopyrightManager.class.getName()); engine.setExtendedProperties(extendedProperties); engine.init(); instance = engine; } catch (Exception e) { } } return instance; } private VelocityHelper() { } private static VelocityEngine instance; }
apache-2.0
ederign/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/test/java/org/kie/workbench/common/stunner/core/client/session/command/impl/ExportToPngSessionCommandTest.java
3183
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.stunner.core.client.session.command.impl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler; import org.kie.workbench.common.stunner.core.client.canvas.util.CanvasFileExport; import org.kie.workbench.common.stunner.core.client.session.command.ClientSessionCommand; import org.kie.workbench.common.stunner.core.client.session.impl.AbstractClientSession; import org.kie.workbench.common.stunner.core.diagram.Diagram; import org.kie.workbench.common.stunner.core.diagram.Metadata; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.uberfire.backend.vfs.Path; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ExportToPngSessionCommandTest { private static final String FILE_NAME = "file-name1"; @Mock private CanvasFileExport canvasFileExport; @Mock private AbstractClientSession session; @Mock private AbstractCanvasHandler canvasHandler; @Mock private Diagram diagram; @Mock private Metadata metadata; @Mock private Path path; @Mock private ClientSessionCommand.Callback callback; private ExportToPngSessionCommand tested; @Before public void setup() throws Exception { when(session.getCanvasHandler()).thenReturn(canvasHandler); when(canvasHandler.getDiagram()).thenReturn(diagram); when(diagram.getMetadata()).thenReturn(metadata); when(metadata.getPath()).thenReturn(path); when(path.getFileName()).thenReturn(FILE_NAME); this.tested = new ExportToPngSessionCommand(canvasFileExport); this.tested.bind(session); } @Test public void testExport() { this.tested.execute(callback); verify(canvasFileExport, times(1)).exportToPng(eq(canvasHandler), eq(FILE_NAME)); verify(canvasFileExport, never()).exportToJpg(any(AbstractCanvasHandler.class), anyString()); verify(canvasFileExport, never()).exportToPdf(any(AbstractCanvasHandler.class), anyString()); } }
apache-2.0
apache/tapestry4
framework/src/java/org/apache/tapestry/listener/ListenerMap.java
1865
// Copyright 2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.listener; import java.util.Collection; import org.apache.tapestry.IActionListener; /** * @author Howard M. Lewis Ship */ public interface ListenerMap { /** * Gets a listener for the given name (which is both a property name and a method name). The * listener is created as needed, but is also cached for later use. The returned object * implements the {@link org.apache.tapestry.IActionListener}. * * @param name * the name of the method to invoke (the most appropriate method will be selected if * there are multiple overloadings of the same method name) * @returns an object implementing {@link IActionListener}. * @throws ApplicationRuntimeException * if the listener can not be created. */ public IActionListener getListener(String name); /** * Returns an unmodifiable collection of the names of the listeners implemented by the target * class. * * @since 1.0.6 */ public Collection getListenerNames(); /** * Returns true if this ListenerMapImpl can provide a listener with the given name. * * @since 2.2 */ public boolean canProvideListener(String name); }
apache-2.0
alexander071/cf-java-client
cloudfoundry-client/src/test/java/org/cloudfoundry/client/v3/deployments/GetDeploymentTest.java
1037
/* * Copyright 2013-2019 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.cloudfoundry.client.v3.deployments; import org.junit.Test; public final class GetDeploymentTest { @Test(expected = IllegalStateException.class) public void noDeploymentId() { GetDeploymentRequest.builder() .build(); } @Test public void valid() { GetDeploymentRequest.builder() .deploymentId("deployment-id") .build(); } }
apache-2.0
jjYBdx4IL/misc
ecs/src/main/java/org/apache/ecs/vxml/Link.java
4470
/* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2003 The Apache Software Foundation. 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. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Jakarta Element Construction Set", * "Jakarta ECS" , and "Apache Software Foundation" must not be used * to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * "Jakarta Element Construction Set" nor "Jakarta ECS" nor may "Apache" * appear in their names without prior written permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ecs.vxml; /** This class implements the link element @author Written by <a href="mailto:jcarol@us.ibm.com">Carol Jones</a> */ public class Link extends VXMLElement { /** Basic constructor. You need to set the attributes using the set* methods. */ public Link() { super("link"); } /** Sets the next="" attribute @param next the next="" attribute */ public Link setNext(String next) { addAttribute("next", next); return this; } /** Sets the expr="" attribute @param expr the expr="" attribute */ public Link setExpr(String expr) { addAttribute("expr", expr); return this; } /** Sets the event="" attribute @param event the event="" attribute */ public Link setEvent(String event) { addAttribute("event", event); return this; } /** Sets the caching="" attribute @param caching the caching="" attribute */ public Link setCaching(String caching) { addAttribute("caching", caching); return this; } /** Sets the fetchaudio="" attribute @param fetchaudio the fetchaudio="" attribute */ public Link setFetchaudio(String fetchaudio) { addAttribute("fetchaudio", fetchaudio); return this; } /** Sets the fetchint="" attribute @param fetchint the fetchint="" attribute */ public Link setFetchint(String fetchint) { addAttribute("fetchint", fetchint); return this; } /** Sets the fetchtimeout="" attribute @param fetchtimeout the fetchtimeout="" attribute */ public Link setFetchtimeout(String fetchtimeout) { addAttribute("fetchtimeout", fetchtimeout); return this; } }
apache-2.0
Kandru/ts3luna
src/main/java/eu/kandru/luna/util/LogHelper.java
774
package eu.kandru.luna.util; import lombok.experimental.UtilityClass; import javax.servlet.http.HttpServletRequest; /** * Helper class for logging output. * * @author jko */ @UtilityClass public class LogHelper { /** * Formats a {@link HttpServletRequest} for logging by extracting the important information. * * @param request the request. * @return this can be logged. */ public String formatRequest(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); sb.append("request from ") .append(request.getRemoteAddr()) .append(" via ") .append(request.getMethod()) .append(" to ") .append(request.getServletPath()); return sb.toString(); } }
apache-2.0
drtodolittle/rest-api
firebase-util/src/main/java/de/drtodolittle/firebase/impl/FirebaseTokenService.java
1784
/** * */ package de.drtodolittle.firebase.impl; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseCredentials; import com.google.firebase.auth.FirebaseToken; import com.google.firebase.tasks.Task; import de.drtodolittle.firebase.api.TokenService; /** * @author Guenther_D * */ public class FirebaseTokenService implements TokenService { public static final String PID = "de.drtodolittle.firebase.firebasetokenservice"; public FirebaseTokenService(String servicePrivateKey, String databaseUrl) throws Exception { InputStream privateKeyStream = null; if (System.getenv("FIREBASE_TOKEN") != null) { privateKeyStream = new ByteArrayInputStream(System.getenv("FIREBASE_TOKEN").getBytes()); } else { privateKeyStream = new FileInputStream(servicePrivateKey); } FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.fromCertificate(privateKeyStream)) .setDatabaseUrl(databaseUrl) .build(); FirebaseApp.initializeApp(options); } /* (non-Javadoc) * @see de.drtodolittle.firebase.api.TokenService#verify(java.lang.String) */ public String verify(String token) { String email = null; Task<FirebaseToken> task = FirebaseAuth.getInstance().verifyIdToken(token); while (!task.isComplete()) { try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (task.isSuccessful()) { email = task.getResult().getEmail(); } else { task.getException().printStackTrace(); } return email; } }
apache-2.0
asmilk/ascloud
src/main/java/asmilk/ascloud/cloud/service/document/CloudantClientCreator.java
1088
package asmilk.ascloud.cloud.service.document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.service.AbstractServiceConnectorCreator; import org.springframework.cloud.service.ServiceConnectorConfig; import com.cloudant.client.api.ClientBuilder; import com.cloudant.client.api.CloudantClient; import asmilk.ascloud.cloud.service.common.CloudantServiceInfo; public class CloudantClientCreator extends AbstractServiceConnectorCreator<CloudantClient, CloudantServiceInfo> { private static final Logger LOG = LoggerFactory.getLogger(CloudantClientCreator.class); @Override public CloudantClient create(CloudantServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) { CloudantClient cloudantClient = ClientBuilder.account(serviceInfo.getHost().replace(".cloudant.com", "")) .username(serviceInfo.getUserName()).password(serviceInfo.getPassword()).build(); String serverVersion = cloudantClient.serverVersion(); LOG.info("serverVersion: {}", serverVersion); return cloudantClient; } }
apache-2.0
oeg-upm/epnoi
storage/src/main/java/org/epnoi/storage/Config.java
770
package org.epnoi.storage; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * Created by cbadenes on 21/12/15. */ @Configuration("storage") @ComponentScan({"org.epnoi.storage","org.epnoi.eventbus"}) @PropertySource({"classpath:storage.properties","classpath:eventbus.properties"}) public class Config { //To resolve ${} in @Value @Bean public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
apache-2.0
kerveros/Android-examples
app/src/main/java/com/neko/androidexamples/recycler_view/RecyclerViewActivity.java
3893
package com.neko.androidexamples.recycler_view; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.neko.androidexamples.R; import com.neko.androidexamples.list_view.Model; import java.util.ArrayList; /** * This class shows how to implement a List with RecyclerView and CardView components * These dependencies must be added in App build.gradle : * - 'com.android.support:recyclerview-v7:26.+' * - 'com.android.support:cardview-v7:26.+' * * @link https://developer.android.com/training/material/lists-cards.html */ public class RecyclerViewActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private RecyclerView.Adapter adapter; private RecyclerView.LayoutManager mLayoutManager; private ArrayList<Model> dataToBePopulated; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view); dataToBePopulated = getDummyData(); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); // specify an adapter (see also next example) adapter = new RecyclerViewAdapter(dataToBePopulated, onDeleteButtonClickedListener); mRecyclerView.setAdapter(adapter); } /** * Callback for Delete Button * @see RecyclerViewAdapter */ RecyclerViewAdapter.OnDeleteButtonClickedListener onDeleteButtonClickedListener = new RecyclerViewAdapter.OnDeleteButtonClickedListener() { @Override public void onDeleteClicked(int position) { removeItem(position); } }; /** * Removes item at current position * * @param position */ private void removeItem(int position) { // Removing current item dataToBePopulated.remove(position); //adapter.notifyDataSetChanged(); // it doesn't show animation // Notifying with animation adapter.notifyItemRemoved(position); } /** * Adds new Item to the list */ private void addNewItem() { dataToBePopulated.add(new Model( R.mipmap.ic_launcher_round, "New Name", "New Description")); //adapter.notifyDataSetChanged(); // it doesn't show animation // Notifying with animation adapter.notifyItemInserted(dataToBePopulated.size()); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_view_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.action_add: addNewItem(); return true; default: return super.onOptionsItemSelected(item); } } /** * Retrieve dummy data to be populated into ListView * * @return List of Models */ private ArrayList<Model> getDummyData() { ArrayList<Model> dummyModels = new ArrayList<>(); for (int i = 0; i < 3; i++) { dummyModels.add(new Model( R.mipmap.ic_launcher_round, "Name: " + i, "Description: " + i)); } return dummyModels; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/metrics/internal/ServiceMetricTypeGuesser.java
2121
/* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.metrics.internal; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.Request; import com.amazonaws.metrics.AwsSdkMetrics; import com.amazonaws.metrics.ServiceMetricType; import com.amazonaws.metrics.SimpleThroughputMetricType; import com.amazonaws.metrics.ThroughputMetricType; /** * An internal helper factory for generating service specific {@link ServiceMetricType} * without causing compile time dependency on the service specific artifacts. * * There exists a S3ServiceMetricTest.java unit test in the S3 client library * that ensures this class behaves consistently with the service metric enum * defined in the S3 client library. */ public enum ServiceMetricTypeGuesser { ; /** * Returned the best-guessed throughput metric type for the given request, * or null if there is none or if metric is disabled. */ public static ThroughputMetricType guessThroughputMetricType( final Request<?> req, final String metricNameSuffix, final String byteCountMetricNameSuffix) { if (!AwsSdkMetrics.isMetricsEnabled()) return null; // metric disabled Object orig = req.getOriginalRequestObject(); if (orig.getClass().getName().startsWith("com.amazonaws.services.s3")) { return new SimpleThroughputMetricType( "S3" + metricNameSuffix, req.getServiceName(), "S3" + byteCountMetricNameSuffix); } return null; } }
apache-2.0
EsupPortail/esup-catapp-admin
src/main/java/org/esupportail/catapp/admin/domain/config/SmtpConfig.java
2612
package org.esupportail.catapp.admin.domain.config; import org.esupportail.commons.mail.CachingEmailSmtpService; import org.esupportail.commons.mail.SimpleSmtpService; import org.esupportail.commons.mail.SmtpService; import org.esupportail.commons.mail.model.SmtpServerData; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.Cache; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import javax.inject.Inject; import javax.inject.Named; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import java.io.UnsupportedEncodingException; @Configuration @Import({ CacheConfig.class }) public class SmtpConfig { @Value("${smtp.host}") private String smtpHost; @Value("${smtp.port}") private Integer smtpPort; @Value("${smtp.user}") private String smtpUser; @Value("${smtp.password}") private String smtpPwd; @Value("${smtp.fromEmail}") private String fromEmail; @Value("${smtp.fromName}") private String fromName; @Value("${smtp.interceptAll}") private boolean interceptAll; @Value("${smtp.interceptEmail}") private String interceptEmail; @Value("${smtp.interceptName}") private String interceptName; @Value("${smtp.charset}") private String charset; @Value("${exceptionHandling.email}") private String emailException; @Inject @Named("mailCache") private Cache mailCache; @Bean public SmtpServerData smtpServer() { return SmtpServerData.builder() .host(smtpHost) .port(smtpPort) .user(smtpUser) .password(smtpPwd) .build(); } @Bean public SmtpService smtpService() throws UnsupportedEncodingException { final InternetAddress from = new InternetAddress(fromEmail, fromName); final InternetAddress intercept = new InternetAddress(interceptEmail, interceptName); return CachingEmailSmtpService.create( SimpleSmtpService .builder(from, null, intercept) .interceptAll(interceptAll) .charset(charset) .server(smtpServer()) .build(), mailCache); } @Bean public InternetAddress exceptionAddress() throws AddressException { return new InternetAddress(emailException); } }
apache-2.0
Qi4j/qi4j-sdk
extensions/entitystore-riak/src/main/java/org/apache/polygene/entitystore/riak/RiakEntityStoreMixin.java
15601
/* * 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.polygene.entitystore.riak; import com.basho.riak.client.api.RiakClient; import com.basho.riak.client.api.commands.buckets.StoreBucketProperties; import com.basho.riak.client.api.commands.kv.DeleteValue; import com.basho.riak.client.api.commands.kv.FetchValue; import com.basho.riak.client.api.commands.kv.ListKeys; import com.basho.riak.client.api.commands.kv.StoreValue; import com.basho.riak.client.core.RiakCluster; import com.basho.riak.client.core.RiakNode; import com.basho.riak.client.core.query.Location; import com.basho.riak.client.core.query.Namespace; import com.basho.riak.client.core.util.HostAndPort; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.Provider; import java.security.Security; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.polygene.api.common.InvalidApplicationException; import org.apache.polygene.api.configuration.Configuration; import org.apache.polygene.api.entity.EntityDescriptor; import org.apache.polygene.api.entity.EntityReference; import org.apache.polygene.api.injection.scope.This; import org.apache.polygene.api.service.ServiceActivation; import org.apache.polygene.spi.entitystore.EntityNotFoundException; import org.apache.polygene.spi.entitystore.EntityStoreException; import org.apache.polygene.spi.entitystore.helpers.MapEntityStore; /** * Riak Protobuf implementation of MapEntityStore. */ public class RiakEntityStoreMixin implements ServiceActivation, MapEntityStore, RiakAccessors { private static final String DEFAULT_HOST = "127.0.0.1"; private static final int DEFAULT_PORT = 8087; @This private Configuration<RiakEntityStoreConfiguration> configuration; private RiakClient riakClient; private Namespace namespace; @Override public void activateService() throws Exception { // Load configuration configuration.refresh(); RiakEntityStoreConfiguration config = configuration.get(); String bucketName = config.bucket().get(); List<String> hosts = config.hosts().get(); // Setup Riak Cluster Client List<HostAndPort> hostsAndPorts = parseHosts( hosts ); RiakNode.Builder nodeBuilder = new RiakNode.Builder(); nodeBuilder = configureNodes( config, nodeBuilder ); nodeBuilder = configureAuthentication( config, nodeBuilder ); List<RiakNode> nodes = new ArrayList<>(); for( HostAndPort host : hostsAndPorts ) { nodes.add( nodeBuilder.withRemoteAddress( host ).build() ); } RiakCluster.Builder clusterBuilder = RiakCluster.builder( nodes ); clusterBuilder = configureCluster( config, clusterBuilder ); // Start Riak Cluster RiakCluster cluster = clusterBuilder.build(); cluster.start(); namespace = new Namespace( bucketName ); riakClient = new RiakClient( cluster ); // Initialize Bucket riakClient.execute( new StoreBucketProperties.Builder( namespace ).build() ); } private RiakNode.Builder configureNodes( RiakEntityStoreConfiguration config, RiakNode.Builder nodeBuilder ) { Integer minConnections = config.minConnections().get(); Integer maxConnections = config.maxConnections().get(); Boolean blockOnMaxConnections = config.blockOnMaxConnections().get(); Integer connectionTimeout = config.connectionTimeout().get(); Integer idleTimeout = config.idleTimeout().get(); if( minConnections != null ) { nodeBuilder = nodeBuilder.withMinConnections( minConnections ); } if( maxConnections != null ) { nodeBuilder = nodeBuilder.withMaxConnections( maxConnections ); } nodeBuilder = nodeBuilder.withBlockOnMaxConnections( blockOnMaxConnections ); if( connectionTimeout != null ) { nodeBuilder = nodeBuilder.withConnectionTimeout( connectionTimeout ); } if( idleTimeout != null ) { nodeBuilder = nodeBuilder.withIdleTimeout( idleTimeout ); } return nodeBuilder; } private RiakNode.Builder configureAuthentication( RiakEntityStoreConfiguration config, RiakNode.Builder nodeBuilder ) throws IOException, GeneralSecurityException { String username = config.username().get(); String password = config.password().get(); String truststoreType = config.truststoreType().get(); String truststorePath = config.truststorePath().get(); String truststorePassword = config.truststorePassword().get(); String keystoreType = config.keystoreType().get(); String keystorePath = config.keystorePath().get(); String keystorePassword = config.keystorePassword().get(); String keyPassword = config.keyPassword().get(); if( username != null ) { // Eventually load BouncyCastle to support PKCS12 if( "PKCS12".equals( keystoreType ) || "PKCS12".equals( truststoreType ) ) { Provider bc = Security.getProvider( "BC" ); if( bc == null ) { try { Class<?> bcType = Class.forName( "org.bouncycastle.jce.provider.BouncyCastleProvider" ); Security.addProvider( (Provider) bcType.newInstance() ); } catch( Exception ex ) { throw new InvalidApplicationException( "Need to open a PKCS#12 but unable to register BouncyCastle, check your classpath", ex ); } } } KeyStore truststore = loadStore( truststoreType, truststorePath, truststorePassword ); if( keystorePath != null ) { KeyStore keyStore = loadStore( keystoreType, keystorePath, keystorePassword ); nodeBuilder = nodeBuilder.withAuth( username, password, truststore, keyStore, keyPassword ); } else { nodeBuilder = nodeBuilder.withAuth( username, password, truststore ); } } return nodeBuilder; } private KeyStore loadStore( String type, String path, String password ) throws IOException, GeneralSecurityException { try( InputStream keystoreInput = new FileInputStream( new File( path ) ) ) { KeyStore keyStore = KeyStore.getInstance( type ); keyStore.load( keystoreInput, password.toCharArray() ); return keyStore; } } private RiakCluster.Builder configureCluster( RiakEntityStoreConfiguration config, RiakCluster.Builder clusterBuilder ) { Integer clusterExecutionAttempts = config.clusterExecutionAttempts().get(); if( clusterExecutionAttempts != null ) { clusterBuilder = clusterBuilder.withExecutionAttempts( clusterExecutionAttempts ); } return clusterBuilder; } @Override public void passivateService() throws Exception { riakClient.shutdown(); riakClient = null; namespace = null; } @Override public RiakClient riakClient() { return riakClient; } @Override public Namespace riakNamespace() { return namespace; } @Override public Reader get( EntityReference entityReference ) { try { Location location = new Location( namespace, entityReference.identity().toString() ); FetchValue fetch = new FetchValue.Builder( location ).build(); FetchValue.Response response = riakClient.execute( fetch ); if( response.isNotFound() ) { throw new EntityNotFoundException( entityReference ); } String jsonState = response.getValue( String.class ); return new StringReader( jsonState ); } catch( InterruptedException | ExecutionException ex ) { throw new EntityStoreException( "Unable to get Entity " + entityReference.identity(), ex ); } } @Override public void applyChanges( MapChanges changes ) { try { changes.visitMap( new MapChanger() { @Override public Writer newEntity( EntityReference ref, EntityDescriptor entityDescriptor ) { return new StringWriter( 1000 ) { @Override public void close() throws IOException { try { super.close(); StoreValue store = new StoreValue.Builder( toString() ) .withLocation( new Location( namespace, ref.identity().toString() ) ) .build(); riakClient.execute( store ); } catch( InterruptedException | ExecutionException ex ) { throw new EntityStoreException( "Unable to apply entity change: newEntity", ex ); } } }; } @Override public Writer updateEntity( MapChange mapChange ) { return new StringWriter( 1000 ) { @Override public void close() throws IOException { try { super.close(); EntityReference reference = mapChange.reference(); String identity = reference.identity().toString(); Location location = new Location( namespace, identity ); FetchValue fetch = new FetchValue.Builder( location ).build(); FetchValue.Response response = riakClient.execute( fetch ); if( response.isNotFound() ) { throw new EntityNotFoundException( reference ); } StoreValue store = new StoreValue.Builder( toString() ) .withLocation( location ) .build(); riakClient.execute( store ); } catch( InterruptedException | ExecutionException ex ) { throw new EntityStoreException( "Unable to apply entity change: updateEntity", ex ); } } }; } @Override public void removeEntity( EntityReference ref, EntityDescriptor entityDescriptor ) { try { Location location = new Location( namespace, ref.identity().toString() ); FetchValue fetch = new FetchValue.Builder( location ).build(); FetchValue.Response response = riakClient.execute( fetch ); if( response.isNotFound() ) { throw new EntityNotFoundException( ref ); } DeleteValue delete = new DeleteValue.Builder( location ).build(); riakClient.execute( delete ); } catch( InterruptedException | ExecutionException ex ) { throw new EntityStoreException( "Unable to apply entity change: removeEntity", ex ); } } } ); } catch( Exception ex ) { throw new EntityStoreException( "Unable to apply entity changes.", ex ); } } @Override public Stream<Reader> entityStates() { try { ListKeys listKeys = new ListKeys.Builder( namespace ).build(); ListKeys.Response listKeysResponse = riakClient.execute( listKeys ); return StreamSupport .stream( listKeysResponse.spliterator(), false ) .map( location -> { try { FetchValue fetch = new FetchValue.Builder( location ).build(); FetchValue.Response response = riakClient.execute( fetch ); return response.getValue( String.class ); } catch( InterruptedException | ExecutionException ex ) { throw new EntityStoreException( "Unable to get entity states.", ex ); } } ) .filter( Objects::nonNull ) .map( StringReader::new ); } catch( InterruptedException | ExecutionException ex ) { throw new EntityStoreException( "Unable to get entity states.", ex ); } } private List<HostAndPort> parseHosts( List<String> hosts ) { if( hosts.isEmpty() ) { hosts.add( DEFAULT_HOST ); } List<HostAndPort> addresses = new ArrayList<>( hosts.size() ); for( String host : hosts ) { String[] splitted = host.split( ":" ); int port = DEFAULT_PORT; if( splitted.length > 1 ) { host = splitted[ 0 ]; port = Integer.valueOf( splitted[ 1 ] ); } addresses.add( HostAndPort.fromParts( host, port ) ); } return addresses; } }
apache-2.0
spidaman/ant-eclipse
src/prantl/ant/eclipse/ClassPathGenerator.java
14121
// Copyright 2005-2006 Ferdinand Prantl <prantl@users.sourceforge.net> // Copyright 2001-2004 The Apache Software Foundation // 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. // // See http://ant-eclipse.sourceforge.net for the most recent version // and more information. package prantl.ant.eclipse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.Vector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; /** * Provides the functionality generating the file <tt>.classpath</tt> for the supplied * task object. It is expected to be used within the class EclipseTask. * * @see EclipseTask * @since Ant-Eclipse 1.0 * @author Ferdinand Prantl &lt;prantl@users.sourceforge.net&gt; */ final class ClassPathGenerator { /** * Contains a ready-to write information about a binary classpath entry - element * kinds "lib" or "var". Fields of this class match attributes of the element * <tt>classpath</tt>. * * @see ClassPathGenerator#writeProcessedBinaryClassPathEntries(XmlWriter, String, * Vector) * @since Ant-Eclipse 1.0 * @author Ferdinand Prantl &lt;prantl@users.sourceforge.net&gt; */ static class ProcessedBinaryClassPathEntry { String kind; String path; boolean exported; String sourcepath; String javadoc_location; } private EclipseTask task; /** * Creates a new instance of the generating object. * * @param parent * The parent task. * @since Ant-Eclipse 1.0 */ ClassPathGenerator(EclipseTask parent) { task = parent; } /** * Generates the file <tt>.classpath</tt> using the supplied output object. * * @since Ant-Eclipse 1.0 */ void generate() { ClassPathElement classPath = task.getEclipse().getClassPath(); if (classPath == null) { task.log("There was no description of a classpath found.", Project.MSG_WARN); return; } EclipseOutput output = task.getOutput(); if (output.isClassPathUpToDate()) { task.log("The classpath definition is up-to-date.", Project.MSG_WARN); return; } task.log("Writing the classpath definition."); XmlWriter writer = null; try { writer = new XmlWriter(new OutputStreamWriter(new BufferedOutputStream(output .createClassPath()), "UTF-8")); writer.writeXmlDeclaration("UTF-8"); writer.openElement("classpath"); checkClassPathEntries(classPath); generateContainerClassPathEntry(writer); generateSourceClassPathEntries(writer); Vector entries = new Vector(); processVariableClassPathEntries(entries, classPath.getVariables()); processLibraryClassPathEntries(entries, classPath.getLibraries()); writeProcessedBinaryClassPathEntries(writer, entries); generateOutputClassPathEntry(writer); writer.closeElement("classpath"); } catch (UnsupportedEncodingException exception) { throw new BuildException("Encoder to UTF-8 is not supported.", exception); } catch (IOException exception) { throw new BuildException("Writing the classpath definition failed.", exception); } finally { if (writer != null) try { writer.close(); } catch (IOException exception1) { throw new BuildException("Closing the classpath definition failed.", exception1); } } } private void generateContainerClassPathEntry(XmlWriter writer) throws IOException { ClassPathEntryContainerElement container = task.getEclipse().getClassPath() .getContainer(); if (container == null) { task.log("No container found, a default one added.", Project.MSG_VERBOSE); container = new ClassPathEntryContainerElement(); } container.validate(); String path = container.getPath(); if (path.indexOf('/') < 0 && !path.startsWith("org.eclipse.jdt.launching.JRE_CONTAINER")) { task.log("Prepending the container class name to the container path \"" + path + "\".", Project.MSG_VERBOSE); path = "org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/" + path; } task.log("Adding container \"" + path + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, "con", path); writer.closeDegeneratedElement(); } private void generateSourceClassPathEntries(XmlWriter writer) throws IOException { Vector entries = task.getEclipse().getClassPath().getSources(); if (entries.size() == 0) { task .log("No source found, the current directory added.", Project.MSG_VERBOSE); entries.addElement(new ClassPathEntrySourceElement()); } for (int i = 0, size = entries.size(); i != size; ++i) { ClassPathEntrySourceElement entry = (ClassPathEntrySourceElement) entries .get(i); entry.validate(); String excluding = entry.getExcluding(); String output = entry.getOutput(); Path path = new Path(task.getProject()); Reference reference = entry.getPathRef(); String[] items = path.list(); if (reference != null) { path.setRefid(reference); items = path.list(); } else { String value = entry.getPath(); if (value.length() == 0) task.log("Using the current directory as a default source path.", Project.MSG_VERBOSE); items = new String[] { value }; } String baseDirectory = task.getProject().getBaseDir().getAbsolutePath(); for (int j = 0; j != items.length; ++j) { String item = cutBaseDirectory(items[j], baseDirectory); task.log("Adding sources from \"" + item + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, "src", item); if (excluding != null) writer.appendAttribute("excluding", excluding); if (output != null) writer.appendAttribute("output", output); writer.closeDegeneratedElement(); } } } private void processVariableClassPathEntries(Vector entries, Vector paths) { processBinaryClassPathEntries(entries, "var", paths); } private void processLibraryClassPathEntries(Vector entries, Vector paths) { processBinaryClassPathEntries(entries, "lib", paths); } private void processBinaryClassPathEntries(Vector entries, String kind, Vector binaries) { for (int i = 0, size = binaries.size(); i != size; ++i) { ClassPathEntryBinaryElement entry = (ClassPathEntryBinaryElement) binaries .get(i); entry.validate(); Path path = new Path(task.getProject()); Reference reference = entry.getPathRef(); if (reference != null) path.setRefid(reference); else { String value = entry.getPath(); path.setPath(value); } processBinaryClassPathEntries(entries, kind, entry.getExported(), entry .getSource(), entry.getJavadoc(), path.list()); } } private void processBinaryClassPathEntries(Vector entries, String kind, boolean exported, String source, String javadoc_location, String[] items) { String baseDirectory = task.getProject().getBaseDir().getAbsolutePath(); for (int j = 0; j != items.length; ++j) { String item = cutBaseDirectory(items[j], baseDirectory); ProcessedBinaryClassPathEntry element = getProcessedBinaryClassPathEntry( entries, item); if (element == null) { task.log("Processing binary dependency \"" + item + "\" of the kind \"" + kind + "\".", Project.MSG_VERBOSE); element = new ProcessedBinaryClassPathEntry(); element.kind = kind; element.path = item; element.exported = exported; element.sourcepath = source; element.javadoc_location = javadoc_location; entries.addElement(element); } else { task.log("Updating binary dependency \"" + item + "\" of the kind \"" + kind + "\".", Project.MSG_VERBOSE); element.kind = kind; element.path = item; element.exported = exported; element.sourcepath = source; element.javadoc_location = javadoc_location; } } } private void writeProcessedBinaryClassPathEntries(XmlWriter writer, Vector entries) throws IOException { for (int i = 0, size = entries.size(); i != size; ++i) { ProcessedBinaryClassPathEntry element = (ProcessedBinaryClassPathEntry) entries .get(i); task.log("Adding binary dependency \"" + element.path + "\" of the kind \"" + element.kind + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, element.kind, element.path); if (element.exported) writer.appendAttribute("exported", "true"); if (element.sourcepath != null) writer.appendAttribute("sourcepath", element.sourcepath); if (element.javadoc_location != null) { writer.closeOpeningTag(); writer.openElement("attributes"); writer.openOpeningTag("attribute"); writer.appendAttribute("value", element.javadoc_location); writer.appendAttribute("name", "javadoc_location"); writer.closeDegeneratedElement(); writer.closeElement("attributes"); writer.closeElement("classpathentry"); } else writer.closeDegeneratedElement(); } } private void generateOutputClassPathEntry(XmlWriter writer) throws IOException { ClassPathEntryOutputElement output = task.getEclipse().getClassPath().getOutput(); if (output == null) { task .log("No output found, the current directory added.", Project.MSG_VERBOSE); output = new ClassPathEntryOutputElement(); } output.validate(); String path = cutBaseDirectory(output.getPath(), task.getProject().getBaseDir() .getAbsolutePath()); task.log("Adding output into \"" + path + "\".", Project.MSG_VERBOSE); openClassPathEntry(writer, "output", path); writer.closeDegeneratedElement(); } private void openClassPathEntry(XmlWriter writer, String kind, String path) throws IOException { writer.openOpeningTag("classpathentry"); writer.appendAttribute("kind", kind); writer.appendAttribute("path", path); } private String cutBaseDirectory(String path, String base) { if (!path.startsWith(base)) return path; task.log("Cutting base directory \"" + base + "\" from the path \"" + path + "\".", Project.MSG_VERBOSE); return path.substring(base.length() + 1); } private void checkClassPathEntries(ClassPathElement classPath) { if (task.getEclipse().getMode().getIndex() == EclipseElement.Mode.ASPECTJ && getClassPathEntry(classPath.getVariables(), "ASPECTJRT_LIB") == null) { ClassPathEntryVariableElement variable = classPath.createVariable(); variable.setPath("ASPECTJRT_LIB"); variable.setSource("ASPECTJRT_SRC"); } } private static ClassPathEntryElement getClassPathEntry(Vector entries, String path) { for (int i = 0, size = entries.size(); i != size; ++i) { ClassPathEntryElement entry = (ClassPathEntryElement) entries.get(i); if (path.equals(entry.getPath())) return entry; } return null; } private static ProcessedBinaryClassPathEntry getProcessedBinaryClassPathEntry( Vector entries, String path) { for (int i = 0, size = entries.size(); i < size; ++i) { ProcessedBinaryClassPathEntry entry = (ProcessedBinaryClassPathEntry) entries .get(i); if (entry.path.equals(path)) return entry; } return null; } }
apache-2.0
visallo/visallo
web/client-api/src/main/java/org/visallo/web/clientapi/model/DirectoryEntity.java
2694
package org.visallo.web.clientapi.model; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.visallo.web.clientapi.VisalloClientApiException; import java.util.Map; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = DirectoryGroup.class, name = DirectoryEntity.TYPE_GROUP), @JsonSubTypes.Type(value = DirectoryPerson.class, name = DirectoryEntity.TYPE_PERSON) }) public abstract class DirectoryEntity implements ClientApiObject, Comparable<DirectoryEntity> { public static final String TYPE_GROUP = "group"; public static final String TYPE_PERSON = "person"; private final String id; private final String displayName; public DirectoryEntity(String id, String displayName) { this.id = id; this.displayName = displayName; } public String getId() { return id; } public String getDisplayName() { return displayName; } public abstract String getType(); public static DirectoryEntity fromMap(Map map) { String type = (String) map.get("type"); String id = (String) map.get("id"); String displayName = (String) map.get("displayName"); if (TYPE_GROUP.equalsIgnoreCase(type)) { return new DirectoryGroup(id, displayName); } else if (TYPE_PERSON.equalsIgnoreCase(type)) { return new DirectoryPerson(id, displayName); } else { throw new VisalloClientApiException("Unhandled type: " + type); } } public static boolean isEntity(Map map) { String id = (String) map.get("id"); String displayName = (String) map.get("displayName"); String type = (String) map.get("type"); return type != null && id != null && displayName != null && isType(type); } private static boolean isType(String type) { return type.equalsIgnoreCase(TYPE_GROUP) || type.equalsIgnoreCase(TYPE_PERSON); } @Override public int compareTo(DirectoryEntity o) { int i = getType().compareTo(o.getType()); if (i != 0) { return i; } return getId().compareTo(o.getId()); } @Override public boolean equals(Object o) { if (!(o instanceof DirectoryEntity)) { return false; } DirectoryEntity other = (DirectoryEntity)o; return id.equals(other.id) && displayName.equals(other.displayName); } @Override public int hashCode() { return id.hashCode() + 31 * displayName.hashCode(); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-ssmincidents/src/main/java/com/amazonaws/services/ssmincidents/model/transform/UpdateIncidentRecordRequestMarshaller.java
4460
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ssmincidents.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.ssmincidents.model.*; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateIncidentRecordRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateIncidentRecordRequestMarshaller { private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("arn").build(); private static final MarshallingInfo<StructuredPojo> CHATCHANNEL_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("chatChannel").build(); private static final MarshallingInfo<String> CLIENTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("clientToken") .defaultValueSupplier(com.amazonaws.util.IdempotentUtils.getGenerator()).build(); private static final MarshallingInfo<Integer> IMPACT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("impact").build(); private static final MarshallingInfo<List> NOTIFICATIONTARGETS_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("notificationTargets").build(); private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("status").build(); private static final MarshallingInfo<String> SUMMARY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("summary").build(); private static final MarshallingInfo<String> TITLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("title").build(); private static final UpdateIncidentRecordRequestMarshaller instance = new UpdateIncidentRecordRequestMarshaller(); public static UpdateIncidentRecordRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpdateIncidentRecordRequest updateIncidentRecordRequest, ProtocolMarshaller protocolMarshaller) { if (updateIncidentRecordRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateIncidentRecordRequest.getArn(), ARN_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getChatChannel(), CHATCHANNEL_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getClientToken(), CLIENTTOKEN_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getImpact(), IMPACT_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getNotificationTargets(), NOTIFICATIONTARGETS_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getSummary(), SUMMARY_BINDING); protocolMarshaller.marshall(updateIncidentRecordRequest.getTitle(), TITLE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
google/schemaorg-java
src/main/java/com/google/schemaorg/core/MotorcycleDealer.java
23054
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.schemaorg.core; import com.google.schemaorg.JsonLdContext; import com.google.schemaorg.SchemaOrgType; import com.google.schemaorg.core.datatype.Date; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.PopularityScoreSpecification; import javax.annotation.Nullable; /** * Interface of <a * href="http://schema.org/MotorcycleDealer}">http://schema.org/MotorcycleDealer}</a>. */ public interface MotorcycleDealer extends AutomotiveBusiness { /** * Builder interface of <a * href="http://schema.org/MotorcycleDealer}">http://schema.org/MotorcycleDealer}</a>. */ public interface Builder extends AutomotiveBusiness.Builder { @Override Builder addJsonLdContext(@Nullable JsonLdContext context); @Override Builder addJsonLdContext(@Nullable JsonLdContext.Builder context); @Override Builder setJsonLdId(@Nullable String value); @Override Builder setJsonLdReverse(String property, Thing obj); @Override Builder setJsonLdReverse(String property, Thing.Builder builder); /** Add a value to property additionalProperty. */ Builder addAdditionalProperty(PropertyValue value); /** Add a value to property additionalProperty. */ Builder addAdditionalProperty(PropertyValue.Builder value); /** Add a value to property additionalProperty. */ Builder addAdditionalProperty(String value); /** Add a value to property additionalType. */ Builder addAdditionalType(URL value); /** Add a value to property additionalType. */ Builder addAdditionalType(String value); /** Add a value to property address. */ Builder addAddress(PostalAddress value); /** Add a value to property address. */ Builder addAddress(PostalAddress.Builder value); /** Add a value to property address. */ Builder addAddress(Text value); /** Add a value to property address. */ Builder addAddress(String value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(AggregateRating value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(AggregateRating.Builder value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(String value); /** Add a value to property alternateName. */ Builder addAlternateName(Text value); /** Add a value to property alternateName. */ Builder addAlternateName(String value); /** Add a value to property alumni. */ Builder addAlumni(Person value); /** Add a value to property alumni. */ Builder addAlumni(Person.Builder value); /** Add a value to property alumni. */ Builder addAlumni(String value); /** Add a value to property areaServed. */ Builder addAreaServed(AdministrativeArea value); /** Add a value to property areaServed. */ Builder addAreaServed(AdministrativeArea.Builder value); /** Add a value to property areaServed. */ Builder addAreaServed(GeoShape value); /** Add a value to property areaServed. */ Builder addAreaServed(GeoShape.Builder value); /** Add a value to property areaServed. */ Builder addAreaServed(Place value); /** Add a value to property areaServed. */ Builder addAreaServed(Place.Builder value); /** Add a value to property areaServed. */ Builder addAreaServed(Text value); /** Add a value to property areaServed. */ Builder addAreaServed(String value); /** Add a value to property award. */ Builder addAward(Text value); /** Add a value to property award. */ Builder addAward(String value); /** Add a value to property awards. */ Builder addAwards(Text value); /** Add a value to property awards. */ Builder addAwards(String value); /** Add a value to property branchCode. */ Builder addBranchCode(Text value); /** Add a value to property branchCode. */ Builder addBranchCode(String value); /** Add a value to property branchOf. */ Builder addBranchOf(Organization value); /** Add a value to property branchOf. */ Builder addBranchOf(Organization.Builder value); /** Add a value to property branchOf. */ Builder addBranchOf(String value); /** Add a value to property brand. */ Builder addBrand(Brand value); /** Add a value to property brand. */ Builder addBrand(Brand.Builder value); /** Add a value to property brand. */ Builder addBrand(Organization value); /** Add a value to property brand. */ Builder addBrand(Organization.Builder value); /** Add a value to property brand. */ Builder addBrand(String value); /** Add a value to property contactPoint. */ Builder addContactPoint(ContactPoint value); /** Add a value to property contactPoint. */ Builder addContactPoint(ContactPoint.Builder value); /** Add a value to property contactPoint. */ Builder addContactPoint(String value); /** Add a value to property contactPoints. */ Builder addContactPoints(ContactPoint value); /** Add a value to property contactPoints. */ Builder addContactPoints(ContactPoint.Builder value); /** Add a value to property contactPoints. */ Builder addContactPoints(String value); /** Add a value to property containedIn. */ Builder addContainedIn(Place value); /** Add a value to property containedIn. */ Builder addContainedIn(Place.Builder value); /** Add a value to property containedIn. */ Builder addContainedIn(String value); /** Add a value to property containedInPlace. */ Builder addContainedInPlace(Place value); /** Add a value to property containedInPlace. */ Builder addContainedInPlace(Place.Builder value); /** Add a value to property containedInPlace. */ Builder addContainedInPlace(String value); /** Add a value to property containsPlace. */ Builder addContainsPlace(Place value); /** Add a value to property containsPlace. */ Builder addContainsPlace(Place.Builder value); /** Add a value to property containsPlace. */ Builder addContainsPlace(String value); /** Add a value to property currenciesAccepted. */ Builder addCurrenciesAccepted(Text value); /** Add a value to property currenciesAccepted. */ Builder addCurrenciesAccepted(String value); /** Add a value to property department. */ Builder addDepartment(Organization value); /** Add a value to property department. */ Builder addDepartment(Organization.Builder value); /** Add a value to property department. */ Builder addDepartment(String value); /** Add a value to property description. */ Builder addDescription(Text value); /** Add a value to property description. */ Builder addDescription(String value); /** Add a value to property dissolutionDate. */ Builder addDissolutionDate(Date value); /** Add a value to property dissolutionDate. */ Builder addDissolutionDate(String value); /** Add a value to property duns. */ Builder addDuns(Text value); /** Add a value to property duns. */ Builder addDuns(String value); /** Add a value to property email. */ Builder addEmail(Text value); /** Add a value to property email. */ Builder addEmail(String value); /** Add a value to property employee. */ Builder addEmployee(Person value); /** Add a value to property employee. */ Builder addEmployee(Person.Builder value); /** Add a value to property employee. */ Builder addEmployee(String value); /** Add a value to property employees. */ Builder addEmployees(Person value); /** Add a value to property employees. */ Builder addEmployees(Person.Builder value); /** Add a value to property employees. */ Builder addEmployees(String value); /** Add a value to property event. */ Builder addEvent(Event value); /** Add a value to property event. */ Builder addEvent(Event.Builder value); /** Add a value to property event. */ Builder addEvent(String value); /** Add a value to property events. */ Builder addEvents(Event value); /** Add a value to property events. */ Builder addEvents(Event.Builder value); /** Add a value to property events. */ Builder addEvents(String value); /** Add a value to property faxNumber. */ Builder addFaxNumber(Text value); /** Add a value to property faxNumber. */ Builder addFaxNumber(String value); /** Add a value to property founder. */ Builder addFounder(Person value); /** Add a value to property founder. */ Builder addFounder(Person.Builder value); /** Add a value to property founder. */ Builder addFounder(String value); /** Add a value to property founders. */ Builder addFounders(Person value); /** Add a value to property founders. */ Builder addFounders(Person.Builder value); /** Add a value to property founders. */ Builder addFounders(String value); /** Add a value to property foundingDate. */ Builder addFoundingDate(Date value); /** Add a value to property foundingDate. */ Builder addFoundingDate(String value); /** Add a value to property foundingLocation. */ Builder addFoundingLocation(Place value); /** Add a value to property foundingLocation. */ Builder addFoundingLocation(Place.Builder value); /** Add a value to property foundingLocation. */ Builder addFoundingLocation(String value); /** Add a value to property geo. */ Builder addGeo(GeoCoordinates value); /** Add a value to property geo. */ Builder addGeo(GeoCoordinates.Builder value); /** Add a value to property geo. */ Builder addGeo(GeoShape value); /** Add a value to property geo. */ Builder addGeo(GeoShape.Builder value); /** Add a value to property geo. */ Builder addGeo(String value); /** Add a value to property globalLocationNumber. */ Builder addGlobalLocationNumber(Text value); /** Add a value to property globalLocationNumber. */ Builder addGlobalLocationNumber(String value); /** Add a value to property hasMap. */ Builder addHasMap(Map value); /** Add a value to property hasMap. */ Builder addHasMap(Map.Builder value); /** Add a value to property hasMap. */ Builder addHasMap(URL value); /** Add a value to property hasMap. */ Builder addHasMap(String value); /** Add a value to property hasOfferCatalog. */ Builder addHasOfferCatalog(OfferCatalog value); /** Add a value to property hasOfferCatalog. */ Builder addHasOfferCatalog(OfferCatalog.Builder value); /** Add a value to property hasOfferCatalog. */ Builder addHasOfferCatalog(String value); /** Add a value to property hasPOS. */ Builder addHasPOS(Place value); /** Add a value to property hasPOS. */ Builder addHasPOS(Place.Builder value); /** Add a value to property hasPOS. */ Builder addHasPOS(String value); /** Add a value to property image. */ Builder addImage(ImageObject value); /** Add a value to property image. */ Builder addImage(ImageObject.Builder value); /** Add a value to property image. */ Builder addImage(URL value); /** Add a value to property image. */ Builder addImage(String value); /** Add a value to property isicV4. */ Builder addIsicV4(Text value); /** Add a value to property isicV4. */ Builder addIsicV4(String value); /** Add a value to property legalName. */ Builder addLegalName(Text value); /** Add a value to property legalName. */ Builder addLegalName(String value); /** Add a value to property location. */ Builder addLocation(Place value); /** Add a value to property location. */ Builder addLocation(Place.Builder value); /** Add a value to property location. */ Builder addLocation(PostalAddress value); /** Add a value to property location. */ Builder addLocation(PostalAddress.Builder value); /** Add a value to property location. */ Builder addLocation(Text value); /** Add a value to property location. */ Builder addLocation(String value); /** Add a value to property logo. */ Builder addLogo(ImageObject value); /** Add a value to property logo. */ Builder addLogo(ImageObject.Builder value); /** Add a value to property logo. */ Builder addLogo(URL value); /** Add a value to property logo. */ Builder addLogo(String value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork.Builder value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(URL value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(String value); /** Add a value to property makesOffer. */ Builder addMakesOffer(Offer value); /** Add a value to property makesOffer. */ Builder addMakesOffer(Offer.Builder value); /** Add a value to property makesOffer. */ Builder addMakesOffer(String value); /** Add a value to property map. */ Builder addMap(URL value); /** Add a value to property map. */ Builder addMap(String value); /** Add a value to property maps. */ Builder addMaps(URL value); /** Add a value to property maps. */ Builder addMaps(String value); /** Add a value to property member. */ Builder addMember(Organization value); /** Add a value to property member. */ Builder addMember(Organization.Builder value); /** Add a value to property member. */ Builder addMember(Person value); /** Add a value to property member. */ Builder addMember(Person.Builder value); /** Add a value to property member. */ Builder addMember(String value); /** Add a value to property memberOf. */ Builder addMemberOf(Organization value); /** Add a value to property memberOf. */ Builder addMemberOf(Organization.Builder value); /** Add a value to property memberOf. */ Builder addMemberOf(ProgramMembership value); /** Add a value to property memberOf. */ Builder addMemberOf(ProgramMembership.Builder value); /** Add a value to property memberOf. */ Builder addMemberOf(String value); /** Add a value to property members. */ Builder addMembers(Organization value); /** Add a value to property members. */ Builder addMembers(Organization.Builder value); /** Add a value to property members. */ Builder addMembers(Person value); /** Add a value to property members. */ Builder addMembers(Person.Builder value); /** Add a value to property members. */ Builder addMembers(String value); /** Add a value to property naics. */ Builder addNaics(Text value); /** Add a value to property naics. */ Builder addNaics(String value); /** Add a value to property name. */ Builder addName(Text value); /** Add a value to property name. */ Builder addName(String value); /** Add a value to property numberOfEmployees. */ Builder addNumberOfEmployees(QuantitativeValue value); /** Add a value to property numberOfEmployees. */ Builder addNumberOfEmployees(QuantitativeValue.Builder value); /** Add a value to property numberOfEmployees. */ Builder addNumberOfEmployees(String value); /** Add a value to property openingHours. */ Builder addOpeningHours(Text value); /** Add a value to property openingHours. */ Builder addOpeningHours(String value); /** Add a value to property openingHoursSpecification. */ Builder addOpeningHoursSpecification(OpeningHoursSpecification value); /** Add a value to property openingHoursSpecification. */ Builder addOpeningHoursSpecification(OpeningHoursSpecification.Builder value); /** Add a value to property openingHoursSpecification. */ Builder addOpeningHoursSpecification(String value); /** Add a value to property owns. */ Builder addOwns(OwnershipInfo value); /** Add a value to property owns. */ Builder addOwns(OwnershipInfo.Builder value); /** Add a value to property owns. */ Builder addOwns(Product value); /** Add a value to property owns. */ Builder addOwns(Product.Builder value); /** Add a value to property owns. */ Builder addOwns(String value); /** Add a value to property parentOrganization. */ Builder addParentOrganization(Organization value); /** Add a value to property parentOrganization. */ Builder addParentOrganization(Organization.Builder value); /** Add a value to property parentOrganization. */ Builder addParentOrganization(String value); /** Add a value to property paymentAccepted. */ Builder addPaymentAccepted(Text value); /** Add a value to property paymentAccepted. */ Builder addPaymentAccepted(String value); /** Add a value to property photo. */ Builder addPhoto(ImageObject value); /** Add a value to property photo. */ Builder addPhoto(ImageObject.Builder value); /** Add a value to property photo. */ Builder addPhoto(Photograph value); /** Add a value to property photo. */ Builder addPhoto(Photograph.Builder value); /** Add a value to property photo. */ Builder addPhoto(String value); /** Add a value to property photos. */ Builder addPhotos(ImageObject value); /** Add a value to property photos. */ Builder addPhotos(ImageObject.Builder value); /** Add a value to property photos. */ Builder addPhotos(Photograph value); /** Add a value to property photos. */ Builder addPhotos(Photograph.Builder value); /** Add a value to property photos. */ Builder addPhotos(String value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action.Builder value); /** Add a value to property potentialAction. */ Builder addPotentialAction(String value); /** Add a value to property priceRange. */ Builder addPriceRange(Text value); /** Add a value to property priceRange. */ Builder addPriceRange(String value); /** Add a value to property review. */ Builder addReview(Review value); /** Add a value to property review. */ Builder addReview(Review.Builder value); /** Add a value to property review. */ Builder addReview(String value); /** Add a value to property reviews. */ Builder addReviews(Review value); /** Add a value to property reviews. */ Builder addReviews(Review.Builder value); /** Add a value to property reviews. */ Builder addReviews(String value); /** Add a value to property sameAs. */ Builder addSameAs(URL value); /** Add a value to property sameAs. */ Builder addSameAs(String value); /** Add a value to property seeks. */ Builder addSeeks(Demand value); /** Add a value to property seeks. */ Builder addSeeks(Demand.Builder value); /** Add a value to property seeks. */ Builder addSeeks(String value); /** Add a value to property serviceArea. */ Builder addServiceArea(AdministrativeArea value); /** Add a value to property serviceArea. */ Builder addServiceArea(AdministrativeArea.Builder value); /** Add a value to property serviceArea. */ Builder addServiceArea(GeoShape value); /** Add a value to property serviceArea. */ Builder addServiceArea(GeoShape.Builder value); /** Add a value to property serviceArea. */ Builder addServiceArea(Place value); /** Add a value to property serviceArea. */ Builder addServiceArea(Place.Builder value); /** Add a value to property serviceArea. */ Builder addServiceArea(String value); /** Add a value to property subOrganization. */ Builder addSubOrganization(Organization value); /** Add a value to property subOrganization. */ Builder addSubOrganization(Organization.Builder value); /** Add a value to property subOrganization. */ Builder addSubOrganization(String value); /** Add a value to property taxID. */ Builder addTaxID(Text value); /** Add a value to property taxID. */ Builder addTaxID(String value); /** Add a value to property telephone. */ Builder addTelephone(Text value); /** Add a value to property telephone. */ Builder addTelephone(String value); /** Add a value to property url. */ Builder addUrl(URL value); /** Add a value to property url. */ Builder addUrl(String value); /** Add a value to property vatID. */ Builder addVatID(Text value); /** Add a value to property vatID. */ Builder addVatID(String value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article.Builder value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(String value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification.Builder value); /** Add a value to property popularityScore. */ Builder addPopularityScore(String value); /** * Add a value to property. * * @param name The property name. * @param value The value of the property. */ Builder addProperty(String name, SchemaOrgType value); /** * Add a value to property. * * @param name The property name. * @param builder The schema.org object builder for the property value. */ Builder addProperty(String name, Thing.Builder builder); /** * Add a value to property. * * @param name The property name. * @param value The string value of the property. */ Builder addProperty(String name, String value); /** Build a {@link MotorcycleDealer} object. */ MotorcycleDealer build(); } }
apache-2.0
x-meta/xworker
xworker_swt/src/main/java/xworker/swt/reacts/DataReactorCreator.java
397
package xworker.swt.reacts; import org.xmeta.ActionContext; /** * 创建DataReactor的接口。 * * @author zyx * */ public interface DataReactorCreator { /** * 创建DataReactor。 * * @param control * @param action 动作 * @param actionContext * @return */ public DataReactor create(Object control, String action, ActionContext actionContext); }
apache-2.0
WANdisco/gerrit
java/com/google/gerrit/server/restapi/change/Rebuild.java
4432
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.restapi.change; import static java.util.stream.Collectors.joining; import com.google.gerrit.extensions.common.Input; import com.google.gerrit.extensions.restapi.BinaryResult; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.reviewdb.server.ReviewDbUtil; import com.google.gerrit.server.CommentsUtil; import com.google.gerrit.server.change.ChangeResource; import com.google.gerrit.server.notedb.ChangeBundle; import com.google.gerrit.server.notedb.ChangeBundleReader; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.notedb.NotesMigration; import com.google.gerrit.server.notedb.rebuild.ChangeRebuilder; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import java.io.IOException; import java.util.List; import org.eclipse.jgit.errors.ConfigInvalidException; @Singleton public class Rebuild implements RestModifyView<ChangeResource, Input> { private final Provider<ReviewDb> db; private final NotesMigration migration; private final ChangeRebuilder rebuilder; private final ChangeBundleReader bundleReader; private final CommentsUtil commentsUtil; private final ChangeNotes.Factory notesFactory; @Inject Rebuild( Provider<ReviewDb> db, NotesMigration migration, ChangeRebuilder rebuilder, ChangeBundleReader bundleReader, CommentsUtil commentsUtil, ChangeNotes.Factory notesFactory) { this.db = db; this.migration = migration; this.rebuilder = rebuilder; this.bundleReader = bundleReader; this.commentsUtil = commentsUtil; this.notesFactory = notesFactory; } @Override public BinaryResult apply(ChangeResource rsrc, Input input) throws ResourceNotFoundException, IOException, OrmException, ConfigInvalidException, ResourceConflictException { if (!migration.commitChangeWrites()) { throw new ResourceNotFoundException(); } if (!migration.readChanges()) { // ChangeBundle#fromNotes currently doesn't work if reading isn't enabled, // so don't attempt a diff. rebuild(rsrc); return BinaryResult.create("Rebuilt change successfully"); } // Not the same transaction as the rebuild, so may result in spurious diffs // in the case of races. This should be easy enough to detect by rerunning. ChangeBundle reviewDbBundle = bundleReader.fromReviewDb(ReviewDbUtil.unwrapDb(db.get()), rsrc.getId()); if (reviewDbBundle == null) { throw new ResourceConflictException("change is missing in ReviewDb"); } rebuild(rsrc); ChangeNotes notes = notesFactory.create(db.get(), rsrc.getChange().getProject(), rsrc.getId()); ChangeBundle noteDbBundle = ChangeBundle.fromNotes(commentsUtil, notes); List<String> diffs = reviewDbBundle.differencesFrom(noteDbBundle); if (diffs.isEmpty()) { return BinaryResult.create("No differences between ReviewDb and NoteDb"); } return BinaryResult.create( diffs.stream().collect(joining("\n", "Differences between ReviewDb and NoteDb:\n", "\n"))); } private void rebuild(ChangeResource rsrc) throws ResourceNotFoundException, OrmException, IOException { try { rebuilder.rebuild(db.get(), rsrc.getId()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(IdString.fromDecoded(rsrc.getId().toString()), e); } } }
apache-2.0
john-mcdonagh/android_app
PracticeApp/app/src/test/java/com/example/john/practiceapp/ExampleUnitTest.java
406
package com.example.john.practiceapp; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
oeg-upm/epnoi
harvester/src/test/java/org/epnoi/harvester/routes/oaipmh/OAIPMHTest.java
1916
package org.epnoi.harvester.routes.oaipmh; import es.cbadenes.lab.test.IntegrationTest; import org.epnoi.harvester.Config; import org.epnoi.model.modules.EventBus; import org.epnoi.storage.UDM; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by cbadenes on 04/01/16. */ @Category(IntegrationTest.class) @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Config.class) @TestPropertySource(properties = { "epnoi.eventbus.uri = localhost", "epnoi.hoarder.storage.path = ../hoarder/target/storage", "epnoi.harvester.folder.input = target/workspace", "epnoi.upf.miner.config = src/test/resources/DRIconfig.properties" }) public class OAIPMHTest { private static final Logger LOG = LoggerFactory.getLogger(OAIPMHTest.class); @Autowired EventBus eventBus; @Autowired UDM udm; @Test public void readFolder() throws Exception { // Source source = new Source(); // source.setUri("http://epnoi.org/sources/7aa484ca-d968-43b2-b336-2a5af501d1e1"); // source.setName("oaipmh-bournemouth"); // source.setUrl("oaipmh://eprints.bournemouth.ac.uk/cgi/oai2?from=2015-01-01T00:00:00Z"); // // udm.saveSource(ResourceUtils.map(source, org.epnoi.storage.model.Source.class)); // // LOG.info("trying to send a 'source.created' event: " + source); // this.eventBus.post(Event.from(source), RoutingKey.of(Resource.Type.SOURCE, Resource.State.CREATED)); LOG.info("event sent. Now going to sleep..."); Thread.sleep(600000); } }
apache-2.0
sohutv/cachecloud
cachecloud-client/cachecloud-jedis/src/main/java/redis/clients/jedis/valueobject/RangeRankVO.java
446
package redis.clients.jedis.valueobject; /** * * @author leifu * @Date 2017年2月14日 * @Time 下午4:58:52 */ public class RangeRankVO { private final long min; private final long max; public RangeRankVO(long min, long max) { this.min = min; this.max = max; } public long getMin() { return min; } public long getMax() { return max; } }
apache-2.0
android-art-intel/marshmallow
art-extension/opttests/src/OptimizationTests/NonTemporalMove/MultipleArraysStoresLong_004/Main.java
1581
/* * Copyright (C) 2015 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 OptimizationTests.NonTemporalMove.MultipleArraysStoresLong_004; // No non temporal move expected, breaking only one array limitation public class Main { final int iterations = 0x40000; public long checkSum(long[] tab, int n) { long s = 0; for (int i = 0; i < n ; i++) { s = s + tab[i]; } return s; } public long testLoop(long[] tab1, long[] tab2) { for (int i = 0; i < iterations; i++) { tab1[i] = i; tab2[i] = i; } return checkSum(tab1, iterations) - checkSum(tab2, iterations); } public void test() { long[] tab1 = new long [iterations]; System.out.println(testLoop(tab1, tab1)); } public static void main(String[] args) { new Main().test(); } }
apache-2.0
blademainer/common_utils
common_helper/src/main/java/com/xiongyingqi/util/xml/SimpleNamespaceContext.java
5171
/* * Copyright 2002-2012 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 com.xiongyingqi.util.xml; import com.xiongyingqi.util.Assert; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import java.util.*; /** * Simple {@code javax.xml.namespace.NamespaceContext} implementation. Follows the standard * {@code NamespaceContext} contract, and is loadable via a {@code java.util.Map} or * {@code java.util.Properties} object * * @author Arjen Poutsma * @since 3.0 */ public class SimpleNamespaceContext implements NamespaceContext { private Map<String, String> prefixToNamespaceUri = new HashMap<String, String>(); private Map<String, List<String>> namespaceUriToPrefixes = new HashMap<String, List<String>>(); private String defaultNamespaceUri = ""; @Override public String getNamespaceURI(String prefix) { Assert.notNull(prefix, "prefix is null"); if (XMLConstants.XML_NS_PREFIX.equals(prefix)) { return XMLConstants.XML_NS_URI; } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) { return XMLConstants.XMLNS_ATTRIBUTE_NS_URI; } else if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { return defaultNamespaceUri; } else if (prefixToNamespaceUri.containsKey(prefix)) { return prefixToNamespaceUri.get(prefix); } return ""; } @Override public String getPrefix(String namespaceUri) { List<?> prefixes = getPrefixesInternal(namespaceUri); return prefixes.isEmpty() ? null : (String) prefixes.get(0); } @Override public Iterator<String> getPrefixes(String namespaceUri) { return getPrefixesInternal(namespaceUri).iterator(); } /** * Sets the bindings for this namespace context. The supplied map must consist of string key value pairs. * * @param bindings the bindings */ public void setBindings(Map<String, String> bindings) { for (Map.Entry<String, String> entry : bindings.entrySet()) { bindNamespaceUri(entry.getKey(), entry.getValue()); } } /** * Binds the given namespace as default namespace. * * @param namespaceUri the namespace uri */ public void bindDefaultNamespaceUri(String namespaceUri) { bindNamespaceUri(XMLConstants.DEFAULT_NS_PREFIX, namespaceUri); } /** * Binds the given prefix to the given namespace. * * @param prefix the namespace prefix * @param namespaceUri the namespace uri */ public void bindNamespaceUri(String prefix, String namespaceUri) { Assert.notNull(prefix, "No prefix given"); Assert.notNull(namespaceUri, "No namespaceUri given"); if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { defaultNamespaceUri = namespaceUri; } else { prefixToNamespaceUri.put(prefix, namespaceUri); getPrefixesInternal(namespaceUri).add(prefix); } } /** * Removes all declared prefixes. */ public void clear() { prefixToNamespaceUri.clear(); } /** * Returns all declared prefixes. * * @return the declared prefixes */ public Iterator<String> getBoundPrefixes() { return prefixToNamespaceUri.keySet().iterator(); } private List<String> getPrefixesInternal(String namespaceUri) { if (defaultNamespaceUri.equals(namespaceUri)) { return Collections.singletonList(XMLConstants.DEFAULT_NS_PREFIX); } else if (XMLConstants.XML_NS_URI.equals(namespaceUri)) { return Collections.singletonList(XMLConstants.XML_NS_PREFIX); } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) { return Collections.singletonList(XMLConstants.XMLNS_ATTRIBUTE); } else { List<String> list = namespaceUriToPrefixes.get(namespaceUri); if (list == null) { list = new ArrayList<String>(); namespaceUriToPrefixes.put(namespaceUri, list); } return list; } } /** * Removes the given prefix from this context. * * @param prefix the prefix to be removed */ public void removeBinding(String prefix) { if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { defaultNamespaceUri = ""; } else { String namespaceUri = prefixToNamespaceUri.remove(prefix); List<String> prefixes = getPrefixesInternal(namespaceUri); prefixes.remove(prefix); } } }
apache-2.0
jankronquist/AirportWeather
src/main/java/com/jayway/xml/CDataTransformer.java
857
/* * Copyright 2011 Jan Kronquist. * * 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.jayway.xml; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class CDataTransformer { public String transform(NodeList list) { Node node = list.item(0); if (node != null) { return node.getNodeValue(); } return null; } }
apache-2.0
WasiqB/coteafs-appium
src/main/java/com/github/wasiqb/coteafs/appium/config/device/android/AdbSetting.java
874
/* * * Copyright (c) 2020, Wasiq Bhamla. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.github.wasiqb.coteafs.appium.config.device.android; import lombok.Data; /** * @author Wasiq Bhamla * @since Mar 13, 2021 */ @Data public class AdbSetting { private String host; private int port; private long timeout; }
apache-2.0
weiwenqiang/GitHub
MVP/RxJava2ToMVP/T-MVP-master/apt/src/main/java/com/app/apt/processor/ApiFactoryProcessor.java
6331
package com.app.apt.processor; import com.app.annotation.apt.ApiFactory; import com.app.apt.AnnotationProcessor; import com.app.apt.inter.IProcessor; import com.app.apt.util.Utils; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.annotation.processing.FilerException; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import javax.tools.Diagnostic; import static com.squareup.javapoet.TypeSpec.classBuilder; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; /** * Created by baixiaokang on 16/12/28. */ public class ApiFactoryProcessor implements IProcessor { @Override public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) { String CLASS_NAME = "ApiFactory"; String DATA_ARR_CLASS = "DataArr"; TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ API工厂 此类由apt自动生成"); try { for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(ApiFactory.class))) { mAbstractProcessor.mMessager.printMessage(Diagnostic.Kind.NOTE, "正在处理: " + element.toString()); for (Element e : element.getEnclosedElements()) { ExecutableElement executableElement = (ExecutableElement) e; MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(e.getSimpleName().toString()) .addJavadoc("@此方法由apt自动生成") .addModifiers(PUBLIC, STATIC); if (TypeName.get(executableElement.getReturnType()).toString().contains(DATA_ARR_CLASS)) {//返回列表数据 methodBuilder.returns(ClassName.get("io.reactivex", "Flowable")); Map<String, Object> params = new HashMap<>(); methodBuilder.addParameter(params.getClass(), "param"); ClassName apiUtil = ClassName.get("com.base.util", "ApiUtil"); ClassName C = ClassName.get("com", "C"); CodeBlock.Builder blockBuilder = CodeBlock.builder(); int len = executableElement.getParameters().size(); for (int i = 0; i < len; i++) { VariableElement ep = executableElement.getParameters().get(i); boolean isLast = i == len - 1; String split = (isLast ? "" : ","); switch (ep.getSimpleName().toString()) { case "include": blockBuilder.add("$L.getInclude(param)" + split, apiUtil); break; case "where": blockBuilder.add("$L.getWhere(param)" + split, apiUtil); break; case "skip": blockBuilder.add("$L.getSkip(param)" + split, apiUtil); break; case "limit": blockBuilder.add("$L.PAGE_COUNT" + split, C); break; case "order": blockBuilder.add("$L._CREATED_AT" + split, C); break; } } methodBuilder.addStatement( "return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())" , ClassName.get("com.api", "Api") , e.getSimpleName().toString() , blockBuilder.build().toString() , ClassName.get("com.base.util.helper", "RxSchedulers")); tb.addMethod(methodBuilder.build()); } else {//返回普通数据 methodBuilder.returns(TypeName.get(executableElement.getReturnType())); String paramsString = ""; for (VariableElement ep : executableElement.getParameters()) { methodBuilder.addParameter(TypeName.get(ep.asType()), ep.getSimpleName().toString()); paramsString += ep.getSimpleName().toString() + ","; } methodBuilder.addStatement( "return $T.getInstance()" + ".service.$L($L)" + ".compose($T.io_main())" , ClassName.get("com.api", "Api") , e.getSimpleName().toString() , paramsString.substring(0, paramsString.length() - 1) , ClassName.get("com.base.util.helper", "RxSchedulers")); tb.addMethod(methodBuilder.build()); } } } JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();// 生成源代码 javaFile.writeTo(mAbstractProcessor.mFiler);// 在 app module/build/generated/source/apt 生成一份源代码 } catch (FilerException e) { } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
wjwin/coolweather
app/src/main/java/com/example/coolweather/util/Utility.java
3289
package com.example.coolweather.util; import android.text.TextUtils; import com.example.coolweather.db.City; import com.example.coolweather.db.County; import com.example.coolweather.db.Province; import com.example.coolweather.gson.Weather; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by Administrator on 2017/4/12. */ public class Utility { public static boolean handProvinceResponse(String response) { if (!TextUtils.isEmpty(response)) { try { JSONArray allProvinces = new JSONArray(response); for (int i= 0; i < allProvinces.length();i ++) { JSONObject provinceObject = allProvinces.getJSONObject(i); Province province = new Province(); province.setProvinceName(provinceObject.getString("name")); province.setProvinceCode(provinceObject.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } public static boolean handCityResponse(String response,int provinId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCities = new JSONArray(response); for (int i= 0; i < allCities.length();i ++) { JSONObject cityObject = allCities.getJSONObject(i); City city = new City(); city.setCityName(cityObject.getString("name")); city.setCityCode(cityObject.getInt("id")); city.setProvinceId(provinId); city.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } public static boolean handCountyResponse(String response,int cityId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCounties = new JSONArray(response); for (int i= 0; i < allCounties.length();i ++) { JSONObject countyObject = allCounties.getJSONObject(i); County county = new County(); county.setCountyName(countyObject.getString("name")); county.setWeatherId(countyObject.getString("weather_id")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } public static Weather handleWeatherResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather"); String weatherContent =jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent,Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; } }
apache-2.0
Kalinovcic/LD32
src/net/kalinovcic/ld32/Enemy.java
3462
package net.kalinovcic.ld32; import static org.lwjgl.opengl.GL11.*; public class Enemy extends Sprite { public GameStage game; public char origc; public String word; public float speed; public float vely; public boolean removeMe = false; public boolean alive = true; public int health; public Behavior behavior; public double cooldown; public boolean isPickup = false; public Enemy(GameStage game, String word, float speed, Behavior behavior) { this(game, word, behavior.getSize() / 2 + LD32.random.nextFloat() * (LD32.WW - behavior.getSize()), -behavior.getSize(), speed, behavior); } public Enemy(GameStage game, String word, float x, float y, float speed, Behavior behavior) { super(behavior.getTexture(), x, y, behavior.getSize(), behavior.getSize(), 180.0f); this.game = game; this.origc = word.charAt(0); this.word = word; health = word.length(); this.behavior = behavior; this.speed = vely = speed * behavior.getSpeedMul(); behavior.init(this); } public void update(double timeDelta) { if (vely < speed) { vely += timeDelta * speed * 4; if (vely > speed) vely = speed; } if (vely > speed) { vely -= timeDelta * speed; if (vely < speed) vely = speed; } y += vely * timeDelta; behavior.update(this, timeDelta); } @Override public void render() { super.render(); if (word.length() <= 0) return; glPushMatrix(); glTranslatef(x, y - h / 2, 0.0f); float w = LD32.font.getTotalWidth(word) + 8; float h = LD32.font.getHeight(); if (x - w / 2.0f < 0) glTranslatef(-(x - w / 2.0f), 0.0f, 0.0f); if (x + w / 2.0f > LD32.WW) glTranslatef(LD32.WW - (x + w / 2.0f), 0.0f, 0.0f); if (y - this.h / 2 - h < 0) glTranslatef(0.0f, -(y - this.h / 2 - h), 0.0f); /* glBindTexture(GL_TEXTURE_2D, 0); glColor4f(0.3f, 0.3f, 0.3f, 0.7f); glBegin(GL_QUADS); glVertex2f(-w / 2.0f, 0.0f); glVertex2f(w / 2.0f, 0.0f); glVertex2f(w / 2.0f, -h); glVertex2f(-w / 2.0f, -h); glEnd(); */ behavior.labelColor(); LD32.font.drawString(-4, 0.0f, word, 1.0f, -1.0f, TrueTypeFont.ALIGN_CENTER); glPopMatrix(); } public void renderSpecial() { super.render(); if (word.length() <= 0) return; glPushMatrix(); glTranslatef(x, y - h / 2, 0.0f); float w = LD32.font.getTotalWidth(word) + 8; float h = LD32.font.getHeight(); if (x - w / 2.0f < 0) glTranslatef(-(x - w / 2.0f), 0.0f, 0.0f); if (x + w / 2.0f > LD32.WW) glTranslatef(LD32.WW - (x + w / 2.0f), 0.0f, 0.0f); if (y - this.h / 2 - h < 0) glTranslatef(0.0f, -(y - this.h / 2 - h), 0.0f); /* glBindTexture(GL_TEXTURE_2D, 0); glBegin(GL_QUADS); glVertex2f(-w / 2.0f, 0.0f); glVertex2f(w / 2.0f, 0.0f); glVertex2f(w / 2.0f, -h); glVertex2f(-w / 2.0f, -h); glEnd(); */ glColor3f(0.4f, 0.4f, 1.0f); LD32.font.drawString(-4, 0.0f, word, 1, -1, TrueTypeFont.ALIGN_CENTER); glPopMatrix(); } }
apache-2.0
wigforss/Ka-Commons-Reflection
src/test/java/org/kasource/commons/reflection/collection/PackageMapTest.java
676
package org.kasource.commons.reflection.collection; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.adapters.XmlAdapter; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import org.junit.Test; public class PackageMapTest { @Test public void get() { Map<String, String> map = new HashMap<String, String>(); map.put("javax", "javax"); map.put("javax.xml", "xml"); map.put("javax.xml.bind", "bind"); PackageMap<String> packageMap = new PackageMap<String>(map); assertThat(packageMap.get(XmlAdapter.class), equalTo("bind")); } }
apache-2.0
aifraenkel/caltec-tools
SonarQube/Plugins/sonar-jira-master/src/test/java/org/sonar/plugins/jira/metrics/JiraWidgetTest.java
1382
/* * Sonar, open source software quality management tool. * Copyright (C) 2009 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.jira.metrics; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; public class JiraWidgetTest { @Test public void testGetTemplatePath() { String path = new JiraWidget().getTemplatePath(); assertThat(getClass().getResource(path)).isNotNull(); } @Test public void testNameAndTitle() throws Exception { JiraWidget widget = new JiraWidget(); assertThat(widget.getId()).isEqualTo("jira"); assertThat(widget.getTitle()).isEqualTo("JIRA issues"); } }
apache-2.0
rwth-acis/REST-OCD-Services
rest_ocd_services/src/main/java/i5/las2peer/services/ocd/centrality/utils/CentralityAlgorithmFactory.java
1036
package i5.las2peer.services.ocd.centrality.utils; import java.util.Map; import i5.las2peer.services.ocd.centrality.data.CentralityMeasureType; import i5.las2peer.services.ocd.utils.ConditionalParameterizableFactory; public class CentralityAlgorithmFactory implements ConditionalParameterizableFactory<CentralityAlgorithm, CentralityMeasureType> { public boolean isInstantiatable(CentralityMeasureType creationType) { if(creationType.correspondsAlgorithm()) { return true; } else { return false; } } @Override public CentralityAlgorithm getInstance(CentralityMeasureType centralityMeasureType, Map<String, String> parameters) throws InstantiationException, IllegalAccessException { if(isInstantiatable(centralityMeasureType)) { CentralityAlgorithm algorithm = (CentralityAlgorithm) centralityMeasureType.getCreationMethodClass().newInstance(); algorithm.setParameters(parameters); return algorithm; } throw new IllegalStateException("This creation type is not an instantiatable algorithm."); } }
apache-2.0