text
stringlengths 7
1.01M
|
|---|
/**
* Copyright (C) 2014-2019 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.servlet.async;
import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of {@link IAsyncServletRunner}
*
* @author Philip Helger
* @since 8.8.0
*/
public class AsyncServletRunnerDefault implements IAsyncServletRunner
{
private static final Logger LOGGER = LoggerFactory.getLogger (AsyncServletRunnerDefault.class);
public AsyncServletRunnerDefault ()
{}
public void runAsync (@Nonnull final HttpServletRequest aOriginalHttpRequest,
@Nonnull final HttpServletResponse aOriginalHttpResponse,
@Nonnull final ExtAsyncContext aAsyncContext,
@Nonnull final Runnable aRunnable)
{
final Runnable aRealRunner = () -> {
// Debug - safe references to original req/resp
final HttpServletRequest o1 = aOriginalHttpRequest;
final HttpServletResponse o2 = aOriginalHttpResponse;
if (o1 != null && o2 != null)
aRunnable.run ();
else
if (LOGGER.isErrorEnabled ())
LOGGER.error ("Original request (" + o1 + ") or original response (" + o2 + ") are invalid!");
};
// Important to use "start" and to not use a custom ExecutorService, as this
// "start" method assigns all the necessary variables etc.
aAsyncContext.start (aRealRunner);
}
}
|
licensed apache software foundation asf contributor license agreements notice file distributed work additional copyright ownership asf licenses file apache license version license file compliance license copy license http apache org licenses license required applicable law agreed writing software distributed license distributed basis warranties conditions kind express implied license specific language governing permissions limitations license software consists voluntary contributions individuals behalf apache software foundation originally based software copyright int ernational international business mac hines machines http apache org apache software foundation http apache org org apache sling scripting jsp jasper xml parser xmlparser xml string xmlstring structure pass character arrays xml string buffer xmlstringbuffer buffer characters appended xml string xmlstring passed methods expecting xml string xmlstring object safe operation assumed callee strong strong modify contents xml string xmlstring structure contents string managed string buffer characters appended string buffer grow needed strong note strong code code code offset code code length code fields fields managed string buffer order reset buffer call code clear code author andy clark ibm author eric ibm version xml string buffer xmlstringbuffer java mark t markt xml string buffer xmlstringbuffer xml string xmlstring constants buffer size size xml string buffer xmlstringbuffer size param size xml string buffer xmlstringbuffer size size constructs string buffer xml string buffer xmlstringbuffer append constructs string buffer string xml string buffer xmlstringbuffer string length append constructs string buffer character array xml string buffer xmlstringbuffer offset length length append offset length constructs string buffer xml string xmlstring xml string buffer xmlstringbuffer xml string xmlstring length append init xml string xmlstring methods clears string buffer clear offset length append param append length length new length newlength length new length newlength length size new length newlength length size new ch newch new length newlength system arraycopy new ch newch length new ch newch length length append append param append string length length length length length new length newlength length new length newlength length length size new length newlength length length size new ch newch new length newlength system arraycopy new ch newch length new ch newch get chars getchars length length length length append string append param param offset param length append offset length length length length new ch newch length length size system arraycopy new ch newch length new ch newch system arraycopy offset length length length length append append param append xml string xmlstring append offset length append xml string xmlstring xml string buffer xmlstringbuffer
|
/* SPDX-License-Identifier: Apache 2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.accessservices.communityprofile.server.spring;
import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.odpi.openmetadata.accessservices.communityprofile.rest.MetadataSourceRequestBody;
import org.odpi.openmetadata.accessservices.communityprofile.rest.UserIdentityListResponse;
import org.odpi.openmetadata.accessservices.communityprofile.rest.UserIdentityRequestBody;
import org.odpi.openmetadata.accessservices.communityprofile.rest.UserIdentityResponse;
import org.odpi.openmetadata.accessservices.communityprofile.server.UserIdentityRESTServices;
import org.odpi.openmetadata.commonservices.ffdc.rest.GUIDResponse;
import org.odpi.openmetadata.commonservices.ffdc.rest.NameRequestBody;
import org.odpi.openmetadata.commonservices.ffdc.rest.SearchStringRequestBody;
import org.odpi.openmetadata.commonservices.ffdc.rest.VoidResponse;
import org.springframework.web.bind.annotation.*;
/**
* UserIdentityResource provides the APIs for maintaining user identities and their relationships with profiles.
*/
@RestController
@RequestMapping("/servers/{serverName}/open-metadata/access-services/community-profile/users/{userId}")
@Tag(name="Community Profile OMAS", description="The Community Profile OMAS provides APIs and events for tools and applications that are managing information about people and the way they work together.", externalDocs=@ExternalDocumentation(description="Community Profile Open Metadata Access Service (OMAS)",url="https://egeria.odpi.org/open-metadata-implementation/access-services/community-profile/"))
public class UserIdentityResource
{
private UserIdentityRESTServices restAPI = new UserIdentityRESTServices();
/**
* Create a UserIdentity. This is not connected to a profile.
*
* @param serverName name of target server
* @param userId the name of the calling user.
* @param requestBody userId for the new userIdentity.
*
* @return guid or
* InvalidParameterException - one of the parameters is invalid or
* PropertyServerException - there is a problem retrieving information from the property server(s) or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
@PostMapping(path = "/user-identities")
public GUIDResponse createUserIdentity(@PathVariable String serverName,
@PathVariable String userId,
@RequestBody UserIdentityRequestBody requestBody)
{
return restAPI.createUserIdentity(serverName, userId, requestBody);
}
/**
* Update a UserIdentity.
*
* @param serverName name of target server
* @param userId the name of the calling user
* @param userIdentityGUID unique identifier of the UserIdentity
* @param isMergeUpdate should the supplied properties be overlaid on the existing properties (true) or replace them (false
* @param requestBody updated properties for the new userIdentity
*
* @return void or
* InvalidParameterException one of the parameters is invalid.
* PropertyServerException there is a problem retrieving information from the property server(s).
* UserNotAuthorizedException the requesting user is not authorized to issue this request.
*/
@PostMapping(path = "/user-identities/{userIdentityGUID}")
public VoidResponse updateUserIdentity(@PathVariable String serverName,
@PathVariable String userId,
@PathVariable String userIdentityGUID,
@RequestParam boolean isMergeUpdate,
@RequestBody UserIdentityRequestBody requestBody)
{
return restAPI.updateUserIdentity(serverName, userId, userIdentityGUID, isMergeUpdate, requestBody);
}
/**
* Remove a user identity object. This will fail if a profile would be left without an
* associated user identity.
*
* @param serverName name of target server
* @param userId the name of the calling user.
* @param userIdentityGUID unique identifier of the UserIdentity
* @param requestBody external source identifiers
*
* @return void or
* InvalidParameterException - one of the parameters is invalid or
* PropertyServerException - there is a problem retrieving information from the property server(s) or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
@PostMapping(path = "/user-identities/{userIdentityGUID}/delete")
public VoidResponse deleteUserIdentity(@PathVariable String serverName,
@PathVariable String userId,
@PathVariable String userIdentityGUID,
@RequestBody MetadataSourceRequestBody requestBody)
{
return restAPI.deleteUserIdentity(serverName, userId, userIdentityGUID, requestBody);
}
/**
* Link a user identity to a profile. This will fail if the user identity is already connected to
* a profile.
*
* @param serverName name of target server
* @param userId the name of the calling user.
* @param userIdentityGUID unique identifier of the UserIdentity
* @param profileGUID the profile to add the identity to.
* @param requestBody external source identifiers
*
* @return void or
* InvalidParameterException - one of the parameters is invalid or
* PropertyServerException - there is a problem retrieving information from the property server(s) or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
@PostMapping(path = "/user-identities/{userIdentityGUID}/personal-profiles/{profileGUID}/link")
public VoidResponse addIdentityToProfile(@PathVariable String serverName,
@PathVariable String userId,
@PathVariable String userIdentityGUID,
@PathVariable String profileGUID,
@RequestBody MetadataSourceRequestBody requestBody)
{
return restAPI.addIdentityToProfile(serverName, userId, userIdentityGUID, profileGUID, requestBody);
}
/**
* Remove a user identity object. This will fail if the profile would be left without an
* associated user identity.
*
* @param serverName name of target server
* @param userId the name of the calling user.
* @param userIdentityGUID unique identifier of the UserIdentity
* @param profileGUID the profile to add the identity to.
* @param requestBody external source identifiers
*
* @return void or
* InvalidParameterException - one of the parameters is invalid or
* PropertyServerException - there is a problem retrieving information from the property server(s) or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
@PostMapping(path = "/user-identities/{userIdentityGUID}/profiles/{profileGUID}/unlink")
public VoidResponse removeIdentityFromProfile(@PathVariable String serverName,
@PathVariable String userId,
@PathVariable String userIdentityGUID,
@PathVariable String profileGUID,
@RequestBody MetadataSourceRequestBody requestBody)
{
return restAPI.removeIdentityFromProfile(serverName, userId, userIdentityGUID, profileGUID, requestBody);
}
/**
* Retrieve the list of user identity metadata elements that contain the search string.
* The search string is treated as a regular expression.
*
* @param serverName name of target server
* @param userId calling user
* @param startFrom paging start point
* @param pageSize maximum results that can be returned
* @param requestBody string to find in the properties
*
* @return list of matching metadata elements or
* InvalidParameterException one of the parameters is invalid
* UserNotAuthorizedException the user is not authorized to issue this request
* PropertyServerException there is a problem reported in the open metadata server(s)
*/
@PostMapping(path = "/user-identities/by-search-string")
public UserIdentityListResponse findUserIdentities(@PathVariable String serverName,
@PathVariable String userId,
@RequestParam int startFrom,
@RequestParam int pageSize,
@RequestBody SearchStringRequestBody requestBody)
{
return restAPI.findUserIdentities(serverName, userId, startFrom, pageSize, requestBody);
}
/**
* Retrieve the list of user identity metadata elements with a matching qualified name.
* There are no wildcards supported on this request.
*
* @param serverName name of target server
* @param userId calling user
* @param startFrom paging start point
* @param pageSize maximum results that can be returned
* @param requestBody name to search for
*
* @return list of matching metadata elements
* InvalidParameterException one of the parameters is invalid
* UserNotAuthorizedException the user is not authorized to issue this request
* PropertyServerException there is a problem reported in the open metadata server(s)
*/
@PostMapping(path = "/user-identities/by-name")
public UserIdentityListResponse getUserIdentitiesByName(@PathVariable String serverName,
@PathVariable String userId,
@RequestParam int startFrom,
@RequestParam int pageSize,
@RequestBody NameRequestBody requestBody)
{
return restAPI.getUserIdentitiesByName(serverName, userId, startFrom, pageSize, requestBody);
}
/**
* Retrieve the userIdentity metadata element with the supplied unique identifier.
*
* @param serverName name of target server
* @param userId calling user
* @param userIdentityGUID unique identifier of the requested metadata element
*
* @return matching metadata element or
*
* InvalidParameterException one of the parameters is invalid
* UserNotAuthorizedException the user is not authorized to issue this request
* PropertyServerException there is a problem reported in the open metadata server(s)
*/
public UserIdentityResponse getUserIdentityByGUID(String serverName,
String userId,
String userIdentityGUID)
{
return restAPI.getUserIdentityByGUID(serverName, userId, userIdentityGUID);
}
}
|
// Copyright 2015 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
// www.source-code.biz, www.inventec.ch/chdh
//
// This module is multi-licensed and may be used under the terms of any of the following licenses:
//
// LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html
// EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal
//
// Please contact the author if you need another license.
// This module is provided "as is", without warranties of any kind.
//
// Home page: http://www.source-code.biz/snippets/java/RawConsoleInput
package biz.source_code.utils;
import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;
import java.util.List;
/**
* A JNA based driver for reading single characters from the console.
* <p>
* <p>This class is used for console mode programs.
* It supports non-blocking reads of single key strokes without echo.
*/
public class RawConsoleInput {
private static final boolean isWindows = System.getProperty("os.name").startsWith("Windows");
private static final int invalidKey = 0xFFFE;
private static final String invalidKeyStr = String.valueOf((char) invalidKey);
private static final int stdinFd = 0;
private static boolean initDone;
private static boolean stdinIsConsole;
private static boolean consoleModeAltered;
private static Msvcrt msvcrt;
private static Kernel32 kernel32;
private static Pointer consoleHandle;
//--- Windows ------------------------------------------------------------------
// The Windows version uses _kbhit() and _getwch() from msvcrt.dll.
private static int originalConsoleMode;
private static Libc libc;
private static CharsetDecoder charsetDecoder;
private static Termios originalTermios;
private static Termios rawTermios;
private static Termios intermediateTermios;
/**
* Reads a character from the console without echo.
*
* @param wait <code>true</code> to wait until an input character is available,
* <code>false</code> to return immediately if no character is available.
* @return -2 if <code>wait</code> is <code>false</code> and no character is available.
* -1 on EOF.
* Otherwise an Unicode character code within the range 0 to 0xFFFF.
*/
public static int read(boolean wait) throws IOException {
if (isWindows) {
return readWindows(wait);
} else {
return readUnix(wait);
}
}
/**
* Resets console mode to normal line mode with echo.
* <p>
* <p>On Windows this method re-enables Ctrl-C processing.
* <p>
* <p>On Unix this method switches the console back to echo mode.
* read() leaves the console in non-echo mode.
*/
public static void resetConsoleMode() throws IOException {
if (isWindows) {
resetConsoleModeWindows();
} else {
resetConsoleModeUnix();
}
}
private static void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdownHook();
}
});
}
private static void shutdownHook() {
try {
resetConsoleMode();
} catch (Exception e) {
}
}
private static int readWindows(boolean wait) throws IOException {
initWindows();
if (!stdinIsConsole) {
int c = msvcrt.getwchar();
if (c == 0xFFFF) {
c = -1;
}
return c;
}
consoleModeAltered = true;
setConsoleMode(consoleHandle, originalConsoleMode & ~Kernel32Defs.ENABLE_PROCESSED_INPUT);
// ENABLE_PROCESSED_INPUT must remain off to prevent Ctrl-C from beeing processed by the system
// while the program is not within getwch().
if (!wait && msvcrt._kbhit() == 0) {
return -2;
} // no key available
return getwch();
}
private static int getwch() {
int c = msvcrt._getwch();
if (c == 0 || c == 0xE0) { // Function key or arrow key
c = msvcrt._getwch();
if (c >= 0 && c <= 0x18FF) {
return 0xE000 + c;
} // construct key code in private Unicode range
return invalidKey;
}
if (c < 0 || c > 0xFFFF) {
return invalidKey;
}
return c;
} // normal key
private static synchronized void initWindows() throws IOException {
if (initDone) {
return;
}
msvcrt = Native.loadLibrary("msvcrt", Msvcrt.class);
kernel32 = Native.loadLibrary("kernel32", Kernel32.class);
try {
consoleHandle = getStdInputHandle();
originalConsoleMode = getConsoleMode(consoleHandle);
stdinIsConsole = true;
} catch (IOException e) {
stdinIsConsole = false;
}
if (stdinIsConsole) {
registerShutdownHook();
}
initDone = true;
}
private static Pointer getStdInputHandle() throws IOException {
Pointer handle = kernel32.GetStdHandle(Kernel32Defs.STD_INPUT_HANDLE);
if (Pointer.nativeValue(handle) == 0 || Pointer.nativeValue(handle) == Kernel32Defs.INVALID_HANDLE_VALUE) {
throw new IOException("GetStdHandle(STD_INPUT_HANDLE) failed.");
}
return handle;
}
//--- Unix ---------------------------------------------------------------------
// The Unix version uses tcsetattr() to switch the console to non-canonical mode,
// System.in.available() to check whether data is available and System.in.read()
// to read bytes from the console.
// A CharsetDecoder is used to convert bytes to characters.
private static int getConsoleMode(Pointer handle) throws IOException {
IntByReference mode = new IntByReference();
int rc = kernel32.GetConsoleMode(handle, mode);
if (rc == 0) {
throw new IOException("GetConsoleMode() failed.");
}
return mode.getValue();
}
private static void setConsoleMode(Pointer handle, int mode) throws IOException {
int rc = kernel32.SetConsoleMode(handle, mode);
if (rc == 0) {
throw new IOException("SetConsoleMode() failed.");
}
}
private static void resetConsoleModeWindows() throws IOException {
if (!initDone || !stdinIsConsole || !consoleModeAltered) {
return;
}
setConsoleMode(consoleHandle, originalConsoleMode);
consoleModeAltered = false;
}
private static int readUnix(boolean wait) throws IOException {
initUnix();
if (!stdinIsConsole) { // STDIN is not a console
return readSingleCharFromByteStream(System.in);
}
consoleModeAltered = true;
setTerminalAttrs(stdinFd, rawTermios); // switch off canonical mode, echo and signals
try {
if (!wait && System.in.available() == 0) {
return -2;
} // no input available
return readSingleCharFromByteStream(System.in);
} finally {
setTerminalAttrs(stdinFd, intermediateTermios);
}
} // reset some console attributes
private static Termios getTerminalAttrs(int fd) throws IOException {
Termios termios = new Termios();
try {
int rc = libc.tcgetattr(fd, termios);
if (rc != 0) {
throw new RuntimeException("tcgetattr() failed.");
}
} catch (LastErrorException e) {
throw new IOException("tcgetattr() failed.", e);
}
return termios;
}
private static void setTerminalAttrs(int fd, Termios termios) throws IOException {
try {
int rc = libc.tcsetattr(fd, LibcDefs.TCSANOW, termios);
if (rc != 0) {
throw new RuntimeException("tcsetattr() failed.");
}
} catch (LastErrorException e) {
throw new IOException("tcsetattr() failed.", e);
}
}
private static int readSingleCharFromByteStream(InputStream inputStream) throws IOException {
byte[] inBuf = new byte[4];
int inLen = 0;
while (true) {
if (inLen >= inBuf.length) { // input buffer overflow
return invalidKey;
}
int b = inputStream.read(); // read next byte
if (b == -1) { // EOF
return -1;
}
inBuf[inLen++] = (byte) b;
int c = decodeCharFromBytes(inBuf, inLen);
if (c != -1) {
return c;
}
}
}
// (This method is synchronized because the charsetDecoder must only be used by a single thread at once.)
private static synchronized int decodeCharFromBytes(byte[] inBytes, int inLen) {
charsetDecoder.reset();
charsetDecoder.onMalformedInput(CodingErrorAction.REPLACE);
charsetDecoder.replaceWith(invalidKeyStr);
ByteBuffer in = ByteBuffer.wrap(inBytes, 0, inLen);
CharBuffer out = CharBuffer.allocate(1);
charsetDecoder.decode(in, out, false);
if (out.position() == 0) {
return -1;
}
return out.get(0);
}
private static synchronized void initUnix() throws IOException {
if (initDone) {
return;
}
libc = Native.loadLibrary("c", Libc.class);
stdinIsConsole = libc.isatty(stdinFd) == 1;
charsetDecoder = Charset.defaultCharset().newDecoder();
if (stdinIsConsole) {
originalTermios = getTerminalAttrs(stdinFd);
rawTermios = new Termios(originalTermios);
rawTermios.c_lflag &= ~(LibcDefs.ICANON | LibcDefs.ECHO | LibcDefs.ECHONL | LibcDefs.ISIG);
intermediateTermios = new Termios(rawTermios);
intermediateTermios.c_lflag |= LibcDefs.ICANON;
// Canonical mode can be switched off between the read() calls, but echo must remain disabled.
registerShutdownHook();
}
initDone = true;
}
private static void resetConsoleModeUnix() throws IOException {
if (!initDone || !stdinIsConsole || !consoleModeAltered) {
return;
}
setTerminalAttrs(stdinFd, originalTermios);
consoleModeAltered = false;
}
private interface Msvcrt extends Library {
int _kbhit();
int _getwch();
int getwchar();
}
private interface Kernel32 extends Library {
int GetConsoleMode(Pointer hConsoleHandle, IntByReference lpMode);
int SetConsoleMode(Pointer hConsoleHandle, int dwMode);
Pointer GetStdHandle(int nStdHandle);
}
private interface Libc extends Library {
// termios.h
int tcgetattr(int fd, Termios termios) throws LastErrorException;
int tcsetattr(int fd, int opt, Termios termios) throws LastErrorException;
// unistd.h
int isatty(int fd);
}
private static class Kernel32Defs {
static final int STD_INPUT_HANDLE = -10;
static final long INVALID_HANDLE_VALUE = (Pointer.SIZE == 8) ? -1 : 0xFFFFFFFFL;
static final int ENABLE_PROCESSED_INPUT = 0x0001;
static final int ENABLE_LINE_INPUT = 0x0002;
static final int ENABLE_ECHO_INPUT = 0x0004;
static final int ENABLE_WINDOW_INPUT = 0x0008;
}
protected static class Termios extends Structure { // termios.h
public int c_iflag;
public int c_oflag;
public int c_cflag;
public int c_lflag;
public byte c_line;
public byte[] filler = new byte[64]; // actual length is platform dependent
Termios() {
}
Termios(Termios t) {
c_iflag = t.c_iflag;
c_oflag = t.c_oflag;
c_cflag = t.c_cflag;
c_lflag = t.c_lflag;
c_line = t.c_line;
filler = t.filler.clone();
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("c_iflag", "c_oflag", "c_cflag", "c_lflag", "c_line", "filler");
}
}
private static class LibcDefs {
// termios.h
static final int ISIG = 0000001;
static final int ICANON = 0000002;
static final int ECHO = 0000010;
static final int ECHONL = 0000100;
static final int TCSANOW = 0;
}
}
|
package io.tatum.model.response.tron;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode
@JsonIgnoreProperties(ignoreUnknown = true)
public class Ret {
private String contractRet;
private long fee;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.dpulab.hideaway.models;
import org.apache.commons.lang3.StringUtils;
import org.dpulab.hideaway.models.objecttable.TableColumnInfo;
import org.junit.*;
import static org.junit.Assert.*;
/**
*
* @author dipu
*/
public class IndexEntryModelTest {
public IndexEntryModelTest() {
}
@BeforeClass
public static void setUpClass() {
System.out.println(StringUtils.center(" IndexEntry ", 80, "="));
}
@AfterClass
public static void tearDownClass() {
System.out.println(StringUtils.center("", 80, "-"));
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testColumnEntries() {
TableColumnInfo[] columns = TableColumnInfo.build(IndexEntryModel.class);
assertNotNull(columns);
assertTrue(columns.length > 0);
}
@Test
public void testFieldReflection() {
System.out.println(StringUtils.center(" Test Field Reflection ", 60, '-'));
IndexEntryModel entry = new IndexEntryModel();
entry.fileName = "My Sample Entry";
entry.fileSize = 80105325;
TableColumnInfo[] items = TableColumnInfo.build(IndexEntryModel.class);
for (TableColumnInfo col : items) {
System.out.printf("* %s = %s (edit: %s, update: %s, style: %s)\n",
col.getName(), col.extractValue(entry), col.isEditable(), col.canUpdate(), col.getStyle());
}
}
}
|
package org.codehaus.mojo.exec;
/*
* Copyright 2005 The Codehaus. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the
* License.
*/
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.OS;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.DefaultArtifactRepository;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.monitor.logging.DefaultLog;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.util.StringOutputStream;
/**
* @author Jerome Lacoste
* @version $Id$
*/
public class ExecMojoTest
extends AbstractMojoTestCase
{
/*
* Finding a file actually on disk of the test system makes some of the tests fail.
* Hence a purely random UUID is used to prevent this situation.
*/
private static final String SOME_EXECUTABLE = UUID.randomUUID().toString();
private MockExecMojo mojo;
static class MockExecMojo
extends ExecMojo
{
public int executeResult;
public List<CommandLine> commandLines = new ArrayList<CommandLine>();
public String failureMsg;
public Map<String, String> systemProperties = new HashMap<String, String>();
protected int executeCommandLine( Executor exec, CommandLine commandLine, Map enviro, OutputStream out,
OutputStream err )
throws IOException, ExecuteException
{
commandLines.add( commandLine );
if ( failureMsg != null )
{
throw new ExecuteException( failureMsg, executeResult );
}
return executeResult;
}
protected String getSystemProperty( String key )
{
return systemProperties.get( key );
}
int getAmountExecutedCommandLines()
{
return commandLines.size();
}
CommandLine getExecutedCommandline( int index )
{
return commandLines.get( index );
}
}
public void setUp()
throws Exception
{
super.setUp();
mojo = new MockExecMojo();
// note: most of the tests below assume that the specified
// executable path is not fully specicied. See ExecMojo#getExecutablePath
mojo.setExecutable( SOME_EXECUTABLE );
mojo.setArguments( Arrays.asList( new String[] { "--version" } ) );
mojo.executeResult = 0;
mojo.setBasedir( File.createTempFile( "mvn-temp", "txt" ).getParentFile() );
}
public void testRunOK()
throws MojoExecutionException
{
mojo.execute();
checkMojo( SOME_EXECUTABLE + " --version" );
}
/*
* This one won't work yet public void xxtestSimpleRunPropertiesAndArguments() throws MojoExecutionException,
* Exception { File pom = new File( getBasedir(), "src/test/projects/project1/pom.xml" ); String output = execute(
* pom, "exec" ); System.out.println(" OUTPUT" + output + "\n\n\n"); String expectedOutput =
* "arg.arg1\narg.arg2\nproject.env1=value1"; // FIXME should work on Windows as well assertEquals( expectedOutput,
* output ); }
*/
/**
* integration test... - compile the Test class using mvn clean compile - run the test file using java, use it to
* generate a file whose contains are compared to expected output
*/
// public void testRunOKWithAutoComputedClasspath()
// throws MojoExecutionException, Exception
// {
// String projectName = "project1";
//
// ExecMojo mojo = new ExecMojo();
//
// setUpProject( projectName, mojo );
//
// // compile project
// mojo.setExecutable( SOME_EXECUTABLE );
// mojo.setWorkingDirectory( new File( "src/test/projects/" + projectName + "/" ) );
// mojo.setArguments( Arrays.asList( new String[]{"clean", "compile"} ) );
//
// mojo.execute();
//
// mojo.getLog().info( "executed mvn clean compile" );
//
// // the command executes the test class
// mojo.setExecutable( "java" );
// mojo.setWorkingDirectory( (File) null );
// Classpath classpath = new Classpath();
// mojo.setArguments( Arrays.asList( new Object[]{"-Dproject.env1=value1", "-classpath", classpath,
// "org.codehaus.mojo.exec.test.Test",
// new File( "src/test/projects/" + projectName + "/target/exec/output.txt" ).getAbsolutePath(), "arg1",
// "arg2"} ) );
//
// mojo.execute();
//
// // checking the command line would involve resolving the repository
// // checkMojo( "java -cp" );
//
// assertFileEquals( null, getTestFile( "src/test/projects/" + projectName + "/output.txt" ),
// getTestFile( "src/test/projects/" + projectName + "/target/exec/output.txt" ) );
//
// // the command executes the test class, this time specifying the dependencies
// mojo.setExecutable( "java" );
// mojo.setWorkingDirectory( (File) null );
// classpath = new Classpath();
// List dependencies = new ArrayList();
// dependencies.add( "commons-io:commons-io" );
// classpath.setDependencies( dependencies );
// mojo.setArguments( Arrays.asList( new Object[]{"-Dproject.env1=value1", "-classpath", classpath,
// "org.codehaus.mojo.exec.test.Test",
// new File( "src/test/projects/" + projectName + "/target/exec/output.txt" ).getAbsolutePath(), "arg1",
// "arg2"} ) );
//
// mojo.execute();
//
// // checking the command line would involve resolving the repository
// // checkMojo( "java -cp" );
//
// assertFileEquals( null, getTestFile( "src/test/projects/" + projectName + "/output.txt" ),
// getTestFile( "src/test/projects/" + projectName + "/target/exec/output.txt" ) );
// }
/**
*
* @param pom the pom file
* @param goal the goal to execute
* @return output from System.out during mojo execution
* @throws Exception if any exception occurs
*/
protected String execute( File pom, String goal )
throws Exception
{
ExecMojo mojo;
mojo = (ExecMojo) lookupMojo( goal, pom );
setUpProject( pom, mojo );
MavenProject project = (MavenProject) getVariableValueFromObject( mojo, "project" );
// why isn't this set up by the harness based on the default-value? TODO get to bottom of this!
// setVariableValueToObject( mojo, "includeProjectDependencies", Boolean.TRUE );
// setVariableValueToObject( mojo, "killAfter", new Long( -1 ) );
assertNotNull( mojo );
assertNotNull( project );
// trap System.out
PrintStream out = System.out;
StringOutputStream stringOutputStream = new StringOutputStream();
System.setOut( new PrintStream( stringOutputStream ) );
// ensure we don't log unnecessary stuff which would interfere with assessing success of tests
mojo.setLog( new DefaultLog( new ConsoleLogger( Logger.LEVEL_ERROR, "exec:exec" ) ) );
try
{
mojo.execute();
}
catch ( Throwable e )
{
e.printStackTrace( System.err );
fail( e.getMessage() );
}
finally
{
System.setOut( out );
}
return stringOutputStream.toString();
}
private void setUpProject( File pomFile, ExecMojo mojo )
throws Exception
{
MavenProjectBuilder builder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );
ArtifactRepositoryLayout localRepositoryLayout =
(ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, "default" );
String path = "src/test/repository";
ArtifactRepository localRepository =
new DefaultArtifactRepository( "local", "file://" + new File( path ).getAbsolutePath(),
localRepositoryLayout );
mojo.setBasedir( File.createTempFile( "mvn-temp", "txt" ).getParentFile() );
MavenProject project = builder.buildWithDependencies( pomFile, localRepository, null );
// this gets the classes for these tests of this mojo (exec plugin) onto the project classpath for the test
project.getBuild().setOutputDirectory( new File( "target/test-classes" ).getAbsolutePath() );
mojo.setProject( project );
mojo.setLog( new SystemStreamLog()
{
public boolean isDebugEnabled()
{
return true;
}
} );
}
// MEXEC-12, MEXEC-72
public void testGetExecutablePath()
throws IOException
{
ExecMojo realMojo = new ExecMojo();
File workdir = new File( System.getProperty( "user.dir" ) );
Map<String, String> enviro = new HashMap<String, String>();
String myJavaPath = "target" + File.separator + "javax";
File f = new File( myJavaPath );
assertTrue( "file created...", f.createNewFile() );
assertTrue( "file exists...", f.exists() );
realMojo.setExecutable( myJavaPath );
CommandLine cmd = realMojo.getExecutablePath( enviro, workdir );
assertTrue( "File exists so path is absolute",
cmd.getExecutable().startsWith( System.getProperty( "user.dir" ) ) );
f.delete();
assertFalse( "file deleted...", f.exists() );
cmd = realMojo.getExecutablePath( enviro, workdir );
assertEquals( "File doesn't exist. Let the system find it (in that PATH?)", myJavaPath, cmd.getExecutable() );
if ( OS.isFamilyWindows() ) // Exec Maven Plugin only supports Batch detection and PATH search on Windows
{
myJavaPath = "target" + File.separator + "javax.bat";
f = new File( myJavaPath );
assertTrue( "file created...", f.createNewFile() );
assertTrue( "file exists...", f.exists() );
final String comSpec = System.getenv( "ComSpec" );
realMojo.setExecutable( "javax.bat" );
cmd = realMojo.getExecutablePath( enviro, workdir );
assertTrue( "is bat file on windows, execute using ComSpec.", cmd.getExecutable().equals( comSpec ) );
enviro.put( "PATH", workdir.getAbsolutePath() + File.separator + "target" );
cmd = realMojo.getExecutablePath( enviro, workdir );
assertTrue( "is bat file on windows' PATH, execute using ComSpec.", cmd.getExecutable().equals( comSpec ) );
f.delete();
assertFalse( "file deleted...", f.exists() );
}
}
// under Windows cmd/bat files should be preferred over files with the same prefix without extension, e.g.
// if there are "node" and "node.cmd" the mojo should pick "node.cmd"
// see https://github.com/mojohaus/exec-maven-plugin/issues/42
public void testGetExecutablePathPreferExecutableExtensionsOnWindows()
throws IOException
{
// this test is for Windows
if (!OS.isFamilyWindows()) {
return;
}
final ExecMojo realMojo = new ExecMojo();
final String tmp = System.getProperty("java.io.tmpdir");
final File workdir = new File(tmp, "testGetExecutablePathPreferExecutableExtensionsOnWindows");
workdir.mkdirs();
final Map<String, String> enviro = new HashMap<String, String>();
final File f = new File(workdir, "mycmd");
final File fCmd = new File(workdir, "mycmd.cmd");
f.createNewFile();
fCmd.createNewFile();
assertTrue( "file exists...", f.exists() );
assertTrue( "file exists...", fCmd.exists() );
realMojo.setExecutable( "mycmd" );
final CommandLine cmd = realMojo.getExecutablePath( enviro, workdir );
// cmdline argumets are: [/c, %path-to-temp%\mycmd.cmd], so check second argument
assertTrue( "File should have cmd extension",
cmd.getArguments()[1].endsWith( "mycmd.cmd" ) );
f.delete();
fCmd.delete();
assertFalse( "file deleted...", f.exists() );
assertFalse( "file deleted...", fCmd.exists() );
}
public void testRunFailure()
{
mojo.executeResult = 1;
try
{
mojo.execute();
fail( "expected failure" );
}
catch ( MojoExecutionException e )
{
assertEquals( "Result of " + mojo.getExecutedCommandline( 0 ) + " execution is: '1'.", e.getMessage() );
}
checkMojo( SOME_EXECUTABLE + " --version" );
}
public void testRunError()
{
mojo.failureMsg = "simulated failure";
try
{
mojo.execute();
fail( "expected failure" );
}
catch ( MojoExecutionException e )
{
assertEquals( "Command execution failed.", e.getMessage() );
}
checkMojo( SOME_EXECUTABLE + " --version" );
}
public void testOverrides()
throws MojoExecutionException
{
mojo.systemProperties.put( "exec.args", "-f pom.xml" );
mojo.execute();
checkMojo( SOME_EXECUTABLE + " -f pom.xml" );
}
public void testOverrides3()
throws MojoExecutionException
{
mojo.systemProperties.put( "exec.args", null );
mojo.execute();
checkMojo( SOME_EXECUTABLE + " --version" );
mojo.commandLines.clear();
mojo.systemProperties.put( "exec.args", "" );
mojo.execute();
checkMojo( SOME_EXECUTABLE + " --version" );
}
public void testIsResultCodeAFailure()
{
ExecMojo execMojo = new ExecMojo();
assertTrue( execMojo.isResultCodeAFailure( 1 ) );
assertFalse( execMojo.isResultCodeAFailure( 0 ) );
execMojo.setSuccessCodes( new Integer[0] );
assertTrue( execMojo.isResultCodeAFailure( 1 ) );
assertFalse( execMojo.isResultCodeAFailure( 0 ) );
execMojo.setSuccessCodes( new Integer[] { Integer.valueOf( "2" ), Integer.valueOf( "5" ) } );
assertTrue( execMojo.isResultCodeAFailure( 0 ) );
assertTrue( execMojo.isResultCodeAFailure( 10 ) );
assertFalse( execMojo.isResultCodeAFailure( 2 ) );
assertFalse( execMojo.isResultCodeAFailure( 5 ) );
}
// MEXEC-81
public void testParseCommandlineOSWin()
throws Exception
{
ExecMojo execMojo = new ExecMojo();
final String javaHome = "C:\\Java\\jdk1.5.0_15";
// can only be set by expression or plugin-configuration
setVariableValueToObject( execMojo, "commandlineArgs", javaHome );
String[] args = execMojo.parseCommandlineArgs();
assertEquals( javaHome, args[0] );
}
private void checkMojo( String expectedCommandLine )
{
assertEquals( 1, mojo.getAmountExecutedCommandLines() );
CommandLine commandline = mojo.getExecutedCommandline( 0 );
// do NOT depend on Commandline toString()
assertEquals( expectedCommandLine, getCommandLineAsString( commandline ) );
}
private String getCommandLineAsString( CommandLine commandline )
{
// for the sake of the test comparisons, cut out the eventual
// cmd /c *.bat conversion
String result = commandline.getExecutable();
boolean isCmd = false;
if ( OS.isFamilyWindows() && result.equals( "cmd" ) )
{
result = "";
isCmd = true;
}
String[] arguments = commandline.getArguments();
for ( int i = 0; i < arguments.length; i++ )
{
String arg = arguments[i];
if ( isCmd && i == 0 && "/c".equals( arg ) )
{
continue;
}
if ( isCmd && i == 1 && arg.endsWith( ".bat" ) )
{
arg = arg.substring( 0, arg.length() - ".bat".length() );
}
result += ( result.length() == 0 ? "" : " " ) + arg;
}
return result;
}
}
|
/*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2019 Nokia. 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.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdcrests.item.types;
import org.junit.jupiter.api.Test;
import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor;
import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.MatcherAssert.assertThat;
class RevisionDtoTest {
@Test
void testBean() {
assertThat(RevisionDto.class, allOf(
hasValidBeanConstructor(),
hasValidGettersAndSetters()
));
}
}
|
package org.calipsoide.featurevalves;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.function.Consumer;
import static java.util.concurrent.TimeUnit.SECONDS;
import static reactor.core.publisher.Mono.justOrEmpty;
/**
* Created by epalumbo on 9/17/17.
*/
@Service
public class CachingFeatureService implements FeatureService, Consumer<Feature> {
private static final Logger logger = LoggerFactory.getLogger(CachingFeatureService.class);
private Cache<FeatureId, Feature> cache;
public CachingFeatureService(@Value("${features.cache.ttl}") String ttl) {
this.cache = CacheBuilder.newBuilder()
.expireAfterWrite(Duration.parse(ttl).getSeconds(), SECONDS)
.build();
}
@Override
public Mono<Feature> findBy(FeatureId id) {
final Feature cached = cache.getIfPresent(id);
return justOrEmpty(cached);
}
@Override
public void accept(Feature feature) {
cache.put(feature.getId(), feature);
logger.debug("Reloaded - {}", feature);
}
}
|
/*
* Copyright 2013 University of Glasgow.
*
* 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 to provide an interface to the data files for the project.
* <p>
*/
package broadwick.data;
|
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Contains connectors for change data capture events from MySQL
* databases.
*
* @since Jet 4.2
*/
package com.hazelcast.jet.cdc.mysql;
|
/*
* Copyright 2002-2018 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.support;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* Simple object instantiation strategy for use in a BeanFactory.
*
* <p>Does not support Method Injection, although it provides hooks for subclasses
* to override to add Method Injection support, for example by overriding methods.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 1.1
*/
public class SimpleInstantiationStrategy implements InstantiationStrategy {
private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<>();
/**
* Return the factory method currently being invoked or {@code null} if none.
* <p>Allows factory method implementations to determine whether the current
* caller is the container itself as opposed to user code.
*/
@Nullable
public static Method getCurrentlyInvokedFactoryMethod() {
return currentlyInvokedFactoryMethod.get();
}
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
// 得到默认的构造方法
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 使用默认构造方法来实例化bean
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
/**
* Subclasses can override this method, which is implemented to throw
* UnsupportedOperationException, if they can instantiate an object with
* the Method Injection specified in the given RootBeanDefinition.
* Instantiation should use a no-arg constructor.
*/
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
final Constructor<?> ctor, Object... args) {
if (!bd.hasMethodOverrides()) {
if (System.getSecurityManager() != null) {
// use own privileged to change accessibility (when security is on)
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(ctor);
return null;
});
}
return BeanUtils.instantiateClass(ctor, args);
}
else {
return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
}
}
/**
* Subclasses can override this method, which is implemented to throw
* UnsupportedOperationException, if they can instantiate an object with
* the Method Injection specified in the given RootBeanDefinition.
* Instantiation should use the given constructor and parameters.
*/
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName,
BeanFactory owner, @Nullable Constructor<?> ctor, Object... args) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Object factoryBean, final Method factoryMethod, Object... args) {
try {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(factoryMethod);
return null;
});
}
else {
ReflectionUtils.makeAccessible(factoryMethod);
}
Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get();
try {
currentlyInvokedFactoryMethod.set(factoryMethod);
Object result = factoryMethod.invoke(factoryBean, args);
if (result == null) {
result = new NullBean();
}
return result;
}
finally {
if (priorInvokedFactoryMethod != null) {
currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod);
}
else {
currentlyInvokedFactoryMethod.remove();
}
}
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(factoryMethod,
"Illegal arguments to factory method '" + factoryMethod.getName() + "'; " +
"args: " + StringUtils.arrayToCommaDelimitedString(args), ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(factoryMethod,
"Cannot access factory method '" + factoryMethod.getName() + "'; is it public?", ex);
}
catch (InvocationTargetException ex) {
String msg = "Factory method '" + factoryMethod.getName() + "' threw exception";
if (bd.getFactoryBeanName() != null && owner instanceof ConfigurableBeanFactory &&
((ConfigurableBeanFactory) owner).isCurrentlyInCreation(bd.getFactoryBeanName())) {
msg = "Circular reference involving containing bean '" + bd.getFactoryBeanName() + "' - consider " +
"declaring the factory method as static for independence from its containing instance. " + msg;
}
throw new BeanInstantiationException(factoryMethod, msg, ex.getTargetException());
}
}
}
|
package cn.devileo.trackpadsimulator.keyboard;
import java.nio.ByteBuffer;
import cn.devileo.trackpadsimulator.Common;
import cn.devileo.trackpadsimulator.MainActivityInterface;
import cn.devileo.trackpadsimulator.R;
import cn.devileo.trackpadsimulator.Util;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.inputmethodservice.Keyboard.Key;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.util.Log;
public class KeyboardListener implements
OnKeyboardActionListener {
static final String LOG_TAG = "TrackPad_KeyboardListener";
Context mContext;
MainActivityInterface mDelegate;
public KeyboardListener(Context context, MainActivityInterface delegate){
super();
mContext = context;
mDelegate = delegate;
}
//>> OnKeyboardActionListener
@Override
public void onKey(int primaryCode, int[] keyCodes) {
if (primaryCode > 0) {
if (Common.KK_RESTART == primaryCode) {
createRestartConfirmDialog();
} else if (Common.KK_SHUTDOWN == primaryCode) {
createShutdownConfirmDialog();
} else if (Common.KK_SLEEP == primaryCode) {
createSleepConfirmDialog();
} else {
Key key = KeyboardManager.getKeyByCode(primaryCode, true);
byte action = Common.ACTION_KK_PRESS;
if (key.modifier) {
action = key.on ? Common.ACTION_KK_DOWN : Common.ACTION_KK_UP;
}
sendKey(action, primaryCode);
}
} else {
switch(primaryCode) {
case Common.KMK_ABC:
KeyboardManager.setKeyboardABC();
break;
case Common.KMK_NUMBER_PUNCTUATION:
KeyboardManager.setKeyboardNumberPunctuation();
break;
case Common.KMK_FN:
KeyboardManager.setKeyboardFn();
break;
case Common.KMK_NUMPAD:
KeyboardManager.setKeyboardNumpad();
break;
case Common.KMK_MEDIA:
KeyboardManager.setKeyboardMedia();
break;
case Common.KMK_SHOW_KEYBOARD:
KeyboardManager.showKeyboard();
break;
case Common.KMK_HIDE_KEYBOARD:
KeyboardManager.hideKeyboard();
break;
}
}
StringBuilder log = new StringBuilder(keyCodes.length*8);
for(int k : keyCodes){
log.append(String.format("0x%02x ", k));
}
String gesture = "On Key " + primaryCode + " : " + primaryCode;
mDelegate.setTextGesture(gesture);
mDelegate.setTextCoord(log.toString());
}
@Override
public void onPress(int primaryCode) {
String gesture = "On Press " + primaryCode;
mDelegate.setTextCoord(gesture);
}
@Override
public void onRelease(int primaryCode) {
String gesture = "On Release " + primaryCode;
mDelegate.setTextCoord(gesture);
}
@Override
public void onText(CharSequence text) {
}
@Override
public void swipeDown() {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeUp() {
}
//<< OnKeyboardActionListener
private void sendKey(byte action, int key){
byte[] key_data = Util.convertInt32ToBytes(key);
ByteBuffer bb = ByteBuffer.allocate(6);
bb.put(Common.INPUT_TYPE_KEYBOARD);
bb.put(action);
bb.put(key_data);
byte[] data = bb.array();
mDelegate.sendData(data);
String log = Util.convertBytes2String(data);
Log.i(LOG_TAG, log);
String gesture = "On Key " + action + " : " + key;
mDelegate.setTextGesture(gesture);
mDelegate.setTextCoord(log);
}
private void createSleepConfirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(R.string.msg_confirm_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.msg_confirm_sleep)
.setPositiveButton(R.string.dialog_button_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendKey(Common.ACTION_KK_PRESS, Common.KK_SLEEP);
}
})
.setNegativeButton(R.string.dialog_button_cancel, null);
AlertDialog alert = builder.create();
alert.show();
}
private void createRestartConfirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(R.string.msg_confirm_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.msg_confirm_restart)
.setPositiveButton(R.string.dialog_button_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendKey(Common.ACTION_KK_PRESS, Common.KK_RESTART);
}
})
.setNegativeButton(R.string.dialog_button_cancel, null);
AlertDialog alert = builder.create();
alert.show();
}
private void createShutdownConfirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(R.string.msg_confirm_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.msg_confirm_shutdown)
.setPositiveButton(R.string.dialog_button_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendKey(Common.ACTION_KK_PRESS, Common.KK_SHUTDOWN);
}
})
.setNegativeButton(R.string.dialog_button_cancel, null);
AlertDialog alert = builder.create();
alert.show();
}
}
|
/*
Copyright 2007 batcage@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.
*
*
* * Changes:
* --/nov/2007 Agustin
* -processUploadEvents: saves the UID of the event at google in the correlation map
*/
package com.gcalsync.component;
import javax.microedition.lcdui.*;
import com.gcalsync.cal.gcal.GCalClient;
import com.gcalsync.cal.gcal.GCalEvent;
import com.gcalsync.log.*;
import com.gcalsync.cal.*;
/**
* Public class responsible for drawing the Commit screen and displaying the
* status of uploads/downloads.
* <p>
* <ol>
* <li>The Preview screen displays events that are available for upload/download.</li>
* <li>The user selects "Commit" from the Preview screen to write events to the
* device or to the calendar.</li>
* <li>The application draws the Commit screen in response to the user selecting "Commit".</li>
* </ol>
*
* <p>
*
* This class is also responsible for displaying the results of download/upload events,
* initiating upload/download events, and instantiation of a new instance of the
* CommitEngine class that handles the download/upload of events.
* <p>
* This class uses the MVCComponent base class to retrieve, draw, and update screens.<br>
*
*
* @author
* @see <code>CommitEngine<code/> for code in this class that was commented out and moved
* to com.gcalsync.cal.CommitEngine.
*/
public class CommitComponent extends MVCComponent implements Runnable, StatusLogger {
Form form;
GCalClient gCalClient;
//PhoneCalClient phoneCalClient;
GCalEvent[] uploads;
GCalEvent[] downloads;
/**
* Constructor
*/
public CommitComponent(GCalClient gcal) {
gCalClient = gcal;
}
/**
* Gets the <code>Displayable</code> object to be displayed for
* this component
*
* @returns <code>Displayable</code>
*/
public Displayable getDisplayable() {return this.form;}
/**
* Initializes the model before creating the view
*/
protected void initModel() {}
/**
* Updates the view after it is created
*/
protected void updateView() {}
/**
* Creates the view
*/
protected void createView() {
this.form = new Form("Commit");
this.form.addCommand(new Command("OK", Command.EXIT, 2));
}
/**
* Appends a message to the current form <br>
* Displays the statistics (results) of the uploads and
* downloads that occurred during the commit event
*
* @param message (results of commit event)to be displayed
*/
public void update(String message) {
form.append(message + "\n");
}
/**
* Replaces the last message on the form with a new message
*
* @param message to be displayed
*/
public void updateMinor(String message) {
form.delete(form.size() - 1);
form.append(message + "\n");
}
/**
* Processes menu commands <br>
* If the user presses the Exit button, show the login screen
*
* @param c command to execute
* @param d <code>Displayable</code> from which the command
* originates
*/
public void commandAction(Command c, Displayable d) {
try {
if (c.getCommandType() == Command.EXIT) {
Components.login.showScreen();
}
}catch(Exception e) {
ErrorHandler.showError(e);
}
}
/**
* Updates screen and begins processing events to be
* downloaded/uploaded
*/
public void handle() throws Exception {
try {
showScreen();
new Thread(this).start();
}catch(Exception e) {
throw new GCalException(CommitComponent.class, "handle", e);
}
}
/**
* Entry point for new thread
*/
public void run() {
try {
/*phoneCalClient = new PhoneCalClient();
//update Google Calendar with any upload events
processUploadEvents();
//update phone with downloaded events
processDownloadEvents();
Store.getTimestamps().lastSync = System.currentTimeMillis();
Store.saveTimestamps();
*/
CommitEngine commitEngine = new CommitEngine();
//<int[]> is called from the CommitEngine class that processes the statistics
//to display on this screen
int[] commnitStatistics = commitEngine.commitSync(this.uploads, this.downloads, this.gCalClient, this.form);
this.form.append(new Spacer(getDisplayable().getWidth(), 20));
//creates the message that displays the results of commit events on the screen
//message displayed through the <code>update</code> method
update("GCal: " + gCalClient.createdCount + " new, " + gCalClient.updatedCount + " updated, " + gCalClient.removedCount + " removed events");
update("Phone: " + commnitStatistics[0] + " new, " + commnitStatistics[1] + " updated, " + commnitStatistics[2] + " removed events");
//phoneCalClient.close();
} catch (Exception e) {
ErrorHandler.showError(e.getMessage(), e);
}
}
/**
* Uploads events to Google Calendar
*/
/*void processUploadEvents() {
String gCalId;
try {
if (this.uploads != null && this.uploads.length > 0) {
//update("Uploading " + this.uploads.length + " event" + ((this.uploads.length > 1)?"s":"") + " to Google...");
gCalClient.setForm(this.form);
for (int i=0; i<this.uploads.length; i++) {
if(this.uploads[i].eventIsToBeUpdated) {
gCalClient.updateEvent(this.uploads[i]);
} else {
gCalId = gCalClient.createEvent(this.uploads[i]);
//update the phone event with the gCalId
if(this.uploads[i].uid == null) {
IdCorrelation idCorrelation = new IdCorrelation();
idCorrelation.phoneCalId = this.uploads[i].phoneCalId;
idCorrelation.gCalId = gCalId;
Store.addCorrelation(idCorrelation);
}
}
}
}
} catch (Exception e) {
update("Failed Google update: " + e);
//#ifdef DEBUG_ERR
//# System.err.println("Failed Google update: " + e);
//#endif
}
}*/
/**
* Saves events to phone calendar
*/
/* void processDownloadEvents() {
Options options;
Merger merger;
Hashtable phoneEventsByGcalId;
Enumeration phoneEvents;
Event phoneEvent;
String gcalId;
String startDate;
String endDate;
long now;
long startDateLong;
long endDateLong;
try {
if (this.downloads != null && this.downloads.length > 0) {
options = Store.getOptions();
now = System.currentTimeMillis();
startDate = DateUtil.longToIsoDate(now, 0 - options.pastDays);
endDate = DateUtil.longToIsoDate(now, options.futureDays);
startDateLong = DateUtil.isoDateToLong(startDate);
endDateLong = DateUtil.isoDateToLong(endDate) + DateUtil.DAY; // want all events starting before midnigth on endDate
phoneEvents = phoneCalClient.getPhoneEvents(startDateLong, endDateLong);
phoneEventsByGcalId = new Hashtable();
merger = new Merger(phoneCalClient, gCalClient);
//enumerate all GCal events in the phone's calendar
while (phoneEvents.hasMoreElements()) {
phoneEvent = (Event)phoneEvents.nextElement();
gcalId = phoneCalClient.getGCalId(phoneEvent);
if (gcalId != null) phoneEventsByGcalId.put(gcalId, phoneEvent);
}
for (int i=0; i<this.downloads.length; i++) {
//find the downloaded event in the phone's GCal event list.
//if the event doesn't exist, then <phoneEvent> is null and
//the event will be added to the phone's calendar
phoneEvent = (Event)phoneEventsByGcalId.remove(this.downloads[i].uid);
//update/add the downloaded event
merger.mergeEvents(phoneEvent, this.downloads[i], this.form);
}
}
} catch (Exception e) {e.printStackTrace();
update("Failed phone update: " + e);
//#ifdef DEBUG_ERR
//# System.err.println("Failed phone update: " + e);
//#endif
}
}*/
/**
* Sets the events to be uploaded/downloaded.
* This method copies array values from <GCalEvent[]> source arrays.
* The uploads and downloads arrays are called to the CommitEngine.java class
* by the <code>processUploadEvents</code> and the <code>processDownloadEvents</code> methods
* to write records to the Google Calendar or to the Device.
*
* @param uploads is the destination array for upload events -
* array values were copied from <GCalEvent[]> source array
* @param downloads is the destination array for download events -
* array values were copied from <GCalEvent[]> source array
*/
public void setEvents(GCalEvent[] uploads, GCalEvent[] downloads) throws Exception {
try {
if (uploads != null) {
this.uploads = new GCalEvent[uploads.length];
System.arraycopy(uploads, 0, this.uploads, 0, uploads.length);
}
if (downloads != null) {
this.downloads = new GCalEvent[downloads.length];
System.arraycopy(downloads, 0, this.downloads, 0, downloads.length);
}
}catch(Exception e) {
throw new GCalException("CommitComponent", "setEvents", e);
}
}
}
|
/*******************************************************************************
* # Copyright 2015 InfinitiesSoft Solutions 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.infinities.keystone4j.assignment.api.command.role;
import java.util.List;
import com.infinities.keystone4j.NonTruncatedCommand;
import com.infinities.keystone4j.assignment.AssignmentApi;
import com.infinities.keystone4j.assignment.AssignmentDriver;
import com.infinities.keystone4j.assignment.api.command.AbstractAssignmentCommand;
import com.infinities.keystone4j.contrib.revoke.RevokeApi;
import com.infinities.keystone4j.credential.CredentialApi;
import com.infinities.keystone4j.identity.IdentityApi;
import com.infinities.keystone4j.model.assignment.Assignment;
public class ListRoleAssignmentsCommand extends AbstractAssignmentCommand implements NonTruncatedCommand<List<Assignment>> {
public ListRoleAssignmentsCommand(CredentialApi credentialApi, IdentityApi identityApi, AssignmentApi assignmentApi,
RevokeApi revokeApi, AssignmentDriver assignmentDriver) {
super(credentialApi, identityApi, assignmentApi, revokeApi, assignmentDriver);
}
@Override
public List<Assignment> execute() {
List<Assignment> assignments = this.getAssignmentDriver().listRoleAssignments();
return assignments;
}
}
|
package com.blocklang.release.controller;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import org.springframework.beans.factory.annotation.Autowired;
import com.blocklang.core.constant.CmPropKey;
import com.blocklang.core.service.PropertyService;
import com.blocklang.develop.service.RepositoryPermissionService;
import com.blocklang.develop.service.RepositoryResourceService;
import com.blocklang.develop.service.RepositoryService;
import com.blocklang.release.service.ProjectReleaseTaskService;
// git 访问地址为: http[s]://ip[:port]/{owner}/{repo}/{project}/{appType}.git
@WebServlet(name = "gitServer", loadOnStartup = 1, urlPatterns = { "/git/*" }, initParams = {
@WebInitParam(name = "base-path", value = ""), @WebInitParam(name = "export-all", value = "true") })
public class GitServlet extends org.eclipse.jgit.http.server.GitServlet {
private static final long serialVersionUID = 7251262335792613657L;
@Autowired
private PropertyService propertyService;
@Autowired
private RepositoryService respositoryService;
@Autowired
private RepositoryResourceService repositoryResourceService;
@Autowired
private RepositoryPermissionService repositoryPermissionService;
@Autowired
private ProjectReleaseTaskService projectReleaseTaskService;
private String basePath;
@Override
public void init(ServletConfig config) throws ServletException {
basePath = propertyService.findStringValue(CmPropKey.BLOCKLANG_ROOT_PATH).get();
var resolver = new GitHttpResolver(basePath,
respositoryService,
repositoryPermissionService,
repositoryResourceService,
projectReleaseTaskService);
super.setRepositoryResolver(resolver);
super.init(config);
}
}
|
package dev.ferrand.chunky.octree;
import dev.ferrand.chunky.octree.implementations.*;
import dev.ferrand.chunky.octree.ui.OctreeTab;
import se.llbit.chunky.Plugin;
import se.llbit.chunky.main.Chunky;
import se.llbit.chunky.main.ChunkyOptions;
import se.llbit.chunky.ui.ChunkyFx;
import se.llbit.chunky.ui.render.RenderControlsTabTransformer;
public class OctreePlugin implements Plugin {
@Override
public void attach(Chunky chunky) {
RenderControlsTabTransformer previousTransformer = chunky.getRenderControlsTabTransformer();
chunky.setRenderControlsTabTransformer(tabs -> {
tabs = previousTransformer.apply(tabs);
tabs.add(new OctreeTab());
return tabs;
});
DiskOctree.initImplementation();
GcPackedOctree.initImplementation();
StatsOctree.initImplementation();
SmallLeafOctree.initImplementation();
DictionaryOctree.initImplementation();
SmallDAGTree.initImplementation();
}
public static void main(String[] args) {
// Start Chunky normally with this plugin attached.
Chunky.loadDefaultTextures();
Chunky chunky = new Chunky(ChunkyOptions.getDefaults());
new OctreePlugin().attach(chunky);
ChunkyFx.startChunkyUI(chunky);
}
}
|
/**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.kaazing.gateway.server.context.resolve;
import com.hazelcast.core.IMap;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.Key;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionInitializer;
import org.kaazing.gateway.resource.address.Protocol;
import org.kaazing.gateway.resource.address.ResourceAddress;
import org.kaazing.gateway.resource.address.ResourceAddressFactory;
import org.kaazing.gateway.resource.address.URLUtils;
import org.kaazing.gateway.security.AuthenticationContext;
import org.kaazing.gateway.security.CrossSiteConstraintContext;
import org.kaazing.gateway.security.RealmContext;
import org.kaazing.gateway.server.service.AbstractSessionInitializer;
import org.kaazing.gateway.service.AcceptOptionsContext;
import org.kaazing.gateway.service.ConnectOptionsContext;
import org.kaazing.gateway.service.Service;
import org.kaazing.gateway.service.ServiceContext;
import org.kaazing.gateway.service.ServiceProperties;
import org.kaazing.gateway.service.TransportOptionNames;
import org.kaazing.gateway.service.cluster.ClusterContext;
import org.kaazing.gateway.service.cluster.MemberId;
import org.kaazing.gateway.service.messaging.collections.CollectionsFactory;
import org.kaazing.gateway.transport.BridgeAcceptor;
import org.kaazing.gateway.transport.BridgeConnector;
import org.kaazing.gateway.transport.BridgeSessionInitializer;
import org.kaazing.gateway.transport.IoFilterAdapter;
import org.kaazing.gateway.transport.Transport;
import org.kaazing.gateway.transport.TransportFactory;
import org.kaazing.gateway.util.Encoding;
import org.kaazing.gateway.util.GL;
import org.kaazing.gateway.util.scheduler.SchedulerProvider;
import org.kaazing.mina.core.session.IoSessionEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static org.kaazing.gateway.resource.address.ResourceAddress.CONNECT_REQUIRES_INIT;
import static org.kaazing.gateway.resource.address.ResourceAddress.TRANSPORT;
import static org.kaazing.gateway.server.context.resolve.DefaultClusterContext.CLUSTER_LOGGER_NAME;
public class DefaultServiceContext implements ServiceContext {
public static final String BALANCER_MAP_NAME = "balancerMap";
public static final String MEMBERID_BALANCER_MAP_NAME = "memberIdBalancerMap";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final String[] EMPTY_REQUIRE_ROLES = new String[]{};
private static final String AUTHENTICATION_CONNECT = "authenticationConnect";
private static final String AUTHENTICATION_IDENTIFIER = "authenticationIdentifier";
private static final String BALANCE_ORIGINS = "balanceOrigins";
private static final String ENCRYPTION_KEY_ALIAS = "encryptionKeyAlias";
private static final String GATEWAY_ORIGIN_SECURITY = "gatewayHttpOriginSecurity";
private static final String LOGIN_CONTEXT_FACTORY = "loginContextFactory";
private static final String ORIGIN_SECURITY = "originSecurity";
private static final String REALM_AUTHENTICATION_COOKIE_NAMES = "realmAuthenticationCookieNames";
private static final String REALM_AUTHENTICATION_HEADER_NAMES = "realmAuthenticationHeaderNames";
private static final String REALM_AUTHENTICATION_PARAMETER_NAMES = "realmAuthenticationParameterNames";
private static final String REALM_AUTHORIZATION_MODE = "realmAuthorizationMode";
private static final String REALM_CHALLENGE_SCHEME = "realmChallengeScheme";
private static final String REALM_DESCRIPTION = "realmDescription";
private static final String REALM_NAME = "realmName";
private static final String REQUIRED_ROLES = "requiredRoles";
private static final String SERVICE_DOMAIN = "serviceDomain";
private static final String TEMP_DIRECTORY = "tempDirectory";
/**
* Prefix to the authentication scheme to indicate that the Kaazing client application will handle the challenge rather than
* delegate to the browser or the native platform.
*/
public static final String AUTH_SCHEME_APPLICATION_PREFIX = "Application ";
private final String serviceType;
private final String serviceName;
private final String serviceDescription;
private final Service service;
private final File tempDir;
private final File webDir;
private final Collection<URI> balances;
private final Collection<URI> accepts;
private final Collection<URI> connects;
private final ServiceProperties properties;
private final Map<String, String> mimeMappings;
private final Map<URI, ? extends Map<String, ? extends CrossSiteConstraintContext>> acceptConstraintsByURI;
private final TransportFactory transportFactory;
private List<Map<URI, Map<String, CrossSiteConstraintContext>>> authorityToSetOfAcceptConstraintsByURI;
private final String[] requireRoles;
private final Map<URI, ResourceAddress> bindings;
private final ConcurrentMap<Long, IoSessionEx> activeSessions;
private final Map<URI, IoHandler> bindHandlers;
private final ClusterContext clusterContext;
private final AcceptOptionsContext acceptOptionsContext;
private final ConnectOptionsContext connectOptionsContext;
private final RealmContext serviceRealmContext;
private final ResourceAddressFactory resourceAddressFactory;
private final Key encryptionKey;
private final Logger logger;
private final SchedulerProvider schedulerProvider;
private final boolean supportsAccepts;
private final boolean supportsConnects;
private final boolean supportsMimeMappings;
private final int processorCount;
private final AtomicBoolean started = new AtomicBoolean(false);
private final Map<String, Object> serviceSpecificObjects;
/**
* Default Session Initializer
*/
private IoSessionInitializer<ConnectFuture> sessionInitializer = new IoSessionInitializer<ConnectFuture>() {
@Override
public void initializeSession(IoSession session, ConnectFuture future) {
// FIXME: Do we need serviceContext and resource address passed in to be effective?
session.getFilterChain().addLast(SESSION_FILTER_NAME, new IoFilterAdapter<IoSessionEx>() {
@Override
protected void doSessionOpened(NextFilter nextFilter, IoSessionEx session) throws Exception {
addActiveSession(session);
super.doSessionOpened(nextFilter, session);
}
@Override
protected void doSessionClosed(NextFilter nextFilter, IoSessionEx session) throws Exception {
removeActiveSession(session);
super.doSessionClosed(nextFilter, session);
}
});
}
};
public DefaultServiceContext(String serviceType, Service service) {
this(serviceType,
null,
null,
service,
null,
null,
Collections.<URI>emptySet(),
Collections.<URI>emptySet(),
Collections.<URI>emptySet(),
new DefaultServiceProperties(),
EMPTY_REQUIRE_ROLES,
Collections.<String, String>emptyMap(),
Collections.<URI, Map<String, CrossSiteConstraintContext>>emptyMap(),
null,
new DefaultAcceptOptionsContext(),
new DefaultConnectOptionsContext(),
null,
null,
null,
true,
true,
false,
1,
TransportFactory.newTransportFactory(Collections.EMPTY_MAP),
ResourceAddressFactory.newResourceAddressFactory()
);
}
public DefaultServiceContext(String serviceType,
String serviceName,
String serviceDescription,
Service service,
File webDir,
File tempDir,
Collection<URI> balances,
Collection<URI> accepts,
Collection<URI> connects,
ServiceProperties properties,
String[] requireRoles,
Map<String, String> mimeMappings,
Map<URI, Map<String, CrossSiteConstraintContext>> crossSiteConstraints,
ClusterContext clusterContext,
AcceptOptionsContext acceptOptionsContext,
ConnectOptionsContext connectOptionsContext,
RealmContext serviceRealmContext,
Key encryptionKey,
SchedulerProvider schedulerProvider,
boolean supportsAccepts,
boolean supportsConnects,
boolean supportsMimeMappings,
int processorCount,
TransportFactory transportFactory,
ResourceAddressFactory resourceAddressFactory) {
this.serviceType = serviceType;
this.serviceName = serviceName;
this.serviceDescription = serviceDescription;
this.service = service;
this.webDir = webDir;
this.tempDir = tempDir;
this.balances = balances;
this.accepts = accepts;
this.connects = connects;
this.properties = properties;
this.requireRoles = requireRoles;
this.mimeMappings = mimeMappings;
this.acceptConstraintsByURI = crossSiteConstraints;
this.bindings = new HashMap<URI, ResourceAddress>();
this.activeSessions = new ConcurrentHashMap<Long, IoSessionEx>();
this.bindHandlers = new HashMap<URI, IoHandler>(4);
this.clusterContext = clusterContext;
this.acceptOptionsContext = acceptOptionsContext;
this.serviceRealmContext = serviceRealmContext;
this.connectOptionsContext = connectOptionsContext;
this.encryptionKey = encryptionKey;
this.logger = LoggerFactory.getLogger("service." + serviceType.replace("$", "_"));
this.schedulerProvider = schedulerProvider;
this.supportsAccepts = supportsAccepts;
this.supportsConnects = supportsConnects;
this.supportsMimeMappings = supportsMimeMappings;
this.processorCount = processorCount;
this.transportFactory = transportFactory;
this.resourceAddressFactory = resourceAddressFactory;
this.serviceSpecificObjects = new HashMap<>();
}
@Override
public boolean equals(Object otherObject) {
if (otherObject instanceof ServiceContext) {
ServiceContext otherServiceContext = (ServiceContext) otherObject;
if (this.serviceType.equals(otherServiceContext.getServiceType())) {
Collection<URI> otherAccepts = otherServiceContext.getAccepts();
for (URI uri : this.accepts) {
if (!otherAccepts.contains(uri)) {
return false;
}
}
// same type, same accepts, return true
return true;
}
}
return false;
}
@Override
public int hashCode() {
int result = serviceType != null ? serviceType.hashCode() : 0;
result = 31 * result + (accepts != null ? accepts.hashCode() : 0);
return result;
}
@Override
public int getProcessorCount() {
return processorCount;
}
@Override
public RealmContext getServiceRealm() {
return serviceRealmContext;
}
@Override
public String getAuthorizationMode() {
if (serviceRealmContext != null &&
serviceRealmContext.getAuthenticationContext() != null) {
return serviceRealmContext.getAuthenticationContext().getAuthorizationMode();
}
return null;
}
@Override
public String getSessionTimeout() {
if (serviceRealmContext != null &&
serviceRealmContext.getAuthenticationContext() != null) {
return serviceRealmContext.getAuthenticationContext().getSessionTimeout();
}
return null;
}
@Override
public String decrypt(String encrypted) throws Exception {
ByteBuffer decoded = Encoding.BASE64.decode(ByteBuffer.wrap(encrypted.getBytes(UTF_8)));
InputStream bin = IoBuffer.wrap(decoded).asInputStream();
Cipher cipher = Cipher.getInstance(encryptionKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, encryptionKey);
DataInputStream in = new DataInputStream(new CipherInputStream(bin, cipher));
try {
return in.readUTF();
} catch (Exception e) {
return "";
}
}
@Override
public String encrypt(String plaintext) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Cipher cipher = Cipher.getInstance(encryptionKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
DataOutputStream out = new DataOutputStream(new CipherOutputStream(bos, cipher));
out.writeUTF(plaintext);
out.close();
ByteBuffer encoded = Encoding.BASE64.encode(ByteBuffer.wrap(bos.toByteArray(), 0, bos.size()));
return IoBuffer.wrap(encoded).getString(UTF_8.newDecoder());
}
@Override
public AcceptOptionsContext getAcceptOptionsContext() {
return acceptOptionsContext;
}
@Override
public ConnectOptionsContext getConnectOptionsContext() {
return connectOptionsContext;
}
public String getServiceType() {
return serviceType;
}
public String getServiceName() {
return serviceName;
}
public String getServiceDescription() {
return serviceDescription;
}
@Override
public Collection<URI> getAccepts() {
return accepts;
}
@Override
public Collection<URI> getBalances() {
return balances;
}
@Override
public Collection<URI> getConnects() {
return connects;
}
@Override
public Service getService() {
return service;
}
@Override
public ServiceProperties getProperties() {
return properties;
}
@Override
public String[] getRequireRoles() {
return requireRoles;
}
@Override
public Map<String, String> getMimeMappings() {
return mimeMappings;
}
@Override
public String getContentType(String fileExtension) {
String contentType = fileExtension == null ? null : mimeMappings.get(fileExtension.toLowerCase());
return contentType;
}
@Override
public Map<URI, ? extends Map<String, ? extends CrossSiteConstraintContext>> getCrossSiteConstraints() {
return acceptConstraintsByURI;
}
@Override
public File getTempDirectory() {
return tempDir;
}
@Override
public File getWebDirectory() {
return webDir;
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public SchedulerProvider getSchedulerProvider() {
return schedulerProvider;
}
@Override
public void bind(Collection<URI> bindURIs, IoHandler handler) {
bind(bindURIs, handler, acceptOptionsContext);
}
@Override
public void bind(Collection<URI> bindURIs, IoHandler handler, AcceptOptionsContext acceptOptionsContext) {
bind(bindURIs, handler, acceptOptionsContext, null);
}
@Override
public void bind(Collection<URI> bindURIs, IoHandler handler, BridgeSessionInitializer<ConnectFuture>
bridgeSessionInitializer) {
bind(bindURIs, handler, acceptOptionsContext, bridgeSessionInitializer);
}
@Override
public void bindConnectsIfNecessary(Collection<URI> connectURIs) {
for (URI connectURI : connectURIs) {
// TODO: services should bind ResourceAddress directly, rather than passing URIs here
Map<String, Object> connectOptions = buildResourceAddressOptions(connectURI, connectOptionsContext);
ResourceAddress connectAddress = resourceAddressFactory.newResourceAddress(connectURI, connectOptions);
bindConnectIfNecessary(connectAddress);
}
}
@Override
public void unbindConnectsIfNecessary(Collection<URI> connectURIs) {
for (URI connectURI : connectURIs) {
// TODO: services should bind ResourceAddress directly, rather than passing URIs here
Map<String, Object> connectOptions = buildResourceAddressOptions(connectURI, connectOptionsContext);
ResourceAddress connectAddress = resourceAddressFactory.newResourceAddress(connectURI, connectOptions);
unbindConnectIfNecessary(connectAddress);
}
}
private void bindConnectIfNecessary(ResourceAddress connectAddress) {
if (connectAddress.getOption(CONNECT_REQUIRES_INIT)) {
final URI transportURI = connectAddress.getResource();
final String transportSchemeName = transportURI.getScheme();
Transport transport = transportFactory.getTransportForScheme(transportSchemeName);
assert transport != null;
transport.getConnector(connectAddress).connectInit(connectAddress);
} else {
ResourceAddress connectTransport = connectAddress.getOption(TRANSPORT);
if (connectTransport != null) {
bindConnectIfNecessary(connectTransport);
}
}
}
private void unbindConnectIfNecessary(ResourceAddress connectAddress) {
if (connectAddress.getOption(CONNECT_REQUIRES_INIT)) {
final URI transportURI = connectAddress.getResource();
final String transportSchemeName = transportURI.getScheme();
Transport transport = transportFactory.getTransportForScheme(transportSchemeName);
assert transport != null;
transport.getConnector(connectAddress).connectDestroy(connectAddress);
} else {
ResourceAddress connectTransport = connectAddress.getOption(TRANSPORT);
if (connectTransport != null) {
unbindConnectIfNecessary(connectTransport);
}
}
}
@Override
public void bind(Collection<URI> bindURIs,
IoHandler handler,
AcceptOptionsContext acceptOptionsContext,
final BridgeSessionInitializer<ConnectFuture> bridgeSessionInitializer) {
if (handler == null) {
throw new IllegalArgumentException("Cannot bind without handler");
}
for (URI uri : bindURIs) {
bindHandlers.put(uri, handler);
}
Map<Transport, List<URI>> bindsByTransport = getURIsByTransport(bindURIs);
// for each transport group, create resource address for URIs and bind to transport.
for (Entry<Transport, List<URI>> entry : bindsByTransport.entrySet()) {
Transport transport = entry.getKey();
List<URI> transportAccepts = entry.getValue();
for (URI transportAccept : transportAccepts) {
Map<String, Object> options = buildResourceAddressOptions(transportAccept, acceptOptionsContext);
ResourceAddress address = resourceAddressFactory.newResourceAddress(transportAccept, options);
bindInternal(address, handler, transport, sessionInitializer, bridgeSessionInitializer);
bindings.put(transportAccept, address);
}
}
//
// After the service has been physically bound, update the cluster state to reflect this service as a possible
// balance target.
//
if (balances != null && balances.size() > 0) {
if (!accepts.containsAll(bindURIs)) {
// if this bind() call is for URIs that aren't the service accept URIs (typically just the broadcast service's
// accept property) then don't update balancer state. Only service accept URIs are balance targets.
return;
}
CollectionsFactory factory = clusterContext.getCollectionsFactory();
if (factory != null) {
Map<MemberId, Map<URI, List<URI>>> memberIdBalancerUriMap = factory.getMap(MEMBERID_BALANCER_MAP_NAME);
if (memberIdBalancerUriMap == null) {
throw new IllegalStateException("MemberId to BalancerMap is null");
}
MemberId localMember = clusterContext.getLocalMember();
Map<URI, List<URI>> memberBalanceUriMap = memberIdBalancerUriMap.get(localMember);
if (memberBalanceUriMap == null) {
memberBalanceUriMap = new HashMap<URI, List<URI>>();
}
List<URI> acceptUris = new ArrayList<URI>();
if (accepts != null) {
acceptUris.addAll(accepts);
}
IMap<URI, Set<URI>> sharedBalanceUriMap = factory.getMap(BALANCER_MAP_NAME);
for (URI balanceURI : balances) {
if (accepts != null) {
memberBalanceUriMap.put(balanceURI, acceptUris);
// get and add to the list here instead of overwriting it
Set<URI> balanceUris = null;
Set<URI> newBalanceUris = null;
do {
balanceUris = sharedBalanceUriMap.get(balanceURI);
if (balanceUris == null) {
newBalanceUris = new HashSet<URI>();
newBalanceUris.addAll(accepts);
balanceUris = sharedBalanceUriMap.putIfAbsent(balanceURI, newBalanceUris);
if (balanceUris == null) {
break;
}
}
newBalanceUris = new HashSet<URI>(balanceUris);
newBalanceUris.addAll(accepts);
if (newBalanceUris.equals(balanceUris)) {
break;
}
} while (!sharedBalanceUriMap.replace(balanceURI, balanceUris, newBalanceUris));
GL.info(CLUSTER_LOGGER_NAME, "Cluster member {}: service {} bound", localMember, serviceType);
GL.debug(CLUSTER_LOGGER_NAME, "Added balance URIs {}, new global list is {}",
acceptUris, newBalanceUris);
}
}
memberIdBalancerUriMap.put(localMember, memberBalanceUriMap);
}
}
}
private Map<String, Object> buildResourceAddressOptions(URI transportURI, AcceptOptionsContext acceptOptionsContext) {
// options is a new HashMap
final Map<String, Object> options = acceptOptionsContext.asOptionsMap();
injectServiceOptions(transportURI, options);
// TODO: Instead of null, perhaps ServiceContext provides a
// set of next protocol possibilities that are bound individually.
options.put(TransportOptionNames.NEXT_PROTOCOL, null);
return options;
}
private Map<String, Object> buildResourceAddressOptions(URI transportURI, ConnectOptionsContext connectOptionsContext) {
// options is a new HashMap
final Map<String, Object> options = connectOptionsContext.asOptionsMap();
injectServiceOptions(transportURI, options);
// TODO: Instead of null, perhaps ServiceContext provides a
// set of next protocol possibilities that are bound individually.
options.put(TransportOptionNames.NEXT_PROTOCOL, null);
return options;
}
private void injectServiceOptions(URI transportURI, Map<String, Object> options) {
Map<String, ? extends CrossSiteConstraintContext> acceptConstraints = acceptConstraintsByURI.get(transportURI);
if (acceptConstraints == null && "balancer".equals(serviceType)) {
if (transportURI.getPath() != null && transportURI.getPath().endsWith("/;e")) {
transportURI = transportURI
.resolve(transportURI.getPath().substring(0, transportURI.getPath().length() - "/;e".length()));
}
acceptConstraints = acceptConstraintsByURI.get(URLUtils.modifyURIScheme(transportURI, "ws"));
if (acceptConstraints == null && transportFactory.getProtocol(transportURI).isSecure()) {
acceptConstraints = acceptConstraintsByURI.get(URLUtils.modifyURIScheme(transportURI, "wss"));
}
}
if (acceptConstraints != null) {
// needed by cross origin bridge filter to cache resources
options.put(format("http[http/1.1].%s", ORIGIN_SECURITY), acceptConstraints);
options.put(format("http[x-kaazing-handshake].%s", ORIGIN_SECURITY), acceptConstraints);
options.put(format("http[httpxe/1.1].%s", ORIGIN_SECURITY), acceptConstraints);
options.put(format("http[httpxe/1.1].http[http/1.1].%s", ORIGIN_SECURITY), acceptConstraints);
}
// needed for silverlight
options.put(format("http[http/1.1].%s", GATEWAY_ORIGIN_SECURITY), authorityToSetOfAcceptConstraintsByURI);
options.put(format("http[x-kaazing-handshake].%s", GATEWAY_ORIGIN_SECURITY), authorityToSetOfAcceptConstraintsByURI);
options.put(format("http[httpxe/1.1].%s", GATEWAY_ORIGIN_SECURITY), authorityToSetOfAcceptConstraintsByURI);
options.put(format("http[httpxe/1.1].http[http/1.1].%s", GATEWAY_ORIGIN_SECURITY),
authorityToSetOfAcceptConstraintsByURI);
//needed for correct enforcement of same origin in clustered gateway scenarios (KG-9686)
final Collection<URI> balanceOriginUris = toHttpBalanceOriginURIs(getBalances());
if (balanceOriginUris != null) {
options.put(format("http[http/1.1].%s", BALANCE_ORIGINS), balanceOriginUris);
options.put(format("http[x-kaazing-handshake].%s", BALANCE_ORIGINS), balanceOriginUris);
options.put(format("http[httpxe/1.1].%s", BALANCE_ORIGINS), balanceOriginUris);
options.put(format("http[httpxe/1.1].http[http/1.1].%s", BALANCE_ORIGINS), balanceOriginUris);
}
// needed by resources handler to serve (cached) resources
// TODO: convert to HTTP cache concept and drop in as a filter instead?
options.put(format("http[http/1.1].%s", TEMP_DIRECTORY), tempDir);
// We only need this option for KG-3476: silently convert a directory
// service configured with application- challenge scheme to a non-application scheme.
boolean forceNativeChallengeScheme = "directory".equals(getServiceType());
// Add realmName property and based on whether the service
// is protected, and whether it is application- or native- security that is desired.
if (serviceRealmContext != null) {
final AuthenticationContext authenticationContext = serviceRealmContext.getAuthenticationContext();
if (authenticationContext != null) {
String challengeScheme = authenticationContext.getHttpChallengeScheme();
boolean isApplicationChallengeScheme = challengeScheme.startsWith(AUTH_SCHEME_APPLICATION_PREFIX);
if (isApplicationChallengeScheme && !forceNativeChallengeScheme) {
options.put(format("http[http/1.1].%s", REALM_CHALLENGE_SCHEME),
authenticationContext.getHttpChallengeScheme());
for (String optionPattern : asList("http[httpxe/1.1].%s", "http[x-kaazing-handshake].%s")) {
options.put(format(optionPattern, REALM_NAME),
serviceRealmContext.getName());
options.put(format(optionPattern, REQUIRED_ROLES),
getRequireRoles());
options.put(format(optionPattern, REALM_AUTHORIZATION_MODE),
authenticationContext.getAuthorizationMode());
options.put(format(optionPattern, REALM_CHALLENGE_SCHEME),
authenticationContext.getHttpChallengeScheme());
options.put(format(optionPattern, REALM_DESCRIPTION),
serviceRealmContext.getDescription());
options.put(format(optionPattern, REALM_AUTHENTICATION_HEADER_NAMES),
authenticationContext.getHttpHeaders());
options.put(format(optionPattern, REALM_AUTHENTICATION_PARAMETER_NAMES),
authenticationContext.getHttpQueryParameters());
options.put(format(optionPattern, REALM_AUTHENTICATION_COOKIE_NAMES),
authenticationContext.getHttpCookieNames());
options.put(format(optionPattern, LOGIN_CONTEXT_FACTORY),
serviceRealmContext.getLoginContextFactory());
// We need this to support reading legacy service properties during authentication.
// authentication-connect, authentication-identifier, encryption.key.alias, service.domain
// The negotiate properties are replaced with client-side capabilities to use different
// KDCs on a per-realm basis. The ksessionid cookie properties are needed to write the cookie
// out if needed (recycle authorization mode).
options.put(format(optionPattern, AUTHENTICATION_CONNECT),
getProperties().get("authentication.connect"));
options.put(format(optionPattern, AUTHENTICATION_IDENTIFIER),
getProperties().get("authentication.identifier"));
options.put(format(optionPattern, ENCRYPTION_KEY_ALIAS),
getProperties().get("encryption.key.alias"));
options.put(format(optionPattern, SERVICE_DOMAIN),
getProperties().get("service.domain"));
}
}
// TODO: eliminate forceNativeChallengeScheme by locking down authentication schemes for "directory" service
if (!isApplicationChallengeScheme || forceNativeChallengeScheme) {
String optionPattern = "http[http/1.1].%s";
options.put(format(optionPattern, REALM_NAME),
serviceRealmContext.getName());
options.put(format(optionPattern, REQUIRED_ROLES),
getRequireRoles());
options.put(format(optionPattern, REALM_AUTHORIZATION_MODE),
authenticationContext.getAuthorizationMode());
options.put(format(optionPattern, REALM_CHALLENGE_SCHEME),
authenticationContext.getHttpChallengeScheme());
options.put(format(optionPattern, REALM_DESCRIPTION),
serviceRealmContext.getDescription());
options.put(format(optionPattern, REALM_AUTHENTICATION_HEADER_NAMES),
authenticationContext.getHttpHeaders());
options.put(format(optionPattern, REALM_AUTHENTICATION_PARAMETER_NAMES),
authenticationContext.getHttpQueryParameters());
options.put(format(optionPattern, REALM_AUTHENTICATION_COOKIE_NAMES),
authenticationContext.getHttpCookieNames());
options.put(format(optionPattern, LOGIN_CONTEXT_FACTORY),
serviceRealmContext.getLoginContextFactory());
// see note above for why this is needed
options.put(format(optionPattern, AUTHENTICATION_CONNECT),
getProperties().get("authentication.connect"));
options.put(format(optionPattern, AUTHENTICATION_IDENTIFIER),
getProperties().get("authentication.identifier"));
options.put(format(optionPattern, ENCRYPTION_KEY_ALIAS),
getProperties().get("encryption.key.alias"));
options.put(format(optionPattern, SERVICE_DOMAIN),
getProperties().get("service.domain"));
}
}
}
}
private Collection<URI> toHttpBalanceOriginURIs(Collection<URI> balances) {
if (balances == null || balances.isEmpty()) {
return balances;
}
List<URI> result = new ArrayList<URI>(balances.size());
for (URI uri : balances) {
if (uri != null) {
try {
final String scheme = uri.getScheme();
if ("ws".equals(scheme)) {
result.add(new URI("http", uri.getAuthority(), uri.getPath(), uri.getQuery(), uri.getFragment()));
} else if ("wss".equals(scheme)) {
result.add(new URI("https", uri.getAuthority(), uri.getPath(), uri.getQuery(), uri.getFragment()));
} else {
result.add(uri);
}
} catch (URISyntaxException e) {
if (logger.isDebugEnabled()) {
logger.warn(String.format("Cannot translate balanc uri '%s' into a http balance origin.", uri));
}
}
}
}
return result;
}
private void bindInternal(final ResourceAddress address,
final IoHandler handler,
final Transport transport,
final IoSessionInitializer<ConnectFuture> sessionInitializer,
final BridgeSessionInitializer<ConnectFuture> bridgeSessionInitializer) {
BridgeAcceptor acceptor = transport.getAcceptor(address);
try {
acceptor.bind(address, handler, new BridgeSessionInitializer<ConnectFuture>() {
@Override
public BridgeSessionInitializer<ConnectFuture> getParentInitializer(Protocol protocol) {
return (bridgeSessionInitializer != null) ? bridgeSessionInitializer.getParentInitializer(protocol) : null;
}
@Override
public void initializeSession(IoSession session, ConnectFuture future) {
sessionInitializer.initializeSession(session, future);
if (bridgeSessionInitializer != null) {
bridgeSessionInitializer.initializeSession(session, future);
}
}
});
} catch (RuntimeException re) {
// Catch this RuntimeException and add a bit more information
// to its message (cf KG-1462)
throw new RuntimeException(String.format("Error binding to %s: %s", address.getResource(), re.getMessage()), re);
}
}
/**
* Return the URIs organized by transport.
* <p/>
* NOTE: because this relies on gatewayContext, we cannot call it until after the service context has been completely set up
* (and in fact not until GatewayContextResolver has constructed, as it doesn't create the DefaultGatewayContext until the
* last step in construction.
*
* @param uris
* @return
*/
private Map<Transport, List<URI>> getURIsByTransport(Collection<URI> uris) {
Map<Transport, List<URI>> urisByTransport = new HashMap<Transport, List<URI>>();
// iterate over URIs and group them by transport
for (URI uri : uris) {
String uriScheme = uri.getScheme();
Transport transport = transportFactory.getTransportForScheme(uriScheme);
List<URI> list = urisByTransport.get(transport);
if (list == null) {
list = new ArrayList<URI>();
urisByTransport.put(transport, list);
}
list.add(uri);
}
return urisByTransport;
}
@Override
public void unbind(Collection<URI> bindURIs, IoHandler handler) {
if (handler == null) {
throw new IllegalArgumentException("Cannot unbind without handler");
} else {
for (URI uri : bindURIs) {
IoHandler bindHandler = bindHandlers.get(uri);
if (bindHandler != null) {
if (!handler.equals(bindHandler)) {
throw new IllegalArgumentException("Cannot unbind with a handler " + handler
+ " different from the one used for binding " + bindHandler + " to URI " + uri);
}
bindHandlers.remove(uri);
}
}
}
//
// If there are balance URIs on the service, update the cluster state before physically unbinding
// so that this cluster member is removed from the balance targets first. This avoids a race
// condition where a new connection comes in *after* this cluster member has been unbound but
// before the cluster state has been updated, resulting in this cluster member being incorrectly
// picked as the balancee.
//
if (balances != null && balances.size() > 0) {
CollectionsFactory factory = clusterContext.getCollectionsFactory();
if (factory != null) {
Map<MemberId, Map<URI, List<URI>>> memberIdBalancerUriMap = factory
.getMap(MEMBERID_BALANCER_MAP_NAME);
if (memberIdBalancerUriMap == null) {
throw new IllegalStateException("MemberId to BalancerMap is null");
}
MemberId localMember = clusterContext.getLocalMember();
Map<URI, List<URI>> memberBalanceUriMap = memberIdBalancerUriMap.get(localMember);
if (memberBalanceUriMap == null) {
throw new IllegalStateException("Member balancerMap is null for member " + localMember);
}
IMap<URI, Set<URI>> sharedBalanceUriMap = factory.getMap(BALANCER_MAP_NAME);
for (URI balanceURI : balances) {
if (accepts != null) {
memberBalanceUriMap.remove(balanceURI);
// get and add to the list here instead of overwriting it
Set<URI> balanceUris = null;
Set<URI> newBalanceUris = null;
do {
boolean didRemove = false;
balanceUris = sharedBalanceUriMap.get(balanceURI);
if (balanceUris != null) {
newBalanceUris = new HashSet<URI>(balanceUris);
for (URI acceptUri : accepts) {
didRemove = didRemove || newBalanceUris.remove(acceptUri);
}
}
if (!didRemove) {
// the current balancer entries were already removed, so since no work
// was done just skip the attempt to update cluster memory
break;
}
if (newBalanceUris.isEmpty()) {
if (sharedBalanceUriMap.remove(balanceURI, balanceUris)) {
break;
} else {
continue; // start over to refresh the newBalanceUris
}
}
} while (!sharedBalanceUriMap.replace(balanceURI, balanceUris, newBalanceUris));
GL.info(CLUSTER_LOGGER_NAME, "Cluster member {}: service {} unbound", localMember, serviceType);
GL.debug(CLUSTER_LOGGER_NAME, "Removed balance URIs {}, new global list is {}", accepts, newBalanceUris);
}
}
memberIdBalancerUriMap.put(localMember, memberBalanceUriMap);
}
}
for (URI uri : bindURIs) {
String uriScheme = uri.getScheme();
Transport transport = transportFactory.getTransportForScheme(uriScheme);
ResourceAddress address = bindings.remove(uri);
if (address != null) {
transport.getAcceptor(address).unbind(address);
}
}
}
@Override
public ConnectFuture connect(URI connectURI, final IoHandler connectHandler,
final IoSessionInitializer<ConnectFuture> connectSessionInitializer) {
String uriScheme = connectURI.getScheme();
Transport transport = transportFactory.getTransportForScheme(uriScheme);
ResourceAddress address = resourceAddressFactory.newResourceAddress(connectURI, connectOptionsContext.asOptionsMap());
BridgeConnector connector = transport.getConnector(address);
return connector.connect(address, connectHandler, new IoSessionInitializer<ConnectFuture>() {
@Override
public void initializeSession(IoSession session, ConnectFuture future) {
sessionInitializer.initializeSession(session, future);
if (connectSessionInitializer != null) {
connectSessionInitializer.initializeSession(session, future);
}
}
});
}
@Override
public Collection<IoSessionEx> getActiveSessions() {
return activeSessions.values();
}
@Override
public IoSessionEx getActiveSession(Long sessionId) {
if (sessionId == null) {
return null;
}
return activeSessions.get(sessionId);
}
@Override
public void addActiveSession(IoSessionEx session) {
activeSessions.put(session.getId(), session);
}
@Override
public void removeActiveSession(IoSessionEx session) {
activeSessions.remove(session.getId());
}
/**
* Session initializer for the 'standard' case.
*/
public final class StandardSessionInitializer extends AbstractSessionInitializer {
@Override
public void initializeSession(IoSession session, ConnectFuture future) {
super.initializeSession(session, future);
session.getFilterChain().addLast(SESSION_FILTER_NAME, new ServiceSessionFilter());
}
}
public class ServiceSessionFilter extends IoFilterAdapter<IoSessionEx> {
@Override
protected void doSessionOpened(NextFilter nextFilter, IoSessionEx session) throws Exception {
activeSessions.put(session.getId(), session);
super.doSessionOpened(nextFilter, session);
}
@Override
protected void doSessionClosed(NextFilter nextFilter, IoSessionEx session) throws Exception {
activeSessions.remove(session.getId());
super.doSessionClosed(nextFilter, session);
}
}
@Override
public void init() throws Exception {
getService().init(this);
}
@Override
public void start() throws Exception {
if (started.compareAndSet(false, true)) {
getService().start();
}
}
@Override
public void stop() throws Exception {
if (started.compareAndSet(true, false)) {
// So management won't get screwed up, don't allow the service
// to add any more sessions than there already are.
service.quiesce();
service.stop();
}
}
@Override
public void destroy() throws Exception {
getService().destroy();
}
@Override
public boolean supportsAccepts() {
return this.supportsAccepts;
}
@Override
public boolean supportsConnects() {
return this.supportsConnects;
}
@Override
public boolean supportsMimeMappings() {
return this.supportsMimeMappings;
}
@Override
public void setListsOfAcceptConstraintsByURI(List<Map<URI, Map<String, CrossSiteConstraintContext>>>
authorityToSetOfAcceptConstraintsByURI) {
this.authorityToSetOfAcceptConstraintsByURI = authorityToSetOfAcceptConstraintsByURI;
}
@Override
public Map<String, Object> getServiceSpecificObjects() {
return serviceSpecificObjects;
}
@Override
public IoSessionInitializer<ConnectFuture> getSessionInitializor() {
return sessionInitializer;
}
@Override
public void setSessionInitializor(IoSessionInitializer<ConnectFuture> ioSessionInitializer) {
this.sessionInitializer = ioSessionInitializer;
}
}
|
package com.zendesk.maxwell.schema.columndef;
import java.sql.Timestamp;
import com.google.code.or.common.util.MySQLConstants;
public class DateTimeColumnDef extends ColumnDefWithLength {
public DateTimeColumnDef(String name, String type, int pos, Long columnLength) {
super(name, type, pos, columnLength);
}
@Override
public boolean matchesMysqlType(int type) {
if ( getType().equals("datetime") ) {
return type == MySQLConstants.TYPE_DATETIME ||
type == MySQLConstants.TYPE_DATETIME2;
} else {
return type == MySQLConstants.TYPE_TIMESTAMP ||
type == MySQLConstants.TYPE_TIMESTAMP2;
}
}
protected String formatValue(Object value) {
Timestamp ts = DateFormatter.extractTimestamp(value);
String dateString = DateFormatter.formatDateTime(value);
if ( dateString == null )
return null;
else
return appendFractionalSeconds(dateString, ts.getNanos(), columnLength);
}
}
|
package com.opitzconsulting.orcas.diff;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.emf.ecore.EObject;
import org.junit.Assume;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Parameterized.UseParametersRunnerFactory;
import de.opitzconsulting.orcas.diff.BaseMultiSchemaConnectionManager;
import de.opitzconsulting.orcas.diff.OrcasDiff.DiffResult;
import de.opitzconsulting.orcas.diff.OrcasExtractStatics;
import de.opitzconsulting.orcas.diff.OrcasMain;
import de.opitzconsulting.orcas.diff.OrcasScriptRunner;
import de.opitzconsulting.orcas.diff.ParameterDefaults;
import de.opitzconsulting.orcas.diff.Parameters.AdditionalExtensionFactory;
import de.opitzconsulting.orcas.diff.Parameters.FailOnErrorMode;
import de.opitzconsulting.orcas.diff.Parameters.JdbcConnectParameters;
import de.opitzconsulting.orcas.diff.ParametersCall;
import de.opitzconsulting.orcas.diff.XmlLogFileHandler;
import de.opitzconsulting.orcasDsl.Model;
@RunWith(OrcasCoreIntegrationTest.MyOrcasParameterizedParallel.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@UseParametersRunnerFactory(OrcasParameterizedParallel.OrcasParametersRunnerFactory.class)
public class OrcasCoreIntegrationTest {
public static class MyOrcasParameterizedParallel extends OrcasParameterizedParallel {
public MyOrcasParameterizedParallel(Class<?> pKlass) throws Throwable {
super(pKlass);
}
@Override
public void assumeShouldExecuteTestcase(String pTestName) {
new TestSetup(pTestName).assumeShouldExecuteTestcase();
}
}
private static OrcasCoreIntegrationConfig orcasCoreIntegrationConfig = OrcasCoreIntegrationConfigSystemProperties.getOrcasCoreIntegrationConfig();
private static final String EXTRACT_FOLDER_NAME = "00_extract";
private static final String REFERENCE_NAME = "00_schema";
static final String DEFAULT_EXCLUDE = "object_name like '%$%'";
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
List<Object[]> lReturn = new ArrayList<Object[]>();
for (File lFile : new File(orcasCoreIntegrationConfig.getBaseDir() + "tests").listFiles()) {
String lTestName = lFile.getName();
if (lTestName.startsWith("test_")) {
if (lTestName.matches(orcasCoreIntegrationConfig.getExecuteTests())) {
lReturn.add(new Object[] { lTestName });
}
}
}
return lReturn;
}
@Parameter
public String testName;
private TestSetup _testSetup;
private String _lognameFirstRun = "01_statics";
private static final Map<String, Map<String, JdbcConnectParameters>> _connectParametersTargetUserMap = new HashMap<>();
private static List<String> parseReaderToLines(File pFile) {
try {
BufferedReader lBufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(pFile), StandardCharsets.UTF_8));
List<String> lLines = new ArrayList<String>();
String lFileLine;
while ((lFileLine = lBufferedReader.readLine()) != null) {
lLines.add(lFileLine);
}
lBufferedReader.close();
return lLines;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void deleteRecursive(File pFile) {
if (pFile.isDirectory()) {
for (String lFile : pFile.list()) {
deleteRecursive(new File(pFile, lFile));
}
}
pFile.delete();
}
interface MultiSchemaSetup {
String getFilePostfix();
default String getSchemaName() {
return getJdbcConnectParameters().getJdbcUser();
}
String getSchemaAlias();
String[] getParameters(String... pOtherParameters);
JdbcConnectParameters getJdbcConnectParameters();
}
private static class TestSetup {
private final boolean _testWithData;
private String testName;
private boolean _dropmode;
private boolean _indexparallelcreate;
private boolean _createmissingfkindexes;
private boolean _test_extract;
private boolean _tablemovetablespace;
private boolean _indexmovetablespace;
private String _extensionfolder;
private String _required_feature_list;
private String _dateformat;
private String relevantFiles;
private String _excludewheresequence;
private boolean _customExtensionFolder;
private boolean _availableFeatureRequirementMatched = true;
private boolean _additionsOnly;
private boolean _columnsSetUnused;
private boolean _indexonlinecreation;
private String _expectfailure;
public boolean _minimizeStatementCount;
public List<String> _schemaNames;
boolean isMultiSchema() {
return _schemaNames.size() > 1;
}
private void runMultiSchemaSetupWithDbaSetup(Consumer<MultiSchemaSetup> pMultiSchemaSetupConsumer) {
internalRunMultiSchemaSetup(pMultiSchemaSetupConsumer, true);
}
public void runMultiSchemaSetup(Consumer<MultiSchemaSetup> pMultiSchemaSetupConsumer) {
internalRunMultiSchemaSetup(pMultiSchemaSetupConsumer, false);
}
public void internalRunMultiSchemaSetup(Consumer<MultiSchemaSetup> pMultiSchemaSetupConsumer, boolean pWithDbaSetup) {
if (!isMultiSchema()) {
pMultiSchemaSetupConsumer.accept(new MultiSchemaSetup() {
@Override
public String getFilePostfix() {
return "";
}
@Override
public String getSchemaAlias() {
return _schemaNames.get(0);
}
@Override
public String[] getParameters(String... pOtherParameters) {
return pOtherParameters;
}
@Override
public JdbcConnectParameters getJdbcConnectParameters() {
synchronized (_connectParametersTargetUserMap) {
return _connectParametersTargetUserMap.get(testName).get(_schemaNames.get(0));
}
}
});
} else {
if (pWithDbaSetup) {
pMultiSchemaSetupConsumer.accept(new MultiSchemaSetup() {
@Override
public String getFilePostfix() {
return "";
}
@Override
public String getSchemaAlias() {
throw new UnsupportedOperationException();
}
@Override
public String[] getParameters(String... pOtherParameters) {
String[] lReturn = new String[_schemaNames.size() + pOtherParameters.length];
synchronized (_connectParametersTargetUserMap) {
for (int i = 0; i < _schemaNames.size(); i++) {
lReturn[i] = _connectParametersTargetUserMap.get(testName).get(_schemaNames.get(i)).getJdbcUser();
}
}
for (int i = 0; i < pOtherParameters.length; i++) {
lReturn[_schemaNames.size() + i] = pOtherParameters[i];
}
return lReturn;
}
@Override
public JdbcConnectParameters getJdbcConnectParameters() {
return OrcasParallelConnectionHandler._connectParametersDba;
}
});
}
_schemaNames.forEach(p -> {
pMultiSchemaSetupConsumer.accept(new MultiSchemaSetup() {
@Override
public String getFilePostfix() {
return "_" + p;
}
@Override
public String getSchemaAlias() {
return p;
}
@Override
public String[] getParameters(String... pOtherParameters) {
String[] lReturn = new String[_schemaNames.size() + pOtherParameters.length];
synchronized (_connectParametersTargetUserMap) {
for (int i = 0; i < _schemaNames.size(); i++) {
lReturn[i] = _connectParametersTargetUserMap.get(testName).get(_schemaNames.get(i)).getJdbcUser();
}
}
for (int i = 0; i < pOtherParameters.length; i++) {
lReturn[_schemaNames.size() + i] = pOtherParameters[i];
}
return lReturn;
}
@Override
public JdbcConnectParameters getJdbcConnectParameters() {
synchronized (_connectParametersTargetUserMap) {
return _connectParametersTargetUserMap.get(testName).get(p);
}
}
});
});
}
}
public boolean isMviewsWithColumns() {
return _mviewsWithColumns;
}
public boolean _mviewsWithColumns;
private boolean _cleanupfkvaluesondropmode;
public TestSetup(String pTestName) {
try {
testName = pTestName;
Properties lDefaultProperties = new Properties();
lDefaultProperties.load(new FileInputStream(orcasCoreIntegrationConfig.getBaseDir() + "/parameter.properties"));
Properties lTestProperties = new Properties();
String lTestPropertiesFileName = orcasCoreIntegrationConfig.getBaseDir() + "tests/" + pTestName + "/parameter.properties";
if (new File(lTestPropertiesFileName).exists()) {
lTestProperties.load(new FileInputStream(lTestPropertiesFileName));
}
_testWithData = getBooleanProperty("test_with_data", lDefaultProperties, lTestProperties);
_dropmode = getBooleanProperty("dropmode", lDefaultProperties, lTestProperties);
_indexparallelcreate = getBooleanProperty("indexparallelcreate", lDefaultProperties, lTestProperties);
_createmissingfkindexes = getBooleanProperty("createmissingfkindexes", lDefaultProperties, lTestProperties);
_test_extract = getBooleanProperty("test_extract", lDefaultProperties, lTestProperties);
_tablemovetablespace = getBooleanProperty("tablemovetablespace", lDefaultProperties, lTestProperties);
_indexmovetablespace = getBooleanProperty("indexmovetablespace", lDefaultProperties, lTestProperties);
_extensionfolder = getProperty("extensionfolder", lDefaultProperties, lTestProperties);
_required_feature_list = getProperty("required_feature_list", lDefaultProperties, lTestProperties);
_dateformat = getProperty("dateformat", lDefaultProperties, lTestProperties);
_excludewheresequence = getProperty("excludewheresequence", lDefaultProperties, lTestProperties);
_excludewheresequence = _excludewheresequence.replaceAll("''", "'");
_additionsOnly = getBooleanProperty("additionsonly", lDefaultProperties, lTestProperties);
_columnsSetUnused = getBooleanProperty("setunused", lDefaultProperties, lTestProperties);
_indexonlinecreation = getBooleanProperty("indexonlinecreation", lDefaultProperties, lTestProperties);
_expectfailure = getProperty("expectfailure", lDefaultProperties, lTestProperties);
_minimizeStatementCount = getBooleanProperty("minimizestatementcount", lDefaultProperties, lTestProperties);
_cleanupfkvaluesondropmode = getBooleanProperty("cleanupfkvaluesondropmode", lDefaultProperties, lTestProperties);
_mviewsWithColumns = getBooleanProperty("mviewswithcolumns", lDefaultProperties, lTestProperties);
relevantFiles = getProperty("relevantFiles", lDefaultProperties, lTestProperties);
if (_expectfailure != null && _expectfailure.trim().length() == 0) {
_expectfailure = null;
}
_schemaNames = Arrays.asList(getProperty("schema_names", lDefaultProperties, lTestProperties).split(","));
_availableFeatureRequirementMatched = true;
for (String lRequiredFeature : Arrays.asList(_required_feature_list.split(","))) {
if (!orcasCoreIntegrationConfig.getAvailableFeatureList().contains(lRequiredFeature)) {
_availableFeatureRequirementMatched = false;
}
}
if (!_extensionfolder.equals("extensions")) {
_customExtensionFolder = true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void assumeShouldExecuteTestcase() {
Assume.assumeTrue("testcase ignored custom extensionfolder not supported yet " + _extensionfolder, !_customExtensionFolder);
Assume.assumeTrue(
"testcase ignored: " + testName + " " + orcasCoreIntegrationConfig.getExecuteTests(),
testName.matches(orcasCoreIntegrationConfig.getExecuteTests()));
Assume.assumeTrue("testcase skipped, required features not available: required: "
+ _required_feature_list
+ " available: "
+ orcasCoreIntegrationConfig.getAvailableFeatureList(), _availableFeatureRequirementMatched);
}
private boolean getBooleanProperty(String pKey, Properties pDefaultProperties, Properties pTestProperties) {
String lValue = getProperty(pKey, pDefaultProperties, pTestProperties);
return lValue.equals("true");
}
private String getProperty(String pKey, Properties pDefaultProperties, Properties pTestProperties) {
if (pTestProperties.getProperty(pKey) != null) {
return pTestProperties.getProperty(pKey);
}
return pDefaultProperties.getProperty(pKey);
}
}
@Before
public void beforeTest() throws Exception {
_testSetup = new TestSetup(testName);
synchronized (_connectParametersTargetUserMap) {
if (!_connectParametersTargetUserMap.containsKey(testName)) {
Map<String, JdbcConnectParameters> lMap = new HashMap<>();
_testSetup._schemaNames.forEach(p -> lMap.put(p, OrcasParallelConnectionHandler.createConnectionParametersForTargetUser()));
_connectParametersTargetUserMap.put(testName, lMap);
}
}
}
public void afterAllTests() {
synchronized (_connectParametersTargetUserMap) {
_connectParametersTargetUserMap.get(testName).values().forEach(p -> {
if (_testSetup.isMultiSchema()) {
try {
OrcasParallelConnectionHandler.resetUser(p);
} catch (Exception e) {
e.printStackTrace();
}
}
OrcasParallelConnectionHandler.returnConnectionParametersForTargetUser(p);
});
_connectParametersTargetUserMap.put(testName, null);
}
}
private JdbcConnectParameters getConnectParametersTargetUser() {
synchronized (_connectParametersTargetUserMap) {
return _connectParametersTargetUserMap.get(testName).get(_testSetup._schemaNames.get(0));
}
}
private static void executeScript(String pBaseDir, JdbcConnectParameters pJdbcConnectParameters, String pScriptName, String... pParameters) {
ParametersCall lParametersCall = new ParametersCall();
copyConnectionParameters(pJdbcConnectParameters, lParametersCall.getJdbcConnectParameters());
lParametersCall.setAdditionalParameters(Arrays.asList(pParameters));
lParametersCall.setIsOneTimeScriptMode(false);
lParametersCall.setFailOnErrorMode(FailOnErrorMode.IGNORE_DROP);
lParametersCall.setModelFile(pBaseDir + pScriptName);
new OrcasScriptRunner().mainRun(lParametersCall);
}
private static void executeScriptIfExists(JdbcConnectParameters pJdbcConnectParameters, String pScriptName, String... pParameters) {
if (new File(orcasCoreIntegrationConfig.getBaseDir() + pScriptName).exists()) {
executeScript(orcasCoreIntegrationConfig.getBaseDir(), pJdbcConnectParameters, pScriptName, pParameters);
}
}
private static void executeScript(JdbcConnectParameters pJdbcConnectParameters, String pScriptName, String... pParameters) {
executeScript(orcasCoreIntegrationConfig.getBaseDir(), pJdbcConnectParameters, pScriptName, pParameters);
}
private static void copyConnectionParameters(JdbcConnectParameters pSourceConnectParameters, JdbcConnectParameters pDestConnectParameters) {
pDestConnectParameters.setJdbcDriver(pSourceConnectParameters.getJdbcDriver());
pDestConnectParameters.setJdbcUrl(pSourceConnectParameters.getJdbcUrl());
pDestConnectParameters.setJdbcUser(pSourceConnectParameters.getJdbcUser());
pDestConnectParameters.setJdbcPassword(pSourceConnectParameters.getJdbcPassword());
}
private void asserSchemasEqual(String pName, boolean pIncludeData) {
extractSchemas(pName, pIncludeData);
assertFilesEqual(
pName,
getSchemaExtarctFileName(REFERENCE_NAME, false, true, testName, ""),
getSchemaExtarctFileName(pName, false, true, testName, ""),
pIncludeData);
if (pIncludeData) {
_testSetup.runMultiSchemaSetup(p -> {
assertFilesEqual(
pName,
getSchemaExtarctFileName(REFERENCE_NAME, pIncludeData, false, testName, p.getFilePostfix()),
getSchemaExtarctFileName(pName, pIncludeData, false, testName, p.getFilePostfix()),
pIncludeData);
});
}
}
static void asserSchemaEqual(
String pNameExpected,
String pNameActual,
boolean pIncludeData,
String pTestName,
String pExcludeWhereSequence,
String pDateformat,
JdbcConnectParameters pJdbcConnectParameters,
boolean pIsMviewsWithColumns) {
extractSchema(
pJdbcConnectParameters,
pNameActual,
pIncludeData,
pTestName,
pExcludeWhereSequence,
pDateformat,
pIsMviewsWithColumns,
"");
assertFilesEqual(
pNameActual,
getSchemaExtarctFileName(pNameExpected, pIncludeData, true, pTestName, ""),
getSchemaExtarctFileName(pNameActual, pIncludeData, true, pTestName, ""),
pIncludeData);
assertFilesEqual(
pNameActual,
getSchemaExtarctFileName(pNameExpected, pIncludeData, false, pTestName, ""),
getSchemaExtarctFileName(pNameActual, pIncludeData, false, pTestName, ""),
pIncludeData);
}
private static void assertFilesEqual(String pName, String pExpectedFile, String pActualFile) {
assertFilesEqual(pName, pExpectedFile, pActualFile, true);
}
private static void assertFilesEqual(String pName, String pExpectedFile, String pActualFile, boolean pIncludeData) {
List<String> lExpectedLines = parseReaderToLines(new File(pExpectedFile));
List<String> lActualLines = parseReaderToLines(new File(pActualFile));
String lMessage = "files not equal: " + pName + " " + pExpectedFile + " " + pActualFile;
int lMinLines = Math.min(lExpectedLines.size(), lActualLines.size());
for (int i = 0; i < lMinLines; i++) {
if (pIncludeData || !lExpectedLines.get(i).contains("max_value_select")) {
assertEquals(lMessage, lExpectedLines.get(i), lActualLines.get(i));
}
}
assertEquals(lMessage, lExpectedLines.size(), lActualLines.size());
}
private void extractSchemas(String pName, boolean pIncludeData) {
if (pIncludeData) {
_testSetup.runMultiSchemaSetup(p -> {
extractSchemaSpool(p.getJdbcConnectParameters(), pName, pIncludeData, testName, p.getFilePostfix());
});
}
extractSchemaOrcas(
getConnectParametersTargetUser(),
pName,
testName,
_testSetup._excludewheresequence,
_testSetup._dateformat,
_testSetup.isMviewsWithColumns(),
this::multiSchemaSetup);
}
static void extractSchema(
JdbcConnectParameters pConnectParametersTargetUser,
String pName,
boolean pIncludeData,
String pTestName,
String pExcludeWhereSequence,
String pDateformat,
boolean pIsMviewsWithColumns,
String pSchemaFilePostfix) {
extractSchemaSpool(pConnectParametersTargetUser, pName, pIncludeData, pTestName, pSchemaFilePostfix);
extractSchemaOrcas(
pConnectParametersTargetUser,
pName,
pTestName,
pExcludeWhereSequence,
pDateformat,
pIsMviewsWithColumns,
p -> {
});
}
private static void extractSchemaSpool(
JdbcConnectParameters pConnectParametersTargetUser,
String pName,
boolean pIncludeData,
String pTestName,
String pSchemaFilePostfix) {
executeScript(
pConnectParametersTargetUser,
"spool.sql",
getSchemaExtarctFileName(pName, pIncludeData, false, pTestName, pSchemaFilePostfix),
orcasCoreIntegrationConfig.getWorkfolder() + pTestName + "/tmp_data.log",
pIncludeData ? "1=1" : "1=2");
}
private static void extractSchemaOrcas(
JdbcConnectParameters pConnectParametersTargetUser,
String pName,
String pTestName,
String pExcludeWhereSequence,
String pDateformat,
boolean pIsMviewsWithColumns,
Consumer<ParametersCall> pParameterModifier) {
ParametersCall lParametersCall = new ParametersCall();
copyConnectionParameters(pConnectParametersTargetUser, lParametersCall.getJdbcConnectParameters());
lParametersCall.setExcludewheresequence(pExcludeWhereSequence);
lParametersCall.setExcludewheretable(DEFAULT_EXCLUDE);
lParametersCall.setDateformat(pDateformat);
lParametersCall.setSpoolfile(getSchemaExtarctFileName(pName, false, true, pTestName, ""));
lParametersCall.setModelFile(null);
lParametersCall.setScriptprefix(null);
lParametersCall.setScriptpostfix(null);
lParametersCall.setOrderColumnsByName(true);
lParametersCall.setRemoveDefaultValuesFromModel(false);
lParametersCall.setViewExtractMode(pIsMviewsWithColumns ? "full" : ParameterDefaults.viewextractmode);
pParameterModifier.accept(lParametersCall);
new OrcasExtractStatics().mainRun(lParametersCall);
}
private static String getSchemaExtarctFileName(
String pString,
boolean pIncludeData,
boolean pOrcas,
String pTestName,
String pSchemaFilePostfix) {
return getWorkfolderFilename(
pTestName,
pString + (pOrcas ? "_orcas" : "_spool" + (pIncludeData ? "data" : "")) + pSchemaFilePostfix + (pOrcas ? ".xml" : ".txt"));
}
private static String getWorkfolderFilename(String pTestName, String pFilename) {
return orcasCoreIntegrationConfig.getWorkfolder() + pTestName + "/" + pFilename;
}
private void orcasExtract(String pString) {
String lSpoolFolder = getSpoolFolder(pString);
ParametersCall lParametersCall = new ParametersCall();
copyConnectionParameters(getConnectParametersTargetUser(), lParametersCall.getJdbcConnectParameters());
multiSchemaSetup(lParametersCall);
lParametersCall.setExcludewheresequence(_testSetup._excludewheresequence);
lParametersCall.setExcludewheretable(DEFAULT_EXCLUDE);
lParametersCall.setDateformat(_testSetup._dateformat);
lParametersCall.setSpoolfile(null);
lParametersCall.setSpoolfolder(lSpoolFolder);
lParametersCall.setModelFile(null);
lParametersCall.setScriptprefix(null);
lParametersCall.setScriptpostfix(null);
lParametersCall.setOrderColumnsByName(false);
lParametersCall.setRemoveDefaultValuesFromModel(true);
lParametersCall.setViewExtractMode(_testSetup.isMviewsWithColumns() ? "full" : ParameterDefaults.viewextractmode);
new OrcasExtractStatics().mainRun(lParametersCall);
}
private void executeOrcasStatics(JdbcConnectParameters pJdbcConnectParameters, String pSpoolName, boolean pLogIgnoredStatements) {
String lXmlInputFile = null;
if (isXmlInputFileExists()) {
lXmlInputFile = getXmlInputFile();
}
executeOrcasStatics(
pJdbcConnectParameters,
pSpoolName,
orcasCoreIntegrationConfig.getBaseDir() + "tests/" + testName + "/tabellen",
pLogIgnoredStatements,
lXmlInputFile);
}
private boolean isXmlInputFileExists() {
return new File(getXmlInputFile()).exists();
}
private String getXmlInputFile() {
return getBasedirFilename("input_xml.xml");
}
private String getBasedirFilename(String pFilename) {
return orcasCoreIntegrationConfig.getBaseDir() + "tests/" + testName + "/" + pFilename;
}
private void executeOrcasStatics(
JdbcConnectParameters pJdbcConnectParameters,
String pSpoolName,
String pModelFolder,
boolean pLogIgnoredStatements,
String pXmlInputFile) {
ParametersCall lParametersCall = new ParametersCall();
copyConnectionParameters(pJdbcConnectParameters, lParametersCall.getJdbcConnectParameters());
lParametersCall.setModelFile(pModelFolder);
lParametersCall.setSqlplustable(false);
lParametersCall.setTargetplsql(null);
lParametersCall.setScriptprefix(null);
lParametersCall.setScriptpostfix("sql");
lParametersCall.setExcludewheresequence(_testSetup._excludewheresequence);
lParametersCall.setExcludewheretable(DEFAULT_EXCLUDE);
lParametersCall.setOrderColumnsByName(false);
lParametersCall.setCreatemissingfkindexes(_testSetup._createmissingfkindexes);
lParametersCall.setDropmode(_testSetup._dropmode);
lParametersCall.setLogonly(false);
lParametersCall.setLogname(pSpoolName);
lParametersCall.setSpoolfolder(getSpoolFolder(pSpoolName));
lParametersCall.setXmlLogFile(orcasCoreIntegrationConfig.getWorkfolder() + testName + "/xmllog_" + pSpoolName + ".xml");
lParametersCall.setTablemovetablespace(_testSetup._tablemovetablespace);
lParametersCall.setIndexmovetablespace(_testSetup._indexmovetablespace);
lParametersCall.setMviewlogmovetablespace(true);
lParametersCall.setIndexparallelcreate(_testSetup._indexparallelcreate);
lParametersCall.setUpdateEnabledStatus(true);
lParametersCall.setDateformat(_testSetup._dateformat);
lParametersCall.setAdditionsOnly(_testSetup._additionsOnly);
lParametersCall.setLogIgnoredStatements(pLogIgnoredStatements);
lParametersCall.setSetUnusedInsteadOfDropColumn(_testSetup._columnsSetUnused);
lParametersCall.setCreateIndexOnline(_testSetup._indexonlinecreation);
String lXmlLogFile = getLogfileName(pSpoolName);
lParametersCall.setXmlLogFile(lXmlLogFile);
lParametersCall.setXmlInputFile(pXmlInputFile);
lParametersCall.setMinimizeStatementCount(_testSetup._minimizeStatementCount);
lParametersCall.setCleanupFkValuesOnDropmode(_testSetup._cleanupfkvaluesondropmode);
lParametersCall.setViewExtractMode(_testSetup.isMviewsWithColumns() ? "full" : ParameterDefaults.viewextractmode);
List<File> lRelevantFileList = Stream.of(_testSetup.relevantFiles.split(","))
.filter(it -> !it.isEmpty())
.map(it -> new File(pModelFolder + "/" + it))
.collect(Collectors.toList());
if (!lRelevantFileList.isEmpty()) {
lParametersCall.setRelevantModelFiles(lRelevantFileList);
}
multiSchemaSetup(lParametersCall);
lParametersCall.setAdditionalOrcasExtensionFactory(new AdditionalExtensionFactory() {
@SuppressWarnings("unchecked")
@Override
public <T extends EObject> List<UnaryOperator<T>> getAdditionalExtensions(Class<T> pModelClass, boolean pReverseMode) {
List<UnaryOperator<T>> lList = new ArrayList<>(Collections.singletonList(p -> (T) new TablespaceRemapperExtension(
orcasCoreIntegrationConfig.getAlternateTablespace1(),
orcasCoreIntegrationConfig.getAlternateTablespace2()).transformModel((Model) p)));
if (_testSetup.isMultiSchema()) {
lList.add(p -> {
ReplaceMultiSchemaPrefixExtension lReplaceMultiSchemaPrefixExtension = new ReplaceMultiSchemaPrefixExtension();
_testSetup.runMultiSchemaSetup(p1 -> lReplaceMultiSchemaPrefixExtension.initSchema(p1));
return (T) lReplaceMultiSchemaPrefixExtension.transformModel((Model) p);
});
}
return lList;
}
});
if (isExpectfailure()) {
try {
new OrcasMain().mainRun(lParametersCall);
fail("expected faliure: " + _testSetup._expectfailure);
} catch (Exception e) {
String lMessage = e.getMessage();
boolean lMatches = lMessage.matches(_testSetup._expectfailure);
if (!lMatches) {
throw new RuntimeException("no matching error: " + _testSetup._expectfailure + " " + lMessage, e);
}
}
} else {
new OrcasMain().mainRun(lParametersCall);
}
if (pXmlInputFile == null) {
assertXmlLogFileParse(pSpoolName, lXmlLogFile);
}
}
private void multiSchemaSetup(ParametersCall pParametersCall) {
if (_testSetup.isMultiSchema()) {
pParametersCall.setMultiSchema(true);
pParametersCall.setMultiSchemaExcludewhereowner("owner not in (','");
_testSetup.runMultiSchemaSetup(p ->
pParametersCall.setMultiSchemaExcludewhereowner(pParametersCall.getMultiSchemaExcludewhereowner() + ",'" + p
.getSchemaName()
.toUpperCase() + "'"));
pParametersCall.setMultiSchemaExcludewhereowner(pParametersCall.getMultiSchemaExcludewhereowner() + ")");
copyConnectionParameters(OrcasParallelConnectionHandler._connectParametersDba, pParametersCall.getJdbcConnectParameters());
pParametersCall.setMultiSchemaDbaViews(true);
pParametersCall.setMultiSchemaConnectionManager(new BaseMultiSchemaConnectionManager() {
@Override
protected JdbcConnectParameters getJdbcConnectParametersForSchema(
String pSchemaName,
de.opitzconsulting.orcas.diff.Parameters pParameters) {
JdbcConnectParameters lJdbcConnectParameters = new JdbcConnectParameters();
copyConnectionParameters(OrcasParallelConnectionHandler._connectParametersDba, lJdbcConnectParameters);
lJdbcConnectParameters.setJdbcUser(pSchemaName);
lJdbcConnectParameters.setJdbcPassword(pSchemaName.toLowerCase());
return lJdbcConnectParameters;
}
});
}
}
private String getLogfileName(String pSpoolName) {
return getSpoolFolder(pSpoolName + "_log.xml");
}
private void assertXmlLogFileParse(String pSpoolName, String pXmlLogFile) {
ParametersCall lParametersCall = new ParametersCall();
XmlLogFileHandler lXmlLogFileHandler = new XmlLogFileHandler(lParametersCall);
DiffResult lParseXmlDiffResult = lXmlLogFileHandler.parseXml(pXmlLogFile);
String lXmlLogFileFromXmlLogFileHandlerParse = getSpoolFolder(pSpoolName + "_log_reparse.xml");
lXmlLogFileHandler.logXml(lParseXmlDiffResult, lXmlLogFileFromXmlLogFileHandlerParse);
assertFilesEqual("xml-log-parse", pXmlLogFile, lXmlLogFileFromXmlLogFileHandlerParse);
}
private String getSpoolFolder(String pSpoolName) {
return orcasCoreIntegrationConfig.getWorkfolder() + testName + "/" + pSpoolName;
}
private void assumeTestNotSkipped(boolean pNoSkipTest) {
Assume.assumeTrue("test skipped", pNoSkipTest);
}
@Test
public void test_00_setup_reference() {
File lFile = new File(orcasCoreIntegrationConfig.getWorkfolder() + testName);
deleteRecursive(lFile);
lFile.mkdirs();
resetUsers();
if (!isExpectfailure()) {
_testSetup.runMultiSchemaSetupWithDbaSetup(p ->
executeScriptIfExists(
p.getJdbcConnectParameters(),
"tests/" + testName + "/" + "erzeuge_zielzustand" + p.getFilePostfix() + ".sql",
p.getParameters(
orcasCoreIntegrationConfig.getAlternateTablespace1(),
orcasCoreIntegrationConfig.getAlternateTablespace2())));
extractSchemas(REFERENCE_NAME, _testSetup._testWithData);
if (orcasCoreIntegrationConfig.isWithRunWithExtractTest()) {
if (_testSetup._testWithData) {
extractSchemas(REFERENCE_NAME, false);
}
orcasExtract(EXTRACT_FOLDER_NAME);
}
}
}
private void resetUsers() {
synchronized (_connectParametersTargetUserMap) {
_connectParametersTargetUserMap
.get(testName)
.values()
.forEach(OrcasParallelConnectionHandler::resetUser);
}
}
private boolean isExpectfailure() {
return _testSetup._expectfailure != null;
}
@Test
public void test_01_update_statics() {
assumeTestNotSkipped(orcasCoreIntegrationConfig.isWithFirstRunTest());
resetUsers();
setupInitialState();
executeOrcasStatics(getConnectParametersTargetUser(), _lognameFirstRun, true);
if (!isExpectfailure()) {
asserSchemasEqual("01_schema", _testSetup._testWithData);
}
String lReferenceXmlFile = getBasedirFilename("reference_log.xml");
if (new File(lReferenceXmlFile).exists()) {
assertFilesEqual("reference_log", lReferenceXmlFile, getLogfileName(_lognameFirstRun));
}
}
private void setupInitialState() {
_testSetup.runMultiSchemaSetupWithDbaSetup(p ->
executeScriptIfExists(
getConnectParametersTargetUser(),
"tests/" + testName + "/" + "erzeuge_ausgangszustand" + p.getFilePostfix() + ".sql",
p.getParameters(
orcasCoreIntegrationConfig.getAlternateTablespace1(),
orcasCoreIntegrationConfig.getAlternateTablespace2())));
}
@Test
public void test_02_second_run_empty() {
assumeTestNotSkipped(orcasCoreIntegrationConfig.isWithSecondRunEmptyTest() && !isXmlInputFileExists() && !isExpectfailure());
String lLognameSecondRun = "02_statics";
executeOrcasStatics(getConnectParametersTargetUser(), lLognameSecondRun, false);
assertFalse("second run not empty", new File(getSpoolFolder(lLognameSecondRun)).exists());
}
@Test
public void test_03_run_with_spool() {
assumeTestNotSkipped(orcasCoreIntegrationConfig.isWithRunWithSpoolTest() && !isExpectfailure());
resetUsers();
setupInitialState();
executeScript(
orcasCoreIntegrationConfig.getWorkfolder() + testName + "/" + _lognameFirstRun + "/",
_testSetup.isMultiSchema() ? OrcasParallelConnectionHandler._connectParametersDba : getConnectParametersTargetUser(),
"master_install.sql");
asserSchemasEqual("03_schema", _testSetup._testWithData);
}
@Test
public void test_04_run_with_extract() {
try {
assumeTestNotSkipped(orcasCoreIntegrationConfig.isWithRunWithExtractTest() && !isExpectfailure());
Assume.assumeTrue("extract test not possible for testcase", _testSetup._test_extract);
resetUsers();
String lErzeugeAusgangszustandExtractFile = getBasedirFilename("erzeuge_ausgangszustand_extract.sql");
if (new File(lErzeugeAusgangszustandExtractFile).exists()) {
executeScript(
getConnectParametersTargetUser(),
lErzeugeAusgangszustandExtractFile,
orcasCoreIntegrationConfig.getAlternateTablespace1(),
orcasCoreIntegrationConfig.getAlternateTablespace2());
}
executeOrcasStatics(
getConnectParametersTargetUser(),
"04_statics",
orcasCoreIntegrationConfig.getWorkfolder() + testName + "/" + EXTRACT_FOLDER_NAME,
true,
null);
asserSchemasEqual("04_schema", false);
} finally {
afterAllTests();
}
}
}
|
package rx.performance;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import rx.Observable;
import rx.Observer;
import rx.util.functions.Func1;
public class PerformanceTest {
/*
* Example run:
*
* compositionTestTotalTime: 2432
* nonCompositionalTestWithDirectLoopTotalTime: 2043
* nonCompositionalTestWithArrayOfFunctionsTotalTime: 1925
*
* compositionTestTotalTime: 2362
* nonCompositionalTestWithDirectLoopTotalTime: 1910
* nonCompositionalTestWithArrayOfFunctionsTotalTime: 1823
*
* compositionTestTotalTime: 2456
* nonCompositionalTestWithDirectLoopTotalTime: 2004
* nonCompositionalTestWithArrayOfFunctionsTotalTime: 2014
*/
/*
* >>> Statically typed <<<
*
* Without chaining:
*
* Sum: 710082754 Time: 130.683ms
* runNonCompositionalTestWithDirectLoop
* Sum: 710082754 Time: 21.011ms
* runNonCompositionalTestWithArrayOfFunctions
* Sum: 710082754 Time: 20.84ms
*
*
* With chaining (composition collapsing):
*
* Sum: 710082754 Time: 28.787ms
* runNonCompositionalTestWithDirectLoop
* Sum: 710082754 Time: 19.525ms
* runNonCompositionalTestWithArrayOfFunctions
* Sum: 710082754 Time: 19.175ms
*
*
* >>> Dynamically typed <<<
*
* When going via generic Functions.execute even with chained sequence:
*
* runCompositionTest
* Sum: 710082754 Time: 577.3ms <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< very bad when dynamic
* runNonCompositionalTestWithDirectLoop
* Sum: 710082754 Time: 31.591ms
* runNonCompositionalTestWithArrayOfFunctions
* Sum: 710082754 Time: 38.093ms
* runCompositionTest
*
*
* With Function memoization so we only pay dynamic price during sequence setup, not in onNext:
*
*
* Using ArrayList
*
* runCompositionTest
* Sum: 710082754 Time: 27.078ms
* runNonCompositionalTestWithDirectLoop
* Sum: 710082754 Time: 18.911ms
* runNonCompositionalTestWithArrayOfFunctions
* Sum: 710082754 Time: 18.852ms
*
*
* Using LinkedBlockingQueue
*
* runCompositionTest
* Sum: 710082754 Time: 46.532ms
* runNonCompositionalTestWithDirectLoop
* Sum: 710082754 Time: 18.946ms
* runNonCompositionalTestWithArrayOfFunctions
* Sum: 710082754 Time: 18.746ms
*/
public static void main(String[] args) {
PerformanceTest test = new PerformanceTest();
Integer[] values = new Integer[100001];
for (int i = 0; i < values.length; i++) {
values[i] = i;
}
AtomicLong compositionTestTotalTime = new AtomicLong();
AtomicLong nonCompositionalTestWithDirectLoopTotalTime = new AtomicLong();
AtomicLong nonCompositionalTestWithArrayOfFunctionsTotalTime = new AtomicLong();
for (int i = 0; i < 100; i++) {
System.out.println("-------------------------------");
// test.runCompositionTestWithMultipleOperations(values);
test.runCompositionTest(compositionTestTotalTime, values);
test.runNonCompositionalTestWithDirectLoop(nonCompositionalTestWithDirectLoopTotalTime, values);
test.runNonCompositionalTestWithArrayOfFunctions(nonCompositionalTestWithArrayOfFunctionsTotalTime, values);
}
System.out.println("-------------------------------");
System.out.println("compositionTestTotalTime: " + compositionTestTotalTime.get());
System.out.println("nonCompositionalTestWithDirectLoopTotalTime: " + nonCompositionalTestWithDirectLoopTotalTime.get());
System.out.println("nonCompositionalTestWithArrayOfFunctionsTotalTime: " + nonCompositionalTestWithArrayOfFunctionsTotalTime.get());
}
@SuppressWarnings("unchecked")
public void runCompositionTestWithMultipleOperations(AtomicLong aggregateTime, Integer[] values) {
System.out.println("runCompositionTestWithMultipleOperations");
// old code before memoizing
// Count: 200002 Time: 403.095ms
// new code with memoizing but no chaining
// Count: 200002 Time: 103.128ms
final AtomicInteger onNextSum = new AtomicInteger(0);
final long start = System.nanoTime();
MathFunction m = new MathFunction();
Observable<Integer> a = Observable.from(values)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m);
final Observable<Integer> b = Observable.from(values)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m);
Observable.merge(a, b).filter(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 > 10;
}
}).map(new Func1<Integer, String>() {
@Override
public String call(Integer t1) {
return t1 + "-value-from-b";
}
}).take(1000000).subscribe(new TestStringObserver(onNextSum, start));
}
public void runCompositionTest(AtomicLong aggregateTime, Integer[] values) {
System.out.println("runCompositionTest");
final AtomicInteger onNextSum = new AtomicInteger(0);
final long start = System.nanoTime();
MathFunction m = new MathFunction();
// 50 levels of composition (same function so that's not the cost)
Observable.from(values)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m)
.map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m).map(m)
.subscribe(new TestObserver(onNextSum, start, aggregateTime));
}
public void runNonCompositionalTestWithDirectLoop(AtomicLong aggregateTime, Integer[] values) {
System.out.println("runNonCompositionalTestWithDirectLoop");
final AtomicInteger onNextSum = new AtomicInteger(0);
final long start = System.nanoTime();
final MathFunction m = new MathFunction();
Observable.from(values).map(new Func1<Integer, Integer>() {
@Override
public Integer call(Integer t1) {
// iterate the 50 times here in a loop rather than via composition
for (int i = 0; i < 50; i++) {
t1 = m.call(t1);
}
return t1;
}
}).subscribe(new TestObserver(onNextSum, start, aggregateTime));
}
public void runNonCompositionalTestWithArrayOfFunctions(AtomicLong aggregateTime, Integer[] values) {
System.out.println("runNonCompositionalTestWithArrayOfFunctions");
final AtomicInteger onNextSum = new AtomicInteger(0);
final long start = System.nanoTime();
final MathFunction m = new MathFunction();
@SuppressWarnings("rawtypes")
final Func1[] functionCalls = new Func1<?, ?>[50];
for (int i = 0; i < 50; i++) {
functionCalls[i] = m;
}
Observable.from(values).map(new Func1<Integer, Integer>() {
@SuppressWarnings("unchecked")
@Override
public Integer call(Integer t1) {
// iterate the 50 times here in a loop rather than via composition
for (Func1<Integer, Integer> f : functionCalls) {
t1 = f.call(t1);
}
return t1;
}
}).subscribe(new TestObserver(onNextSum, start, aggregateTime));
}
private static final class TestObserver implements Observer<Integer> {
private final AtomicInteger onNextSum;
private final AtomicLong aggregateTime;
private final long start;
private TestObserver(AtomicInteger onNextSum, long start, AtomicLong aggregateTime) {
this.onNextSum = onNextSum;
this.start = start;
this.aggregateTime = aggregateTime;
}
@Override
public void onNext(Integer i) {
onNextSum.addAndGet(i);
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
@Override
public void onCompleted() {
long end = System.nanoTime();
double timeInMilliseconds = ((double) (end - start)) / 1000 / 1000;
aggregateTime.addAndGet(Math.round(timeInMilliseconds));
System.out.println("Sum: " + onNextSum.get() + " Time: " + timeInMilliseconds + "ms");
}
}
private static final class TestStringObserver implements Observer<String> {
private final AtomicInteger onNextSum;
private final long start;
private TestStringObserver(AtomicInteger onNextSum, long start) {
this.onNextSum = onNextSum;
this.start = start;
}
@Override
public void onNext(String i) {
// System.out.println(i);
onNextSum.incrementAndGet();
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
@Override
public void onCompleted() {
long end = System.nanoTime();
System.out.println("Count: " + onNextSum.get() + " Time: " + ((double) (end - start)) / 1000 / 1000 + "ms");
}
}
private static class MathFunction implements Func1<Integer, Integer> {
@Override
public Integer call(Integer t1) {
return t1 + 1;
}
}
}
|
package io.perfeccionista.framework.exceptions.attachments;
import io.perfeccionista.framework.exceptions.EmptyAttachment;
import io.perfeccionista.framework.screenshots.Screenshot;
import org.jetbrains.annotations.NotNull;
import static io.perfeccionista.framework.exceptions.messages.UtilsMessages.EMPTY_ATTACHMENT_ENTRY;
public class ScreenshotAttachmentEntry extends FileAttachmentEntry<Screenshot> {
protected ScreenshotAttachmentEntry(String name, Screenshot content) {
super(name, content);
}
public static ScreenshotAttachmentEntry of(@NotNull String name, @NotNull Screenshot content) {
return new ScreenshotAttachmentEntry(name, content);
}
// TODO: Можно здесь выводить параметры скриншота: тип, имя, размер
@Override
public String getDescription() {
return "No text description for screenshot";
}
@Override
public @NotNull String getFileExtension() {
return getContent().orElseThrow(() -> EmptyAttachment.exception(EMPTY_ATTACHMENT_ENTRY.getMessage()))
.getFileExtension();
}
}
|
/**
* MIT License
*
* Copyright (c) 2021 the original author or authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mountsea.django.bson.projection.dtbson;
import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
/**
* A Codec for DtBsonDouble instances.
*
* @since 3.0
*/
public class DtBsonDoubleCodec implements Codec<DtBsonDouble> {
@Override
public DtBsonDouble decode(final BsonReader reader, final DecoderContext decoderContext) {
return new DtBsonDouble(reader.readDouble());
}
@Override
public void encode(final BsonWriter writer, final DtBsonDouble value, final EncoderContext encoderContext) {
writer.writeDouble(value.getValue());
}
@Override
public Class<DtBsonDouble> getEncoderClass() {
return DtBsonDouble.class;
}
}
|
/*
* #%L
* sfdc-email-to-case-agent
* %%
* Copyright (C) 2005 salesforce.com, inc.
* %%
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* 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. Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package com.sforce;
import java.util.TimerTask;
public abstract class SalesforceWorker extends TimerTask {
}
|
package com.hazelcast.management;
import com.eclipsesource.json.JsonObject;
/**
* JsonSerializable is a serialization interface that serializes/de-serializes to/from JSON.
*/
public interface JsonSerializable {
JsonObject toJson();
void fromJson(JsonObject json);
}
|
/*
* Copyright 2011 The Netty Project
*
* The Netty Project 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 com.yammer.httptunnel.client.auth;
import java.util.Map;
import org.jboss.netty.handler.codec.http.HttpRequest;
import com.yammer.httptunnel.client.ProxyAuthenticationException;
/**
* This interface is used by the client end of an http tunnel to handle proxy
* authentication requests.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public interface AuthScheme {
/**
* Gets the name of the authentication method supported by this instance.
*/
public String getName();
/**
* Generates the authentication response header for the given request, using
* the given credentials.
*/
public String authenticate(HttpRequest request, Map<String, String> challenge, String username, String password) throws ProxyAuthenticationException;
}
|
package com.nulabinc.backlog4j.api.option;
import com.nulabinc.backlog4j.http.NameValuePair;
import java.util.ArrayList;
import java.util.List;
/**
* Parameters for patch request.
*
* @author nulab-inc
*/
public abstract class PatchParams {
protected List<NameValuePair> parameters = new ArrayList<NameValuePair>();
public List<NameValuePair> getParamList() {
return parameters;
}
}
|
package com.yvrun.officeprocess.news;
import androidx.annotation.NonNull;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.yvrun.officeprocess.R;
public class VideoAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
public VideoAdapter() {
super(R.layout.item_news);
}
@Override
protected void convert(@NonNull BaseViewHolder helper, String item) {
helper.setText(R.id.tv_title,item);
}
}
|
/*
* Copyright 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 software.amazon.smithy.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.CodegenUtils.getBlobStreamingMembers;
import static software.amazon.smithy.typescript.codegen.CodegenUtils.writeInlineStreamingMemberType;
import java.util.List;
import java.util.stream.Collectors;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.codegen.core.SymbolReference;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.ErrorTrait;
import software.amazon.smithy.typescript.codegen.integration.HttpProtocolGeneratorUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Generates normal structures and error structures.
*
* Renders structures as interfaces.
*
* <p>A namespace is created with the same name as the structure to
* provide helper functionality for checking if a given value is
* known to be of the same type as the structure. This will be
* even more useful if/when inheritance is added to Smithy.
*
* <p>Note that the {@code required} trait on structures is used to
* determine whether or not a generated TypeScript interface uses
* required members. This is typically not recommended in other languages
* since it's documented as backward-compatible for a model to migrate a
* required property to optional. This becomes an issue when an older
* client consumes a service that has relaxed a member to become optional.
* In the case of sending data from the client to the server, the client
* likely either is still operating under the assumption that the property
* is required, or the client can set a property explicitly to
* {@code undefined} to fix any TypeScript compilation errors. In the
* case of deserializing a value from a service to the client, the
* deserializers will need to set previously required properties to
* undefined too.
*
* <p>The generator will explicitly state that a required property can
* be set to {@code undefined}. This makes it clear that undefined checks
* need to be made when using {@code --strictNullChecks}, but has no
* effect otherwise.
*/
@SmithyInternalApi
final class StructureGenerator implements Runnable {
private final Model model;
private final SymbolProvider symbolProvider;
private final TypeScriptWriter writer;
private final StructureShape shape;
private final boolean includeValidation;
/**
* sets 'includeValidation' to 'false' for backwards compatibility.
*/
StructureGenerator(Model model, SymbolProvider symbolProvider, TypeScriptWriter writer, StructureShape shape) {
this(model, symbolProvider, writer, shape, false);
}
StructureGenerator(Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer,
StructureShape shape,
boolean includeValidation) {
this.model = model;
this.symbolProvider = symbolProvider;
this.writer = writer;
this.shape = shape;
this.includeValidation = includeValidation;
}
@Override
public void run() {
if (shape.hasTrait(ErrorTrait.class)) {
renderErrorStructure();
} else {
renderNonErrorStructure();
}
}
/**
* Renders a normal, non-error structure.
*
* <p>For example, given the following Smithy model:
*
* <pre>{@code
* namespace smithy.example
*
* structure Person {
* @required
* name: String,
* @range(min: 1)
* age: Integer,
* }
* }</pre>
*
* <p>The following TypeScript is rendered:
*
* <pre>{@code
* export interface Person {
* name: string | undefined;
* age?: number | null;
* }
*
* export namespace Person {
* export const filterSensitiveLog = (obj: Person): any => ({...obj});
* }
* }</pre>
*
* <p>If validation is enabled, it generates the following:
*
* <pre>{@code
* export interface Person {
* name: string | undefined;
* age?: number | null;
* }
*
* export namespace Person {
* export const filterSensitiveLog = (obj: Person): any => ({...obj});
* export const validate = (obj: Person): ValidationFailure[] => {
* // validation
* }
* }
* }</pre>
*/
private void renderNonErrorStructure() {
Symbol symbol = symbolProvider.toSymbol(shape);
writer.writeShapeDocs(shape);
// Find symbol references with the "extends" property.
String extendsFrom = symbol.getReferences().stream()
.filter(ref -> ref.getProperty(SymbolVisitor.IMPLEMENTS_INTERFACE_PROPERTY).isPresent())
.map(SymbolReference::getAlias)
.collect(Collectors.joining(", "));
if (extendsFrom.isEmpty()) {
writer.openBlock("export interface $L {", symbol.getName());
} else {
writer.openBlock("export interface $L extends $L {", symbol.getName(), extendsFrom);
}
StructuredMemberWriter config = new StructuredMemberWriter(
model, symbolProvider, shape.getAllMembers().values());
config.writeMembers(writer, shape);
writer.closeBlock("}");
writer.write("");
renderStructureNamespace(config, includeValidation);
}
private void renderStructureNamespace(StructuredMemberWriter structuredMemberWriter, boolean includeValidation) {
Symbol symbol = symbolProvider.toSymbol(shape);
writer.openBlock("export namespace $L {", "}", symbol.getName(), () -> {
String objectParam = "obj";
writer.writeDocs("@internal");
writer.openBlock("export const filterSensitiveLog = ($L: $L): any => ({", "})",
objectParam, symbol.getName(),
() -> {
structuredMemberWriter.writeFilterSensitiveLog(writer, objectParam);
}
);
if (!includeValidation) {
return;
}
structuredMemberWriter.writeMemberValidatorCache(writer, "memberValidators");
writer.addImport("ValidationFailure", "__ValidationFailure", "@aws-smithy/server-common");
writer.writeDocs("@internal");
List<MemberShape> blobStreamingMembers = getBlobStreamingMembers(model, shape);
writer.writeInline("export const validate = ($L: ", objectParam);
if (blobStreamingMembers.isEmpty()) {
writer.writeInline("$L", symbol.getName());
} else {
writeInlineStreamingMemberType(writer, symbol, blobStreamingMembers.get(0));
}
writer.openBlock(", path: string = \"\"): __ValidationFailure[] => {", "}", () -> {
structuredMemberWriter.writeMemberValidatorFactory(writer, "memberValidators");
structuredMemberWriter.writeValidateMethodContents(writer, objectParam);
});
});
}
/**
* Error structures generate classes that extend from service base exception
* (ServiceException in case of server SDK), and add the appropriate fault
* property.
*
* <p>Given the following Smithy structure:
*
* <pre>{@code
* namespace smithy.example
*
* @error("client")
* structure NoSuchResource {
* @required
* resourceType: String
* }
* }</pre>
*
* <p>The following TypeScript is generated:
*
* <pre>{@code
* import { ExceptionOptionType as __ExceptionOptionType } from "@aws-sdk/smithy-client";
* import { FooServiceException as __BaseException } from "./FooServiceException";
* // In server SDK:
* // import { ServiceException as __BaseException } from "@aws-smithy/server-common";
*
* export class NoSuchResource extends __BaseException {
* name: "NoSuchResource";
* $fault: "client";
* resourceType: string | undefined;
* // @internal
* constructor(opts: __ExceptionOptionType<NoSuchResource, __BaseException>) {
* super({
* name: "NoSuchResource",
* $fault: "client",
* ...opts
* });
* Object.setPrototypeOf(this, NoSuchResource.prototype);
* this.resourceType = opts.resourceType;
* }
* }
* }</pre>
*/
private void renderErrorStructure() {
ErrorTrait errorTrait = shape.getTrait(ErrorTrait.class).orElseThrow(IllegalStateException::new);
Symbol symbol = symbolProvider.toSymbol(shape);
writer.writeShapeDocs(shape);
boolean isServerSdk = this.includeValidation;
writer.openBlock("export class $T extends $L {", symbol, "__BaseException");
writer.write("readonly name: $1S = $1S;", shape.getId().getName());
writer.write("readonly $$fault: $1S = $1S;", errorTrait.getValue());
if (!isServerSdk) {
HttpProtocolGeneratorUtils.writeRetryableTrait(writer, shape, ";");
}
StructuredMemberWriter structuredMemberWriter = new StructuredMemberWriter(model, symbolProvider,
shape.getAllMembers().values());
// since any error interface must extend from JavaScript Error interface, message member is already
// required in the JavaScript Error interface
structuredMemberWriter.skipMembers.add("message");
structuredMemberWriter.writeMembers(writer, shape);
structuredMemberWriter.writeErrorConstructor(writer, shape, isServerSdk);
writer.closeBlock("}");
writer.write("");
}
}
|
package api;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import main.Compte;
public class connect extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7605265537803683707L;
@Override
public void init() throws ServletException {
super.init();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String resp = "";
try {
String host ="http://"+ request.getParameter("host");
String action =request.getParameter("action");
String from = request.getServerName();
machine m = new machine(host+"/authenticate","med","med");
HttpSession session=request.getSession();
Compte.assign_history(Integer.valueOf(session.getAttribute("user_id").toString()), action, from, host);
if (action.equals("c_msg")) {
//String title =request.getParameter("title");
String msg =request.getParameter("msg");
m.send_msg(host, msg,"MSG FROM admin");
}else if (action.contains("behaviour")) {
m.send_bhv(host+action);
}else if(action.contains("execute")) {
String cmd = request.getParameter("cmd");
resp = m.send_cmd(host+action,cmd);
}
}catch(Exception e) {
e.printStackTrace();
}
pwriter.println(resp);
pwriter.println("done");
}
}
|
/*
TcpClient.java
Firefly Luciferin, very fast Java Screen Capture software designed
for Glow Worm Luciferin firmware.
Copyright (C) 2020 - 2022 Davide Perini (https://github.com/sblantipodi)
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 <https://www.gnu.org/licenses/>.
*/
package org.dpsoftware.network.tcpUdp;
import lombok.extern.slf4j.Slf4j;
import org.dpsoftware.config.Constants;
import org.dpsoftware.managers.dto.TcpResponse;
import org.dpsoftware.utilities.CommonUtility;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* Utility class for TCP communication
*/
@Slf4j
public class TcpClient {
/**
* Send an HTTP GET to a specifi IP address
*
* @param msg msg to use in the payload param
* @param topic http get path
* @return response
*/
@SuppressWarnings("UnusedReturnValue")
public static TcpResponse httpGet(String msg, String topic, String destinationIP) {
TcpResponse tcpResponse = new TcpResponse();
try {
HttpURLConnection con;
String request = Constants.HTTP_URL
.replace("{0}", destinationIP)
.replace("{1}", topic)
.replace("{2}", URLEncoder.encode(msg, StandardCharsets.UTF_8));
CommonUtility.conditionedLog(Constants.TCP_CLIENT, "HTTP GET=" + request);
URL url = new URL(request);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.setConnectTimeout(1000);
con.setReadTimeout(1000);
con.setRequestProperty(Constants.UPGRADE_CONTENT_TYPE, Constants.HTTP_RESPONSE);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
int status = con.getResponseCode();
in.close();
con.disconnect();
tcpResponse.setResponse(response.toString());
tcpResponse.setErrorCode(status);
CommonUtility.conditionedLog(Constants.TCP_CLIENT, CommonUtility.toJsonStringPrettyPrinted(tcpResponse));
return tcpResponse;
} catch (IOException e) {
log.error(e.getMessage());
}
return tcpResponse;
}
/**
* Send an HTTP GET to default device
*
* @param msg msg to use in the payload param
* @param topic http get path
* @return response
*/
@SuppressWarnings("UnusedReturnValue")
public static TcpResponse httpGet(String msg, String topic) {
TcpResponse tcpResponse = new TcpResponse();
if (CommonUtility.getDeviceToUse() != null && CommonUtility.getDeviceToUse().getDeviceIP() != null) {
tcpResponse = httpGet(msg, topic, CommonUtility.getDeviceToUse().getDeviceIP());
}
return tcpResponse;
}
}
|
package com.sunseagear.common.mvc.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.sunseagear.common.mvc.constant.DataBaseConstant;
import lombok.Data;
import java.util.Date;
/**
* 数据Entity类
*
* @param <ID> 主键类型
* @version 2016-12-03
*/
@Data
public abstract class DataEntity<ID> extends AbstractEntity<ID> {
private static final long serialVersionUID = 1L;
@TableField(value = "remarks")
protected String remarks; // 备注
@TableField(value = "create_by", fill = FieldFill.INSERT)
protected String createBy; // 创建者
@TableField(value = "create_date", fill = FieldFill.INSERT)
protected Date createDate; // 创建日期
@TableField(value = "update_by", fill = FieldFill.UPDATE)
protected String updateBy; // 更新者
@TableField(value = "update_date", fill = FieldFill.UPDATE)
protected Date updateDate; // 更新日期
@TableField(value = "del_flag", fill = FieldFill.INSERT)
protected String delFlag = "0"; // 删除标记(0:正常;1:删除 )
public DataEntity() {
super();
this.delFlag = DataBaseConstant.DEL_FLAG_NORMAL;
}
}
|
package tournament;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by jmontes on 4/3/16.
*/
@Controller
public class TournamentController {
@RequestMapping("/")
public ModelAndView root() {
ModelAndView mv = new ModelAndView("root");
return mv;
}
}
|
/*
* Copyright 1999-2011 Alibaba Group.
*
* 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.alibaba.dubbo.remoting.transport;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.Version;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.store.DataStore;
import com.alibaba.dubbo.common.utils.ExecutorUtil;
import com.alibaba.dubbo.common.utils.NamedThreadFactory;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.ChannelHandler;
import com.alibaba.dubbo.remoting.Client;
import com.alibaba.dubbo.remoting.RemotingException;
import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers;
/**
* AbstractClient
*
* @author qian.lei
* @author chao.liuc
*/
public abstract class AbstractClient extends AbstractEndpoint implements Client {
private static final Logger logger = LoggerFactory.getLogger(AbstractClient.class);
protected static final String CLIENT_THREAD_POOL_NAME = "DubboClientHandler";
private static final AtomicInteger CLIENT_THREAD_POOL_ID = new AtomicInteger();
private final Lock connectLock = new ReentrantLock();
private static final ScheduledThreadPoolExecutor reconnectExecutorService = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("DubboClientReconnectTimer", true));
private volatile ScheduledFuture<?> reconnectExecutorFuture = null;
protected volatile ExecutorService executor;
private final boolean send_reconnect;
private final AtomicInteger reconnect_count = new AtomicInteger(0);
//重连的error日志是否已经被调用过.
private final AtomicBoolean reconnect_error_log_flag = new AtomicBoolean(false);
//重连warning的间隔.(waring多少次之后,warning一次) //for test
private final int reconnect_warning_period;
//the last successed connected time
private long lastConnectedTime = System.currentTimeMillis();
private final long shutdown_timeout;
/**
* 网络框架无关的抽象客户端实现
*
* @param url 元信息
* @param handler 通道处理器
* @throws RemotingException 异常信息
*/
public AbstractClient(URL url, ChannelHandler handler) throws RemotingException {
super(url, handler);
//发送重连标志,默认为(send.reconnect:false)
send_reconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, false);
//断开超时时间,默认为(shutdown.timeout,15分钟)
shutdown_timeout = url.getParameter(Constants.SHUTDOWN_TIMEOUT_KEY, Constants.DEFAULT_SHUTDOWN_TIMEOUT);
//默认重连间隔2s,1800表示1小时warning一次.
reconnect_warning_period = url.getParameter("reconnect.waring.period", 1800);
try {
doOpen();
} catch (Throwable t) {
close();
throw new RemotingException(url.toInetSocketAddress(), null, "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
+ " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t);
}
try {
connect();
if (logger.isInfoEnabled()) {
logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress());
}
} catch (RemotingException t) {
if (url.getParameter(Constants.CHECK_KEY, true)) {
close();
throw t;
} else {
logger.warn("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
+ " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t);
}
} catch (Throwable t) {
close();
throw new RemotingException(url.toInetSocketAddress(), null, "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
+ " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t);
}
DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class)
.getDefaultExtension();
executor = (ExecutorService) dataStore.get(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()));
dataStore.remove(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()));
}
protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler) {
url = ExecutorUtil.setThreadName(url, CLIENT_THREAD_POOL_NAME);
url = url.addParameterIfAbsent(Constants.THREADPOOL_KEY, Constants.DEFAULT_CLIENT_THREADPOOL);
return ChannelHandlers.wrap(handler, url);
}
/**
* init reconnect thread
*/
private synchronized void initConnectStatusCheckCommand() {
//reconnect=false to close reconnect
int reconnect = getReconnectParam(getUrl());
if (reconnect > 0 && (reconnectExecutorFuture == null || reconnectExecutorFuture.isCancelled())) {
Runnable connectStatusCheckCommand = new Runnable() {
public void run() {
try {
if (!isConnected()) {
connect();
} else {
lastConnectedTime = System.currentTimeMillis();
}
} catch (Throwable t) {
String errorMsg = "client reconnect to " + getUrl().getAddress() + " find error . url: " + getUrl();
// wait registry sync provider list
if (System.currentTimeMillis() - lastConnectedTime > shutdown_timeout) {
if (!reconnect_error_log_flag.get()) {
reconnect_error_log_flag.set(true);
logger.error(errorMsg, t);
return;
}
}
if (reconnect_count.getAndIncrement() % reconnect_warning_period == 0) {
logger.warn(errorMsg, t);
}
}
}
};
reconnectExecutorFuture = reconnectExecutorService.scheduleWithFixedDelay(connectStatusCheckCommand, reconnect, reconnect, TimeUnit.MILLISECONDS);
}
}
/**
* @param url
* @return 0-false
*/
private static int getReconnectParam(URL url) {
int reconnect;
String param = url.getParameter(Constants.RECONNECT_KEY);
if (param == null || param.length() == 0 || "true".equalsIgnoreCase(param)) {
reconnect = Constants.DEFAULT_RECONNECT_PERIOD;
} else if ("false".equalsIgnoreCase(param)) {
reconnect = 0;
} else {
try {
reconnect = Integer.parseInt(param);
} catch (Exception e) {
throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:" + param);
}
if (reconnect < 0) {
throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:" + param);
}
}
return reconnect;
}
private synchronized void destroyConnectStatusCheckCommand() {
try {
if (reconnectExecutorFuture != null && !reconnectExecutorFuture.isDone()) {
reconnectExecutorFuture.cancel(true);
reconnectExecutorService.purge();
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
}
protected ExecutorService createExecutor() {
return Executors.newCachedThreadPool(new NamedThreadFactory(CLIENT_THREAD_POOL_NAME + CLIENT_THREAD_POOL_ID.incrementAndGet() + "-" + getUrl().getAddress(), true));
}
public InetSocketAddress getConnectAddress() {
return new InetSocketAddress(NetUtils.filterLocalHost(getUrl().getHost()), getUrl().getPort());
}
public InetSocketAddress getRemoteAddress() {
Channel channel = getChannel();
if (channel == null)
return getUrl().toInetSocketAddress();
return channel.getRemoteAddress();
}
public InetSocketAddress getLocalAddress() {
Channel channel = getChannel();
if (channel == null)
return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0);
return channel.getLocalAddress();
}
public boolean isConnected() {
Channel channel = getChannel();
if (channel == null)
return false;
return channel.isConnected();
}
public Object getAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
return null;
return channel.getAttribute(key);
}
public void setAttribute(String key, Object value) {
Channel channel = getChannel();
if (channel == null)
return;
channel.setAttribute(key, value);
}
public void removeAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
return;
channel.removeAttribute(key);
}
public boolean hasAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
return false;
return channel.hasAttribute(key);
}
/**
* 发送,回调子类的实现,来使用子类中持有的相关对象进行发送信息。
* 默认情况下是nettyClient,
* 这里的channel,默认对应了nettyChannel
* @param message
* @param sent 是否已发送完成
* @throws RemotingException
* @see #getChannel()
*/
public void send(Object message, boolean sent) throws RemotingException {
if (send_reconnect && !isConnected()) {
connect();
}
Channel channel = getChannel();
//TODO getChannel返回的状态是否包含null需要改进
if (channel == null || !channel.isConnected()) {
throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl());
}
channel.send(message, sent);
}
/**
* 进行网络连接
* @throws RemotingException 异常信息
*/
protected void connect() throws RemotingException {
connectLock.lock();
try {
if (isConnected()) {
return;
}
initConnectStatusCheckCommand();
doConnect();
if (!isConnected()) {
throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
+ ", cause: Connect wait timeout: " + getTimeout() + "ms.");
} else {
if (logger.isInfoEnabled()) {
logger.info("Successed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
+ ", channel is " + this.getChannel());
}
}
reconnect_count.set(0);
reconnect_error_log_flag.set(false);
} catch (RemotingException e) {
throw e;
} catch (Throwable e) {
throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
+ ", cause: " + e.getMessage(), e);
} finally {
connectLock.unlock();
}
}
/**
* 断开网络连接
*/
public void disconnect() {
connectLock.lock();
try {
destroyConnectStatusCheckCommand();
try {
Channel channel = getChannel();
if (channel != null) {
channel.close();
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
doDisConnect();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
} finally {
connectLock.unlock();
}
}
/**
* 重连
* @throws RemotingException 异常
* @see #disconnect()
* @see #connect()
*/
public void reconnect() throws RemotingException {
disconnect();
connect();
}
public void close() {
try {
if (executor != null) {
ExecutorUtil.shutdownNow(executor, 100);
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
super.close();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
disconnect();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
doClose();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
}
public void close(int timeout) {
ExecutorUtil.gracefulShutdown(executor, timeout);
close();
}
@Override
public String toString() {
return getClass().getName() + " [" + getLocalAddress() + " -> " + getRemoteAddress() + "]";
}
/**
* Open client.
*
* @throws Throwable
*/
protected abstract void doOpen() throws Throwable;
/**
* Close client.
*
* @throws Throwable
*/
protected abstract void doClose() throws Throwable;
/**
* Connect to server.
*
* @throws Throwable
*/
protected abstract void doConnect() throws Throwable;
/**
* disConnect to server.
*
* @throws Throwable
*/
protected abstract void doDisConnect() throws Throwable;
/**
* Get the connected channel.
*
* @return channel
*/
protected abstract Channel getChannel();
}
|
package sri.snippets.hackertests;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class TimeConversion
{
public static void main(String[] args) throws Exception
{
new TimeConversion().test1();
}
public void test1() throws Exception
{
Scanner scanner = new Scanner(System.in);
String inTime = scanner.next();
scanner.close();
inTime = inTime.substring(0, inTime.length()-2)
+ " "
+ inTime.substring(inTime.length()- 2, inTime.length());
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
Date date = parseFormat.parse(inTime);
System.out.println(displayFormat.format(date));
}
}
|
/* SPDX-License-Identifier: Apache-2.0 */
package io.openlineage.spark.agent.lifecycle.plan;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import io.openlineage.client.OpenLineage;
import io.openlineage.spark.agent.SparkAgentTestExtension;
import java.util.List;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.catalyst.TableIdentifier;
import org.apache.spark.sql.execution.command.DropTableCommand;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StringType$;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import scala.collection.Map$;
import scala.collection.immutable.HashMap;
@ExtendWith(SparkAgentTestExtension.class)
public class DropTableCommandVisitorTest {
SparkSession session;
DropTableCommandVisitor visitor;
DropTableCommand command;
String database;
TableIdentifier table = new TableIdentifier("drop_table");
@BeforeEach
public void setup() {
session =
SparkSession.builder()
.config("spark.sql.warehouse.dir", "/tmp/warehouse")
.master("local")
.getOrCreate();
database = session.catalog().currentDatabase();
command = new DropTableCommand(table, true, false, true);
visitor = new DropTableCommandVisitor(SparkAgentTestExtension.newContext(session));
}
@AfterEach
public void afterEach() {
session.sessionState().catalog().dropTable(table, true, true);
}
@Test
public void testDropTableCommandWhenTableDoesNotExist() {
// make sure table does not exist
session.sessionState().catalog().dropTable(table, true, true);
command.run(session);
assertThat(visitor.isDefinedAt(command)).isTrue();
List<OpenLineage.OutputDataset> datasets = visitor.apply(command);
assertThat(datasets).isEmpty();
}
@Test
public void testDropCommand() {
// create some other table first
StructType schema =
new StructType(
new StructField[] {
new StructField("field1", StringType$.MODULE$, false, new Metadata(new HashMap<>()))
});
session.catalog().createTable("drop_table", "csv", schema, Map$.MODULE$.empty());
// apply the visitor before running the command
List<OpenLineage.OutputDataset> datasets = visitor.apply(command);
assertEquals(null, datasets.get(0).getFacets().getSchema());
assertThat(datasets)
.singleElement()
.hasFieldOrPropertyWithValue("name", "/tmp/warehouse/drop_table")
.hasFieldOrPropertyWithValue("namespace", "file");
assertThat(
datasets
.get(0)
.getFacets()
.getLifecycleStateChange()
.getLifecycleStateChange()
.equals(OpenLineage.LifecycleStateChangeDatasetFacet.LifecycleStateChange.DROP));
}
}
|
/*
* Copyright (c) 2003, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package jakarta.xml.bind.util;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.XMLFilterImpl;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.XMLFilter;
/**
* JAXP {@link javax.xml.transform.Source} implementation
* that marshals a Jakarta XML Binding-generated object.
*
* <p>
* This utility class is useful to combine Jakarta XML Binding with
* other Java/XML technologies.
*
* <p>
* The following example shows how to use Jakarta XML Binding to marshal a document
* for transformation by XSLT.
*
* <blockquote>
* <pre>
* MyObject o = // get JAXB content tree
*
* // jaxbContext is a JAXBContext object from which 'o' is created.
* JAXBSource source = new JAXBSource( jaxbContext, o );
*
* // set up XSLT transformation
* TransformerFactory tf = TransformerFactory.newInstance();
* Transformer t = tf.newTransformer(new StreamSource("test.xsl"));
*
* // run transformation
* t.transform(source,new StreamResult(System.out));
* </pre>
* </blockquote>
*
* <p>
* The fact that JAXBSource derives from SAXSource is an implementation
* detail. Thus in general applications are strongly discouraged from
* accessing methods defined on SAXSource. In particular,
* the setXMLReader and setInputSource methods shall never be called.
* The XMLReader object obtained by the getXMLReader method shall
* be used only for parsing the InputSource object returned by
* the getInputSource method.
*
* <p>
* Similarly the InputSource object obtained by the getInputSource
* method shall be used only for being parsed by the XMLReader object
* returned by the getXMLReader.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
* @since 1.6
*/
public class JAXBSource extends SAXSource {
/**
* Creates a new {@link javax.xml.transform.Source} for the given content object.
*
* @param context
* JAXBContext that was used to create
* <code>contentObject</code>. This context is used
* to create a new instance of marshaller and must not be null.
* @param contentObject
* An instance of a Jakarta XML Binding-generated class, which will be
* used as a {@link javax.xml.transform.Source} (by marshalling it into XML). It must
* not be null.
* @throws JAXBException if an error is encountered while creating the
* JAXBSource or if either of the parameters are null.
*/
public JAXBSource( JAXBContext context, Object contentObject )
throws JAXBException {
this(
( context == null ) ?
assertionFailed( Messages.format( Messages.SOURCE_NULL_CONTEXT ) ) :
context.createMarshaller(),
( contentObject == null ) ?
assertionFailed( Messages.format( Messages.SOURCE_NULL_CONTENT ) ) :
contentObject);
}
/**
* Creates a new {@link javax.xml.transform.Source} for the given content object.
*
* @param marshaller
* A marshaller instance that will be used to marshal
* <code>contentObject</code> into XML. This must be
* created from a JAXBContext that was used to build
* <code>contentObject</code> and must not be null.
* @param contentObject
* An instance of a Jakarta XML Binding-generated class, which will be
* used as a {@link javax.xml.transform.Source} (by marshalling it into XML). It must
* not be null.
* @throws JAXBException if an error is encountered while creating the
* JAXBSource or if either of the parameters are null.
*/
public JAXBSource( Marshaller marshaller, Object contentObject )
throws JAXBException {
if( marshaller == null )
throw new JAXBException(
Messages.format( Messages.SOURCE_NULL_MARSHALLER ) );
if( contentObject == null )
throw new JAXBException(
Messages.format( Messages.SOURCE_NULL_CONTENT ) );
this.marshaller = marshaller;
this.contentObject = contentObject;
super.setXMLReader(pseudoParser);
// pass a dummy InputSource. We don't care
super.setInputSource(new InputSource());
}
private final Marshaller marshaller;
private final Object contentObject;
// this object will pretend as an XMLReader.
// no matter what parameter is specified to the parse method,
// it just parse the contentObject.
private final XMLReader pseudoParser = new XMLReader() {
public boolean getFeature(String name) throws SAXNotRecognizedException {
if(name.equals("http://xml.org/sax/features/namespaces"))
return true;
if(name.equals("http://xml.org/sax/features/namespace-prefixes"))
return false;
throw new SAXNotRecognizedException(name);
}
public void setFeature(String name, boolean value) throws SAXNotRecognizedException {
if(name.equals("http://xml.org/sax/features/namespaces") && value)
return;
if(name.equals("http://xml.org/sax/features/namespace-prefixes") && !value)
return;
throw new SAXNotRecognizedException(name);
}
public Object getProperty(String name) throws SAXNotRecognizedException {
if( "http://xml.org/sax/properties/lexical-handler".equals(name) ) {
return lexicalHandler;
}
throw new SAXNotRecognizedException(name);
}
public void setProperty(String name, Object value) throws SAXNotRecognizedException {
if( "http://xml.org/sax/properties/lexical-handler".equals(name) ) {
this.lexicalHandler = (LexicalHandler)value;
return;
}
throw new SAXNotRecognizedException(name);
}
private LexicalHandler lexicalHandler;
// we will store this value but never use it by ourselves.
private EntityResolver entityResolver;
public void setEntityResolver(EntityResolver resolver) {
this.entityResolver = resolver;
}
public EntityResolver getEntityResolver() {
return entityResolver;
}
private DTDHandler dtdHandler;
public void setDTDHandler(DTDHandler handler) {
this.dtdHandler = handler;
}
public DTDHandler getDTDHandler() {
return dtdHandler;
}
// SAX allows ContentHandler to be changed during the parsing,
// but JAXB doesn't. So this repeater will sit between those
// two components.
private XMLFilter repeater = new XMLFilterImpl();
public void setContentHandler(ContentHandler handler) {
repeater.setContentHandler(handler);
}
public ContentHandler getContentHandler() {
return repeater.getContentHandler();
}
private ErrorHandler errorHandler;
public void setErrorHandler(ErrorHandler handler) {
this.errorHandler = handler;
}
public ErrorHandler getErrorHandler() {
return errorHandler;
}
public void parse(InputSource input) throws SAXException {
parse();
}
public void parse(String systemId) throws SAXException {
parse();
}
public void parse() throws SAXException {
// parses a content object by using the given marshaller
// SAX events will be sent to the repeater, and the repeater
// will further forward it to an appropriate component.
try {
marshaller.marshal( contentObject, (XMLFilterImpl)repeater );
} catch( JAXBException e ) {
// wrap it to a SAXException
SAXParseException se =
new SAXParseException( e.getMessage(),
null, null, -1, -1, e );
// if the consumer sets an error handler, it is our responsibility
// to notify it.
if(errorHandler!=null)
errorHandler.fatalError(se);
// this is a fatal error. Even if the error handler
// returns, we will abort anyway.
throw se;
}
}
};
/**
* Hook to throw exception from the middle of a contructor chained call
* to this
*/
private static Marshaller assertionFailed( String message )
throws JAXBException {
throw new JAXBException( message );
}
}
|
package com.pjzhong.leetcode;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1,
which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1] .
Example 2:
Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both
courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
https://leetcode.com/problems/course-schedule-ii/description/
* */
public class CourseScheduleII {
@Test
public void test() {
int[][][] testCases = {
{{1,0}},
{{1,0}, {2, 0}, {3,1}, {3,2}},
{},
};
int[] edges = {2, 4, 1};
for(int i = 0; i < edges.length; i++) {
System.out.println(Arrays.toString(findOrder(edges[i], testCases[i])));
}
}
private boolean hasCycle = false;
boolean[] onStack;
boolean[] marked;
public int[] findOrder(int numCourses, int[][] prerequisites) {
onStack = new boolean[numCourses];
marked = new boolean[numCourses];
List<Integer>[] adjacent = new List[numCourses];
for(int[] adj : prerequisites) {
if(adjacent[adj[0]] == null) {adjacent[adj[0]] = new ArrayList<>();}
adjacent[adj[0]].add(adj[1]);
}
List<Integer> course = new ArrayList<>();
for(int i = 0; i < numCourses; i++) {
if(!marked[i] && !hasCycle) {
dfs(adjacent, course, i);
}
}
int[] result = new int[hasCycle ? 0 : numCourses];
if(!hasCycle) {
for(int i = 0; i < numCourses; i++) {
result[i] = course.get(i);
}
}
return result;
}
public void dfs(List<Integer>[] adjacent, List<Integer> result, int f) {
marked[f] = onStack[f] = true;
if(adjacent[f] != null) {
for(int t : adjacent[f]) {
if(hasCycle) { return;}
else if(!marked[t]) {
dfs(adjacent, result, t);
} else if(onStack[t]) { hasCycle = true;}
}
}
result.add(f);
onStack[f] = false;
}
}
|
// Targeted by JavaCPP version 1.5.4-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.arrow_flight;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import org.bytedeco.arrow.*;
import static org.bytedeco.arrow.global.arrow.*;
import static org.bytedeco.arrow.global.arrow_flight.*;
/** \brief A RecordBatchReader exposing Flight metadata and cancel
* operations. */
@Namespace("arrow::flight") @Properties(inherit = org.bytedeco.arrow.presets.arrow_flight.class)
public class FlightStreamReader extends MetadataRecordBatchReader {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public FlightStreamReader(Pointer p) { super(p); }
/** \brief Try to cancel the call. */
public native void Cancel();
}
|
/**
* Copyright (C) 2014-2021 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.commons.locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import java.util.Locale;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.junit.DebugModeTestRule;
import com.helger.commons.system.SystemHelper;
/**
* Test class for class {@link LocaleHelper}.
*
* @author Philip Helger
*/
public final class LocaleHelperTest
{
private static final Locale L_DE = new Locale ("de");
private static final Locale L_EN = new Locale ("en");
private static final Locale L_DE_AT = new Locale ("de", "AT");
private static final Locale L_FR = new Locale ("fr");
private static final Locale L_FR_FR = new Locale ("fr", "FR");
@Rule
public final TestRule m_aRule = new DebugModeTestRule ();
@Test
public void testGetLocaleDisplayName ()
{
assertNotNull (LocaleHelper.getLocaleDisplayName (null, L_DE));
assertNotNull (LocaleHelper.getLocaleDisplayName (LocaleHelper.LOCALE_ALL, L_DE));
assertNotNull (LocaleHelper.getLocaleDisplayName (LocaleHelper.LOCALE_INDEPENDENT, L_DE));
assertNotNull (LocaleHelper.getLocaleDisplayName (L_DE, L_DE));
}
@Test
public void testGetLocaleNativeDisplayName ()
{
assertNull (LocaleHelper.getLocaleNativeDisplayName (LocaleHelper.LOCALE_ALL));
assertNull (LocaleHelper.getLocaleNativeDisplayName (LocaleHelper.LOCALE_INDEPENDENT));
assertNotNull (LocaleHelper.getLocaleNativeDisplayName (L_DE));
try
{
LocaleHelper.getLocaleNativeDisplayName (null);
fail ();
}
catch (final NullPointerException ex)
{}
}
@Test
public void testGetAllLocaleDisplayNames ()
{
assertNotNull (LocaleHelper.getAllLocaleDisplayNames (LocaleCache.getInstance ().getLocale ("de")));
assertFalse (LocaleHelper.getAllLocaleDisplayNames (LocaleCache.getInstance ().getLocale ("de")).isEmpty ());
}
@Test
public void testGetCalculatedLocaleListForResolving ()
{
try
{
LocaleHelper.getCalculatedLocaleListForResolving (null);
fail ();
}
catch (final NullPointerException ex)
{}
// Neither language, country not variant
List <Locale> aList = LocaleHelper.getCalculatedLocaleListForResolving (new Locale (""));
assertNotNull (aList);
assertEquals (0, aList.size ());
// Only the language
aList = LocaleHelper.getCalculatedLocaleListForResolving (LocaleCache.getInstance ().getLocale ("de"));
assertNotNull (aList);
assertEquals (1, aList.size ());
assertEquals (LocaleCache.getInstance ().getLocale ("de"), aList.get (0));
// Language + country
aList = LocaleHelper.getCalculatedLocaleListForResolving (LocaleCache.getInstance ().getLocale ("de", "AT"));
assertNotNull (aList);
assertEquals (2, aList.size ());
assertEquals (LocaleCache.getInstance ().getLocale ("de", "AT"), aList.get (0));
assertEquals (LocaleCache.getInstance ().getLocale ("de"), aList.get (1));
// Language + country + Variant
aList = LocaleHelper.getCalculatedLocaleListForResolving (LocaleCache.getInstance ().getLocale ("de", "AT", "Wien"));
assertNotNull (aList);
assertEquals (3, aList.size ());
assertEquals (LocaleCache.getInstance ().getLocale ("de", "AT", "Wien"), aList.get (0));
assertEquals (LocaleCache.getInstance ().getLocale ("de", "AT"), aList.get (1));
assertEquals (LocaleCache.getInstance ().getLocale ("de"), aList.get (2));
// No language - only country
aList = LocaleHelper.getCalculatedLocaleListForResolving (new Locale ("", "AT"));
assertNotNull (aList);
assertEquals (0, aList.size ());
// No language - only country + variant
aList = LocaleHelper.getCalculatedLocaleListForResolving (new Locale ("", "AT", "Wien"));
assertNotNull (aList);
assertEquals (0, aList.size ());
}
@Test
public void testGetLocaleFromString ()
{
assertEquals (SystemHelper.getSystemLocale (), LocaleHelper.getLocaleFromString (""));
assertEquals (LocaleCache.getInstance ().getLocale ("de"), LocaleHelper.getLocaleFromString ("de"));
assertEquals (LocaleCache.getInstance ().getLocale ("de"), LocaleHelper.getLocaleFromString ("DE"));
assertEquals (LocaleCache.getInstance ().getLocale ("de", "AT"), LocaleHelper.getLocaleFromString ("de_AT"));
assertEquals (LocaleCache.getInstance ().getLocale ("de", "AT"), LocaleHelper.getLocaleFromString ("de_at"));
assertEquals (LocaleCache.getInstance ().getLocale ("de", "AT"), LocaleHelper.getLocaleFromString ("de_at"));
// only variant is not allowed!
assertEquals (LocaleCache.getInstance ().getLocale ("", "", ""), LocaleHelper.getLocaleFromString ("__wien"));
assertEquals (LocaleCache.getInstance ().getLocale ("de", "AT", "WIEN"), LocaleHelper.getLocaleFromString ("de_at_wien"));
assertEquals (LocaleCache.getInstance ().getLocale ("de", "", "WIEN"), LocaleHelper.getLocaleFromString ("de__wien"));
assertEquals (LocaleCache.getInstance ().getLocale ("", "AT", "WIEN"), LocaleHelper.getLocaleFromString ("_at_wien"));
assertEquals (LocaleCache.getInstance ().getLocale ("", "AT", "WIEN"), LocaleHelper.getLocaleFromString ("dee_at_wien"));
assertEquals (LocaleCache.getInstance ().getLocale ("de", "", "WIEN"), LocaleHelper.getLocaleFromString ("de_att_wien"));
}
@Test
public void testGetLocaleToUseOrFallback ()
{
final ICommonsList <Locale> aLocales = new CommonsArrayList <> (L_DE, L_EN, LocaleHelper.LOCALE_ALL);
try
{
LocaleHelper.getLocaleToUseOrFallback (null, aLocales, null);
fail ();
}
catch (final NullPointerException ex)
{}
try
{
LocaleHelper.getLocaleToUseOrFallback (L_DE, null, null);
fail ();
}
catch (final NullPointerException ex)
{}
assertSame (L_DE, LocaleHelper.getLocaleToUseOrFallback (L_DE, aLocales, null));
assertEquals (L_DE, LocaleHelper.getLocaleToUseOrFallback (L_DE_AT, aLocales, null));
assertEquals (LocaleHelper.LOCALE_ALL, LocaleHelper.getLocaleToUseOrFallback (L_FR, aLocales, null));
assertEquals (LocaleHelper.LOCALE_ALL, LocaleHelper.getLocaleToUseOrFallback (LocaleHelper.LOCALE_INDEPENDENT, aLocales, null));
assertEquals (LocaleHelper.LOCALE_INDEPENDENT,
LocaleHelper.getLocaleToUseOrFallback (L_FR, new CommonsArrayList <> (LocaleHelper.LOCALE_INDEPENDENT), null));
assertNull (LocaleHelper.getLocaleToUseOrFallback (L_FR, new CommonsArrayList <> (L_DE, L_EN), null));
assertEquals (L_FR_FR, LocaleHelper.getLocaleToUseOrFallback (L_FR, new CommonsArrayList <> (L_DE, L_EN), L_FR_FR));
assertEquals (L_FR_FR, LocaleHelper.getLocaleToUseOrFallback (L_FR, new CommonsArrayList <> (L_FR_FR), null));
}
@Test
public void testIsSpecialLocale ()
{
assertTrue (LocaleHelper.isSpecialLocale (LocaleHelper.LOCALE_ALL));
assertTrue (LocaleHelper.isSpecialLocale (LocaleHelper.LOCALE_INDEPENDENT));
assertFalse (LocaleHelper.isSpecialLocale (null));
assertFalse (LocaleHelper.isSpecialLocale (LocaleCache.getInstance ().getLocale ("de")));
}
@Test
public void testIsSpecialLocaleCode ()
{
assertTrue (LocaleHelper.isSpecialLocaleCode (LocaleHelper.LOCALE_ALL.toString ()));
assertTrue (LocaleHelper.isSpecialLocaleCode (LocaleHelper.LOCALE_INDEPENDENT.toString ()));
assertFalse (LocaleHelper.isSpecialLocaleCode (null));
assertFalse (LocaleHelper.isSpecialLocaleCode ("de"));
}
@Test
public void testGetValidLanguageCode ()
{
assertNull (LocaleHelper.getValidLanguageCode (null));
assertNull (LocaleHelper.getValidLanguageCode (""));
assertNull (LocaleHelper.getValidLanguageCode ("1"));
assertNull (LocaleHelper.getValidLanguageCode ("a"));
assertNull (LocaleHelper.getValidLanguageCode (" "));
assertNull (LocaleHelper.getValidLanguageCode ("_"));
assertNull (LocaleHelper.getValidLanguageCode ("_de"));
assertNull (LocaleHelper.getValidLanguageCode ("d.e"));
assertNull (LocaleHelper.getValidLanguageCode ("d e"));
assertNull (LocaleHelper.getValidLanguageCode ("abcdefghi"));
assertEquals ("de", LocaleHelper.getValidLanguageCode ("De"));
assertEquals ("abc", LocaleHelper.getValidLanguageCode ("ABC"));
assertEquals ("en", LocaleHelper.getValidLanguageCode ("en"));
assertEquals ("abcdefgh", LocaleHelper.getValidLanguageCode ("abcDefgh"));
}
@Test
public void testGetValidCountryCode ()
{
assertNull (LocaleHelper.getValidCountryCode (null));
assertNull (LocaleHelper.getValidCountryCode (""));
assertNull (LocaleHelper.getValidCountryCode ("1"));
assertNull (LocaleHelper.getValidCountryCode ("12"));
assertNull (LocaleHelper.getValidCountryCode ("a"));
assertNull (LocaleHelper.getValidCountryCode (" "));
assertNull (LocaleHelper.getValidCountryCode ("_"));
assertNull (LocaleHelper.getValidCountryCode ("_de"));
assertNull (LocaleHelper.getValidCountryCode ("d.e"));
assertNull (LocaleHelper.getValidCountryCode ("d e"));
// Because Alpha3
assertNotNull (LocaleHelper.getValidCountryCode ("abc"));
assertNull (LocaleHelper.getValidCountryCode ("abcd"));
assertNull (LocaleHelper.getValidCountryCode ("1234"));
assertEquals ("DE", LocaleHelper.getValidCountryCode ("De"));
assertEquals ("123", LocaleHelper.getValidCountryCode ("123"));
assertEquals ("EN", LocaleHelper.getValidCountryCode ("en"));
}
}
|
package com.github.zuihou.authority.dto.auth;
import java.io.Serializable;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.github.zuihou.authority.enumeration.auth.TargetType;
import com.github.zuihou.base.entity.SuperEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.hibernate.validator.constraints.Length;
/**
* <p>
* 实体类
* 菜单
* </p>
*
* @author zuihou
* @since 2019-07-27
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = false)
@Builder
@ApiModel(value = "MenuUpdateDTO", description = "菜单")
public class MenuUpdateDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键")
@NotNull(message = "id不能为空", groups = SuperEntity.Update.class)
private Long id;
/**
* 菜单名称
*/
@ApiModelProperty(value = "菜单名称")
@NotEmpty(message = "菜单名称不能为空")
@Length(max = 20, message = "菜单名称长度不能超过20")
private String name;
/**
* 功能描述
*/
@ApiModelProperty(value = "功能描述")
@Length(max = 200, message = "功能描述长度不能超过200")
private String describe;
/**
* 是否公开菜单
* 就是无需分配就可以访问的。所有人可见
*/
@ApiModelProperty(value = "是否公开菜单")
private Boolean isPublic;
/**
* 资源路径
*/
@ApiModelProperty(value = "资源路径")
@Length(max = 255, message = "资源路径长度不能超过255")
private String href;
/**
* 打开方式
* #TargetType{SELF:_self,相同框架;TOP:_top,当前页;BLANK:_blank,新建窗口;PAREN:_parent,父窗口}
*/
@ApiModelProperty(value = "打开方式")
private TargetType target;
/**
* 是否启用
*/
@ApiModelProperty(value = "是否启用")
private Boolean isEnable;
/**
* 排序
*/
@ApiModelProperty(value = "排序")
private Integer sortValue;
/**
* 菜单图标
*/
@ApiModelProperty(value = "菜单图标")
@Length(max = 255, message = "菜单图标长度不能超过255")
private String icon;
/**
* 菜单分组
*/
@ApiModelProperty(value = "菜单分组")
@Length(max = 20, message = "菜单分组长度不能超过20")
private String group;
/**
* 父级菜单id
*/
@ApiModelProperty(value = "父级菜单id")
private Long parentId;
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.component.cxf.jaxrs.testbean
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|cxf
operator|.
name|jaxrs
operator|.
name|testbean
package|;
end_package
begin_comment
comment|// START SNIPPET: example
end_comment
begin_interface
DECL|interface|CustomerServiceNoAnnotations
specifier|public
interface|interface
name|CustomerServiceNoAnnotations
block|{
DECL|method|getCustomer (String id)
name|Customer
name|getCustomer
parameter_list|(
name|String
name|id
parameter_list|)
function_decl|;
block|}
end_interface
begin_comment
comment|// END SNIPPET: example
end_comment
end_unit
|
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
package gov.nist.javax.sip.stack;
import gov.nist.core.CommonLogger;
import gov.nist.core.LogWriter;
import gov.nist.core.StackLogger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.Queue;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
/**
* This is a helper state machine that negotiates the SSL connection automatically
* without ever blocking any threads. It is important not to block here because
* the TLS may occur in the selector thread which is one per all sockets.
*
* Other than that the state machine is able to handle partial chunks of SIP messages
* and only supply them when they are ready to the original TCP channel once they are
* decrypted.
*
* @author vladimirralev
*
*/
public class SSLStateMachine {
private static StackLogger logger = CommonLogger.getLogger(SSLStateMachine.class);
public final static ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[] {});
protected SSLEngine sslEngine;
protected Queue<MessageSendItem> pendingOutboundBuffers =
new LinkedList<MessageSendItem>();
protected NioTlsChannelInterface channel;
protected ByteBuffer tlsRecordBuffer;
private Object unwrapLock = new Object();
private Object wrapLock = new Object();
public SSLStateMachine(SSLEngine sslEngine, NioTlsChannelInterface channel) {
this.sslEngine = sslEngine;
this.channel = channel;
}
public void wrapRemaining() throws IOException {
wrap(null, channel.prepareEncryptedDataBuffer(), null);
}
public void wrap(ByteBuffer src, ByteBuffer dst,
MessageSendCallback callback) throws IOException {
synchronized (wrapLock) {
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Wrapping " + src + ", buffers size " + pendingOutboundBuffers.size());
}
// Null src means we just have no ne data but still want to push any previously queued data
if(src != null) {
pendingOutboundBuffers.offer(new MessageSendItem(src, callback));
}
int iter = 0;
loop:while(true) {
iter ++;
MessageSendItem currentBuffer = pendingOutboundBuffers.peek();
// If there is no queued operations break out of the loop
if(currentBuffer == null) break;
SSLEngineResult result;
try {
result = sslEngine.wrap(currentBuffer.message, dst);
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Wrap result " + result + " buffers size " + pendingOutboundBuffers.size());
}
} finally {
if(!currentBuffer.message.hasRemaining()) {
pendingOutboundBuffers.remove();
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("REMOVED item from encryption queue because it has no more data, all is done, buffers size now is "
+ pendingOutboundBuffers.size() + " current buffer is " + currentBuffer);
}
}
}
int remaining = currentBuffer.message.remaining();
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Remaining " + remaining + " queue size is " + pendingOutboundBuffers.size());
}
if(result.bytesProduced() > 0) {
// produced > 0 means encryption was successful and we have something to send over the wire
dst.flip();
byte[] bytes = new byte[dst.remaining()];
dst.get(bytes);
if(currentBuffer.getCallBack() != null) {
// Send using message channel (it discriminates between client/server and new/old connecitons)
currentBuffer.getCallBack().doSend(bytes);
} else {
// Send using the existing connection without attempting to guess client or server etc
sendSSLMetadata(bytes);
}
dst.clear();
} else {
switch (result.getHandshakeStatus()) {
case NEED_WRAP:
if (currentBuffer.message.hasRemaining()) {
break;
} else {
break loop;
}
case NEED_UNWRAP:
break loop;
case NEED_TASK:
runDelegatedTasks(result);
break;
case FINISHED:
// Added for https://java.net/jira/browse/JSIP-483
if(channel instanceof NioTlsMessageChannel) {
((NioTlsMessageChannel)channel).setHandshakeCompleted(true);
if(sslEngine.getSession() != null) {
if(!ClientAuthType.Disabled.equals(channel.getSIPStack().getClientAuth()) && !ClientAuthType.DisabledAll.equals(channel.getSIPStack().getClientAuth())) {
// https://java.net/jira/browse/JSIP-483 Don't try to get the PeerCertificates if the client auth is Disabled or DisabledAll as they won't be available
try {
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setPeerCertificates(sslEngine.getSession().getPeerCertificates());
} catch (SSLPeerUnverifiedException e) {
// no op if -Dgov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE=Disabled is used, no peer certificates will be available
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("sslEngine.getSession().getPeerCertificates() are not available, which is normal if running with gov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE=Disabled");
}
}
}
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setLocalCertificates(sslEngine.getSession().getLocalCertificates());
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setCipherSuite(sslEngine.getSession().getCipherSuite());
}
}
break;
case NOT_HANDSHAKING:
break loop;
default:
break;
}
}
}
}
}
private void wrapNonAppData() throws Exception {
ByteBuffer encryptedDataBuffer = channel.prepareEncryptedDataBuffer();
SSLEngineResult result;
try {
loop:while(true) {
result = sslEngine.wrap(EMPTY_BUFFER, encryptedDataBuffer);
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("NonAppWrap result " + result + " buffers size "
+ pendingOutboundBuffers.size());
}
if (result.bytesProduced() > 0) {
// any output here is internal TLS metadata such as handshakes
encryptedDataBuffer.flip();
byte[] msg = new byte[encryptedDataBuffer.remaining()];
encryptedDataBuffer.get(msg);
// send it directly over the wire without further processing or parsing
sendSSLMetadata(msg);
encryptedDataBuffer.clear();
}
switch (result.getHandshakeStatus()) {
case FINISHED:
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Handshake complete!");
}
// Added for https://java.net/jira/browse/JSIP-483
if(channel instanceof NioTlsMessageChannel) {
((NioTlsMessageChannel)channel).setHandshakeCompleted(true);
if(sslEngine.getSession() != null) {
if(!ClientAuthType.Disabled.equals(channel.getSIPStack().getClientAuth()) && !ClientAuthType.DisabledAll.equals(channel.getSIPStack().getClientAuth())) {
// https://java.net/jira/browse/JSIP-483 Don't try to get the PeerCertificates if the client auth is Disabled or DisabledAll as they won't be available
try {
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setPeerCertificates(sslEngine.getSession().getPeerCertificates());
} catch (SSLPeerUnverifiedException e) {
// no op if -Dgov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE=Disabled is used, no peer certificates will be available
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("sslEngine.getSession().getPeerCertificates() are not available, which is normal if running with gov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE=Disabled");
}
}
}
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setLocalCertificates(sslEngine.getSession().getLocalCertificates());
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setCipherSuite(sslEngine.getSession().getCipherSuite());
}
}
break;
case NEED_TASK:
runDelegatedTasks(result);
break;
}
if (result.bytesProduced() == 0) {
break;
}
}
} catch (SSLException e) {
throw e;
} finally {
}
}
public void unwrap(ByteBuffer src) throws Exception {
ByteBuffer outputBuffer = channel.prepareAppDataBuffer();
unwrap(src, outputBuffer);
}
private void startBuffer(ByteBuffer src) {
if(tlsRecordBuffer == null) {
// Begin buffering, if there is already a buffer the normalization will take of adding the bytes
tlsRecordBuffer = ByteBufferFactory.getInstance().allocateDirect(33270); // max record size in other implementations
// Append the current buffer
tlsRecordBuffer.put(src);
// Prepare the buffer for reading
tlsRecordBuffer.flip();
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Allocated record buffer for reading " + tlsRecordBuffer + " for src = " + src);
}
}
}
private void clearBuffer() {
tlsRecordBuffer = null;
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Buffer cleared");
}
}
private ByteBuffer normalizeTlsRecordBuffer(ByteBuffer src) {
if(tlsRecordBuffer == null) {
return src;
} else {
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Normalize buffer " + src + " into record buffer "
+ tlsRecordBuffer);
}
// Reverse flip() to prepare the buffer to writing in append mode
tlsRecordBuffer.position(tlsRecordBuffer.limit());
tlsRecordBuffer.limit(tlsRecordBuffer.capacity());
// Append data
tlsRecordBuffer.put(src);
// And prepare it for reading again as if it came from the network
tlsRecordBuffer.flip();
return tlsRecordBuffer;
}
}
private void unwrap(ByteBuffer src, ByteBuffer dst) throws Exception {
synchronized (unwrapLock) {
loop:while(true) {
src = normalizeTlsRecordBuffer(src);
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Unwrap src " + src + " dst "
+ dst);
}
SSLEngineResult result = null;
try {
result = sslEngine.unwrap(src, dst);
} catch (Exception e) {
// https://java.net/jira/browse/JSIP-464
// Make sure to throw the exception so the result variable is not null below which makes the stack hang
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("A problem occured while trying to unwrap the message " + e.getMessage());
}
throw e;
}
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Unwrap result " + result + " buffers size "
+ pendingOutboundBuffers.size() + " src=" + src + " dst=" + dst);
}
if(result.getStatus().equals(Status.BUFFER_UNDERFLOW)) {
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Buffer underflow, wait for the next inbound chunk of data to feed the SSL engine");
}
startBuffer(src);
break;
} else {
clearBuffer();
}
if(result.getStatus().equals(Status.BUFFER_OVERFLOW)) {
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Buffer overflow , must prepare the buffer again."
+ " outNetBuffer remaining: " + dst.remaining()
+ " outNetBuffer postion: " + dst.position()
+ " Packet buffer size: " + sslEngine.getSession().getPacketBufferSize()
+ " new buffer size: " + sslEngine.getSession().getPacketBufferSize() + dst.position());
}
ByteBuffer newBuf = channel.prepareAppDataBuffer(sslEngine.getSession().getPacketBufferSize());
dst = newBuf;
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(" new outNetBuffer remaining: " + dst.remaining()
+ " new outNetBuffer postion: " + dst.position());
}
continue;
}
if(result.bytesProduced()>0) {
// There is actual application data in this chunk
dst.flip();
byte[] a = new byte[dst.remaining()];
dst.get(a);
// take it and feed the plain text to out chunk-by-chunk parser
channel.addPlaintextBytes(a);
}
switch(result.getHandshakeStatus()) {
case NEED_UNWRAP:
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Unwrap has remaining: " + src.hasRemaining() + " buffer " + src);
}
if(src.hasRemaining()) {
break;
} else {
break loop;
}
case NEED_WRAP:
wrapNonAppData();
break;
case NEED_TASK:
runDelegatedTasks(result);
break;
case FINISHED:
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Handshaking just finnished, but has remaining. Will try to wrap the queues app items.");
}
wrapRemaining();
if(src.hasRemaining()) {
break;
} else {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
this.logger.logDebug(
"Handshake passed");
}
// Added for https://java.net/jira/browse/JSIP-483
// allow application to enforce policy by validating the
// certificate
if(channel instanceof NioTlsMessageChannel) {
((NioTlsMessageChannel)channel).setHandshakeCompleted(true);
if(sslEngine.getSession() != null) {
if(!ClientAuthType.Disabled.equals(channel.getSIPStack().getClientAuth()) && !ClientAuthType.DisabledAll.equals(channel.getSIPStack().getClientAuth())) {
// https://java.net/jira/browse/JSIP-483 Don't try to get the PeerCertificates if the client auth is Disabled or DisabledAll as they won't be available
try {
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setPeerCertificates(sslEngine.getSession().getPeerCertificates());
} catch (SSLPeerUnverifiedException e) {
// no op if -Dgov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE=Disabled is used, no peer certificates will be available
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("sslEngine.getSession().getPeerCertificates() are not available, which is normal if running with gov.nist.javax.sip.TLS_CLIENT_AUTH_TYPE=Disabled");
}
}
}
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setLocalCertificates(sslEngine.getSession().getLocalCertificates());
((NioTlsMessageChannel)channel).getHandshakeCompletedListener().setCipherSuite(sslEngine.getSession().getCipherSuite());
}
try {
channel.getSIPStack()
.getTlsSecurityPolicy()
.enforceTlsPolicy(
channel
.getEncapsulatedClientTransaction());
} catch (SecurityException ex) {
throw new IOException(ex.getMessage());
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
this.logger.logDebug(
"TLS Security policy passed");
}
}
break loop;
}
case NOT_HANDSHAKING:
wrapRemaining();
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Not handshaking, but has remaining: " + src.hasRemaining() + " buffer " + src);
}
if(src.hasRemaining()) {
break;
} else {
break loop;
}
default:
break;
}
}
}
}
private void runDelegatedTasks(SSLEngineResult result) throws IOException {
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Running delegated task for " + result);
}
/*
* Delegated tasks are just invisible steps inside the sslEngine state machine.
* Call them every time they have NEED_TASK otherwise the sslEngine won't make progress
*/
if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
Runnable runnable;
while ((runnable = sslEngine.getDelegatedTask()) != null) {
runnable.run();
}
HandshakeStatus hsStatus = sslEngine.getHandshakeStatus();
if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Handshake status after delegated tasks " + hsStatus);
}
if (hsStatus == HandshakeStatus.NEED_TASK) {
throw new IOException(
"handshake shouldn't need additional tasks");
}
}
}
public void sendSSLMetadata(byte[] msg) throws IOException {
channel.sendEncryptedData(msg);
}
public static interface MessageSendCallback {
public void doSend(byte[] bytes) throws IOException;
}
/**
* Each time we send a SIP message it will be associated with the originating channel.send() method
* which keep additional information about the transport in its context. That method will be called
* using the callback provided here.
*
* @author vladimirralev
*
*/
public static class MessageSendItem {
private ByteBuffer message;
private MessageSendCallback callback;
public MessageSendItem(ByteBuffer buffer, MessageSendCallback callback) {
this.message = buffer;
this.callback = callback;
}
public MessageSendCallback getCallBack() {
return callback;
}
public String toString() {
return MessageSendItem.class.getSimpleName() + " ["
+ message + ", " + callback + "]";
}
}
}
|
/*
* Copyright (C) 2017 Drakeet <drakeet.me@gmail.com>
*
* This file is part of rebase-android
*
* rebase-android 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.
*
* rebase-android 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 rebase-android. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dangxy.androidpractice.utils;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
/**
* @author drakeet
*/
public class LoadMoreDelegate {
private final LoadMoreSubject loadMoreSubject;
public LoadMoreDelegate(LoadMoreSubject loadMoreSubject) {
this.loadMoreSubject = loadMoreSubject;
}
/**
* Should be called after recyclerView setup with its layoutManager and adapter
*
* @param recyclerView the RecyclerView
*/
public void attach(RecyclerView recyclerView) {
final LinearLayoutManager layoutManager
= (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(
new EndlessScrollListener(layoutManager, loadMoreSubject));
}
private static class EndlessScrollListener extends RecyclerView.OnScrollListener {
private static final int VISIBLE_THRESHOLD = 6;
private final LinearLayoutManager layoutManager;
private final LoadMoreSubject loadMoreSubject;
private EndlessScrollListener(LinearLayoutManager layoutManager, LoadMoreSubject loadMoreSubject) {
this.layoutManager = layoutManager;
this.loadMoreSubject = loadMoreSubject;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy < 0 || loadMoreSubject.isLoading()) return;
final int itemCount = layoutManager.getItemCount();
final int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
final boolean isBottom = (lastVisiblePosition >= itemCount - VISIBLE_THRESHOLD);
if (isBottom) {
loadMoreSubject.onLoadMore();
}
}
}
public interface LoadMoreSubject {
boolean isLoading();
void onLoadMore();
}
}
|
/*
* Copyright (C) 2010 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.android.connectivitymanagertest.functional;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;
import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
import com.android.connectivitymanagertest.ConnectivityManagerTestRunner;
import com.android.connectivitymanagertest.NetworkState;
public class ConnectivityManagerMobileTest extends
ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
private static final String LOG_TAG = "ConnectivityManagerMobileTest";
private String mTestAccessPoint;
private ConnectivityManagerTestActivity cmActivity;
private WakeLock wl;
private boolean mWifiOnlyFlag;
public ConnectivityManagerMobileTest() {
super(ConnectivityManagerTestActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
cmActivity = getActivity();
ConnectivityManagerTestRunner mRunner =
(ConnectivityManagerTestRunner)getInstrumentation();
mTestAccessPoint = mRunner.mTestSsid;
mWifiOnlyFlag = mRunner.mWifiOnlyFlag;
PowerManager pm = (PowerManager)getInstrumentation().
getContext().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "CMWakeLock");
wl.acquire();
// Each test case will start with cellular connection
if (Settings.Global.getInt(getInstrumentation().getContext().getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON) == 1) {
log("airplane is not disabled, disable it.");
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
}
if (!mWifiOnlyFlag) {
if (!cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT)) {
// Note: When the test fails in setUp(), tearDown is not called. In that case,
// the activity is destroyed which blocks the next test at "getActivity()".
// tearDown() is called here to avoid that situation.
tearDown();
fail("Device is not connected to Mobile, setUp failed");
}
}
}
@Override
public void tearDown() throws Exception {
cmActivity.finish();
log("tear down ConnectivityManagerTestActivity");
wl.release();
cmActivity.removeConfiguredNetworksAndDisableWifi();
// if airplane mode is set, disable it.
if (Settings.Global.getInt(getInstrumentation().getContext().getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON) == 1) {
log("disable airplane mode if it is enabled");
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
}
super.tearDown();
}
// help function to verify 3G connection
public void verifyCellularConnection() {
NetworkInfo extraNetInfo = cmActivity.mCM.getActiveNetworkInfo();
assertEquals("network type is not MOBILE", ConnectivityManager.TYPE_MOBILE,
extraNetInfo.getType());
assertTrue("not connected to cellular network", extraNetInfo.isConnected());
}
private void log(String message) {
Log.v(LOG_TAG, message);
}
private void sleep(long sleeptime) {
try {
Thread.sleep(sleeptime);
} catch (InterruptedException e) {}
}
// Test case 1: Test enabling Wifi without associating with any AP, no broadcast on network
// event should be expected.
@LargeTest
public void test3GToWifiNotification() {
if (mWifiOnlyFlag) {
Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test");
return;
}
// Enable Wi-Fi to avoid initial UNKNOWN state
cmActivity.enableWifi();
sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT);
// Wi-Fi is disabled
cmActivity.disableWifi();
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI,
State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
// Wait for 10 seconds for broadcasts to be sent out
sleep(10 * 1000);
// As Wifi stays in DISCONNETED, Mobile statys in CONNECTED,
// the connectivity manager will not broadcast any network connectivity event for Wifi
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(), NetworkState.DO_NOTHING, State.CONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.DO_NOTHING, State.DISCONNECTED);
// Eanble Wifi without associating with any AP
cmActivity.enableWifi();
sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT);
// validate state and broadcast
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
log("the state for WIFI is changed");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue("state validation fail", false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
log("the state for MOBILE is changed");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue("state validation fail", false);
}
// Verify that the device is still connected to MOBILE
verifyCellularConnection();
}
// Test case 2: test connection to a given AP
@LargeTest
public void testConnectToWifi() {
assertNotNull("SSID is null", mTestAccessPoint);
NetworkInfo networkInfo;
if (!mWifiOnlyFlag) {
//Prepare for connectivity verification
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(), NetworkState.TO_DISCONNECTION, State.DISCONNECTED);
}
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_CONNECTION, State.CONNECTED);
// Enable Wifi and connect to a test access point
assertTrue("failed to connect to " + mTestAccessPoint,
cmActivity.connectToWifi(mTestAccessPoint));
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
log("wifi state is enabled");
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!mWifiOnlyFlag) {
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
}
// validate states
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
log("Wifi state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
if (!mWifiOnlyFlag) {
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
log("Mobile state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
}
}
// Test case 3: connect to Wifi with known AP
@LargeTest
public void testConnectToWifWithKnownAP() {
assertNotNull("SSID is null", mTestAccessPoint);
// Connect to mTestAccessPoint
assertTrue("failed to connect to " + mTestAccessPoint,
cmActivity.connectToWifi(mTestAccessPoint));
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
// Disable Wifi
log("Disable Wifi");
if (!cmActivity.disableWifi()) {
log("disable Wifi failed");
return;
}
// Wait for the Wifi state to be DISABLED
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_DISABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI,
State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!mWifiOnlyFlag) {
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
}
NetworkInfo networkInfo;
if (!mWifiOnlyFlag) {
//Prepare for connectivity state verification
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(), NetworkState.DO_NOTHING,
State.DISCONNECTED);
}
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_CONNECTION, State.CONNECTED);
// wait for 2 minutes before restart wifi
sleep(ConnectivityManagerTestActivity.WIFI_STOP_START_INTERVAL);
// Enable Wifi again
log("Enable Wifi again");
cmActivity.enableWifi();
// Wait for Wifi to be connected and mobile to be disconnected
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!mWifiOnlyFlag) {
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
}
// validate wifi states
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
log("Wifi state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
}
// Test case 4: test disconnect Wifi
@LargeTest
public void testDisconnectWifi() {
assertNotNull("SSID is null", mTestAccessPoint);
// connect to Wifi
assertTrue("failed to connect to " + mTestAccessPoint,
cmActivity.connectToWifi(mTestAccessPoint));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// Wait for a few seconds to avoid the state that both Mobile and Wifi is connected
sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
NetworkInfo networkInfo;
if (!mWifiOnlyFlag) {
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.TO_CONNECTION,
State.CONNECTED);
}
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_DISCONNECTION, State.DISCONNECTED);
// clear Wifi
cmActivity.removeConfiguredNetworksAndDisableWifi();
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!mWifiOnlyFlag) {
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
}
// validate states
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
log("Wifi state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
if (!mWifiOnlyFlag) {
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
log("Mobile state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
}
}
// Test case 5: test connectivity from 3G to airplane mode, then to 3G again
@LargeTest
public void testDataConnectionWith3GToAmTo3G() {
if (mWifiOnlyFlag) {
Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test");
return;
}
//Prepare for state verification
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.TO_DISCONNECTION,
State.DISCONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
assertEquals(State.DISCONNECTED, networkInfo.getState());
// Enable airplane mode
log("Enable airplane mode");
cmActivity.setAirplaneMode(getInstrumentation().getContext(), true);
sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
assertEquals(State.DISCONNECTED, networkInfo.getState());
// wait until mobile is turn off
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
log("Mobile state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
// reset state recorder
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.TO_CONNECTION,
State.CONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.DO_NOTHING, State.DISCONNECTED);
// disable airplane mode
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// Validate the state transition
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
log("Mobile state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
log("Wifi state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
}
// Test case 6: test connectivity with airplane mode Wifi connected
@LargeTest
public void testDataConnectionOverAMWithWifi() {
if (mWifiOnlyFlag) {
Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test");
return;
}
assertNotNull("SSID is null", mTestAccessPoint);
// Eanble airplane mode
log("Enable airplane mode");
cmActivity.setAirplaneMode(getInstrumentation().getContext(), true);
NetworkInfo networkInfo;
if (!mWifiOnlyFlag) {
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.DO_NOTHING,
State.DISCONNECTED);
}
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_CONNECTION, State.CONNECTED);
// Connect to Wifi
assertTrue("failed to connect to " + mTestAccessPoint,
cmActivity.connectToWifi(mTestAccessPoint));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// validate state and broadcast
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
log("state validate for Wifi failed");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue("State validation failed", false);
}
if (!mWifiOnlyFlag) {
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
log("state validation for Mobile failed");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue("state validation failed", false);
}
}
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
}
// Test case 7: test connectivity while transit from Wifi->AM->Wifi
@LargeTest
public void testDataConnectionWithWifiToAMToWifi () {
if (mWifiOnlyFlag) {
Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test");
return;
}
// Connect to mTestAccessPoint
assertNotNull("SSID is null", mTestAccessPoint);
// Connect to Wifi
assertTrue("failed to connect to " + mTestAccessPoint,
cmActivity.connectToWifi(mTestAccessPoint));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
log("exception: " + e.toString());
}
// Enable airplane mode without clearing Wifi
cmActivity.setAirplaneMode(getInstrumentation().getContext(), true);
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
log("exception: " + e.toString());
}
// Prepare for state validation
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
assertEquals(State.DISCONNECTED, networkInfo.getState());
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI,
networkInfo.getState(), NetworkState.TO_CONNECTION, State.CONNECTED);
// Disable airplane mode
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!mWifiOnlyFlag) {
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE,
State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT));
}
// validate the state transition
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
log("Wifi state transition validation failed.");
log("reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
}
// Test case 8: test wifi state change while connecting/disconnecting to/from an AP
@LargeTest
public void testWifiStateChange () {
assertNotNull("SSID is null", mTestAccessPoint);
//Connect to mTestAccessPoint
assertTrue("failed to connect to " + mTestAccessPoint,
cmActivity.connectToWifi(mTestAccessPoint));
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertNotNull("Not associated with any AP",
cmActivity.mWifiManager.getConnectionInfo().getBSSID());
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
log("exception: " + e.toString());
}
// Disconnect from the current AP
log("disconnect from the AP");
if (!cmActivity.disconnectAP()) {
log("failed to disconnect from " + mTestAccessPoint);
}
// Verify the connectivity state for Wifi is DISCONNECTED
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!cmActivity.disableWifi()) {
log("disable Wifi failed");
return;
}
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_DISABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
}
}
|
package com.energyxxer.trident.sets.java.selector_arguments;
import com.energyxxer.commodore.functionlogic.selector.arguments.DZArgument;
import com.energyxxer.enxlex.pattern_matching.matching.TokenPatternMatch;
import com.energyxxer.prismarine.PrismarineProductions;
import com.energyxxer.prismarine.providers.PatternSwitchProviderUnit;
import com.energyxxer.prismarine.worker.PrismarineProjectWorker;
import com.energyxxer.trident.compiler.TridentProductions;
import static com.energyxxer.prismarine.PrismarineProductions.*;
public class DZArgumentParser implements PatternSwitchProviderUnit {
@Override
public String[] getSwitchKeys() {
return new String[] {"dz"};
}
@Override
public TokenPatternMatch createPatternMatch(PrismarineProductions productions, PrismarineProjectWorker worker) {
return group(
literal("dz").setName("SELECTOR_ARGUMENT_KEY"),
TridentProductions.equals(),
wrapper(TridentProductions.real(productions), (v, p, d) -> new DZArgument((double)v))
).setSimplificationFunctionContentIndex(2);
}
}
|
package com.nmys.story.model.dto;
import lombok.Data;
import java.io.Serializable;
/**
* 后台统计对象
* <p>
* Created by 70kg
*/
@Data
public class Statistics implements Serializable {
// 文章数
private long articles = 10;
// 页面数
private long pages = 10;
// 评论数
private long comments = 10;
// 分类数
private long categories = 10;
// 标签数
private long tags = 10;
// 附件数
private long attachs = 10;
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.12.26 at 02:59:00 PM IST
//
package generated;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for flightStatusUpdateV2 complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="flightStatusUpdateV2">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="updatedAt" type="{}dateInfoV2"/>
* <element name="source" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="updatedTextFields" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="updatedTextField" type="{}flightStatusUpdatedTextV2" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="updatedDateFields" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="updatedDateField" type="{}flightStatusUpdatedDateV2" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "flightStatusUpdateV2", propOrder = {
"updatedAt",
"source",
"updatedTextFields",
"updatedDateFields"
})
public class FlightStatusUpdateV2 {
@XmlElement(required = true)
protected DateInfoV2 updatedAt;
@XmlElement(required = true)
protected String source;
protected FlightStatusUpdateV2 .UpdatedTextFields updatedTextFields;
protected FlightStatusUpdateV2 .UpdatedDateFields updatedDateFields;
/**
* Gets the value of the updatedAt property.
*
* @return
* possible object is
* {@link DateInfoV2 }
*
*/
public DateInfoV2 getUpdatedAt() {
return updatedAt;
}
/**
* Sets the value of the updatedAt property.
*
* @param value
* allowed object is
* {@link DateInfoV2 }
*
*/
public void setUpdatedAt(DateInfoV2 value) {
this.updatedAt = value;
}
/**
* Gets the value of the source property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSource() {
return source;
}
/**
* Sets the value of the source property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSource(String value) {
this.source = value;
}
/**
* Gets the value of the updatedTextFields property.
*
* @return
* possible object is
* {@link FlightStatusUpdateV2 .UpdatedTextFields }
*
*/
public FlightStatusUpdateV2 .UpdatedTextFields getUpdatedTextFields() {
return updatedTextFields;
}
/**
* Sets the value of the updatedTextFields property.
*
* @param value
* allowed object is
* {@link FlightStatusUpdateV2 .UpdatedTextFields }
*
*/
public void setUpdatedTextFields(FlightStatusUpdateV2 .UpdatedTextFields value) {
this.updatedTextFields = value;
}
/**
* Gets the value of the updatedDateFields property.
*
* @return
* possible object is
* {@link FlightStatusUpdateV2 .UpdatedDateFields }
*
*/
public FlightStatusUpdateV2 .UpdatedDateFields getUpdatedDateFields() {
return updatedDateFields;
}
/**
* Sets the value of the updatedDateFields property.
*
* @param value
* allowed object is
* {@link FlightStatusUpdateV2 .UpdatedDateFields }
*
*/
public void setUpdatedDateFields(FlightStatusUpdateV2 .UpdatedDateFields value) {
this.updatedDateFields = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="updatedDateField" type="{}flightStatusUpdatedDateV2" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"updatedDateField"
})
public static class UpdatedDateFields {
protected List<FlightStatusUpdatedDateV2> updatedDateField;
/**
* Gets the value of the updatedDateField property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the updatedDateField property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUpdatedDateField().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FlightStatusUpdatedDateV2 }
*
*
*/
public List<FlightStatusUpdatedDateV2> getUpdatedDateField() {
if (updatedDateField == null) {
updatedDateField = new ArrayList<FlightStatusUpdatedDateV2>();
}
return this.updatedDateField;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="updatedTextField" type="{}flightStatusUpdatedTextV2" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"updatedTextField"
})
public static class UpdatedTextFields {
protected List<FlightStatusUpdatedTextV2> updatedTextField;
/**
* Gets the value of the updatedTextField property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the updatedTextField property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUpdatedTextField().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FlightStatusUpdatedTextV2 }
*
*
*/
public List<FlightStatusUpdatedTextV2> getUpdatedTextField() {
if (updatedTextField == null) {
updatedTextField = new ArrayList<FlightStatusUpdatedTextV2>();
}
return this.updatedTextField;
}
}
}
|
package com.camunda.demo.engine_plugin_custom_history_event_handler;
import java.util.List;
import java.util.logging.Logger;
import org.camunda.bpm.engine.impl.history.event.HistoryEvent;
import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler;
public class MyCustomHistoryEventHandler implements HistoryEventHandler {
private final Logger LOGGER = Logger.getLogger(MyCustomHistoryEventHandler.class.getName());
private static final MyCustomHistoryEventHandler INSTANCE = new MyCustomHistoryEventHandler();
public static MyCustomHistoryEventHandler getInstance(){
return INSTANCE;
}
@Override
public void handleEvent(HistoryEvent historyEvent) {
LOGGER.info("----- HISTORY EVENT PRODUCED: "+ historyEvent.toString());
}
@Override
public void handleEvents(List<HistoryEvent> historyEvents) {
for (HistoryEvent historyEvent : historyEvents) {
handleEvent(historyEvent);
}
}
}
|
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* 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.komodo.relational.resource;
import org.komodo.core.repository.ObjectImpl;
import org.komodo.relational.TypeResolver;
import org.komodo.relational.dataservice.DataServiceResource;
import org.komodo.relational.resource.internal.DriverImpl;
import org.komodo.spi.KException;
import org.komodo.spi.repository.DocumentType;
import org.komodo.spi.repository.KomodoObject;
import org.komodo.spi.repository.KomodoType;
import org.komodo.spi.repository.Repository.UnitOfWork;
import org.komodo.spi.lexicon.datavirt.DataVirtLexicon;
/**
* Represents a driver of a data service.
*/
public interface Driver extends DataServiceResource {
/**
* The file extension of driver files.
*/
DocumentType DOC_TYPE = DocumentType.JAR;
/**
* The type identifier.
*/
int TYPE_ID = Driver.class.hashCode();
/**
* Identifier of this object
*/
KomodoType IDENTIFIER = KomodoType.DRIVER;
/**
* An empty array of drivers.
*/
Driver[] NO_DRIVERS = new Driver[ 0 ];
/**
* The resolver of a {@link Driver}.
*/
TypeResolver< Driver > RESOLVER = new TypeResolver< Driver >() {
/**
* {@inheritDoc}
*
* @see org.komodo.relational.TypeResolver#identifier()
*/
@Override
public KomodoType identifier() {
return IDENTIFIER;
}
/**
* {@inheritDoc}
*
* @see org.komodo.relational.TypeResolver#owningClass()
*/
@Override
public Class< DriverImpl > owningClass() {
return DriverImpl.class;
}
/**
* {@inheritDoc}
*
* @see org.komodo.relational.TypeResolver#resolvable(org.komodo.spi.repository.Repository.UnitOfWork,
* org.komodo.spi.repository.KomodoObject)
*/
@Override
public boolean resolvable( final UnitOfWork transaction,
final KomodoObject kobject ) throws KException {
return ObjectImpl.validateType( transaction,
kobject.getRepository(),
kobject,
DataVirtLexicon.ResourceFile.DRIVER_FILE_NODE_TYPE );
}
/**
* {@inheritDoc}
*
* @see org.komodo.relational.TypeResolver#resolve(org.komodo.spi.repository.Repository.UnitOfWork,
* org.komodo.spi.repository.KomodoObject)
*/
@Override
public Driver resolve( final UnitOfWork transaction,
final KomodoObject kobject ) throws KException {
if ( kobject.getTypeId() == Driver.TYPE_ID ) {
return ( Driver )kobject;
}
return new DriverImpl( transaction, kobject.getRepository(), kobject.getAbsolutePath() );
}
};
/**
* {@inheritDoc}
*
* @see org.komodo.spi.repository.Exportable#getDocumentType(org.komodo.spi.repository.Repository.UnitOfWork)
*/
@Override
default DocumentType getDocumentType( final UnitOfWork transaction ) {
return DocumentType.JAR;
}
}
|
/*
* Copyright (c) 2002-2003, The Joust Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of the Joust Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File created by keith @ Apr 27, 2003
*
*/
package net.kano.joscar.rvcmd.sendbl;
import net.kano.joscar.common.ByteBlock;
import net.kano.joscar.common.DefensiveTools;
import net.kano.joscar.rvcmd.AbstractRequestRvCmd;
import net.kano.joscar.snaccmd.CapabilityBlock;
import net.kano.joscar.snaccmd.icbm.RecvRvIcbm;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
/**
* A rendezvous command used in sending portions of one's buddy list to another
* user.
* <br>
* <br>
* <b>Important note for implementing Send Buddy List:</b><br>
* The official Windows AIM client (WinAIM, as I call it) <i>always</i> sends a
* {@link net.kano.joscar.snaccmd.icbm.RvResponse} with a code of {@link
* net.kano.joscar.snaccmd.icbm.RvResponse#CODE_NOT_ACCEPTING} in response to a
* Send Buddy List command (this class). If this <code>RvResponse</code> is not
* sent in response to an incoming <code>SendBuddyListRvCmd</code> and the
* sender is using WinAIM, he or she will not be able to send any more Send
* Buddy List commands to your client until he or she restarts AIM. I do not
* know why this happens, but this behavior should be duplicated for maximum
* compatibility with other users.
*/
public class SendBuddyListRvCmd extends AbstractRequestRvCmd {
/** The buddy groups being sent. */
private final List<SendBuddyListGroup> groups;
/**
* Creates a new Send Buddy List command from the given incoming Send Buddy
* List RV ICBM.
*
* @param icbm an incoming Send Buddy List RV ICBM
*/
public SendBuddyListRvCmd(RecvRvIcbm icbm) {
super(icbm);
ByteBlock serviceData = getServiceData();
if (serviceData == null) groups = null;
else groups = SendBuddyListGroup.readBuddyListGroups(serviceData);
}
/**
* Creates a new Send Buddy List command with the given list of buddy
* groups.
*
* @param groups the list of buddy groups
*/
public SendBuddyListRvCmd(Collection<SendBuddyListGroup> groups) {
super(CapabilityBlock.BLOCK_SENDBUDDYLIST);
this.groups = DefensiveTools.getSafeNonnullListCopy(groups, "groups");
}
/**
* Returns a list of the buddy groups contained in this command. Note that
* this method will never return <code>null</code>; if no groups were sent,
* the returned array will simply be empty.
*
* @return a list of the buddy groups sent in this command
*/
public final List<SendBuddyListGroup> getGroups() {
return groups;
}
protected void writeServiceData(OutputStream out) throws IOException {
for (SendBuddyListGroup group : groups) {
group.write(out);
}
}
protected void writeRvTlvs(OutputStream out) throws IOException { }
public String toString() {
return "SendBuddyListRvCmd: " + groups;
}
}
|
package br.com.zupacademy.clayton.proposta.utilitarios.validadores;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import org.hibernate.validator.constraints.CompositionType;
import org.hibernate.validator.constraints.ConstraintComposition;
import org.hibernate.validator.constraints.br.CNPJ;
import org.hibernate.validator.constraints.br.CPF;
@Documented
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@ReportAsSingleViolation //ignora os erros individuais de cada restrição
@CPF @CNPJ @ConstraintComposition(CompositionType.OR) //combina as restrições @CPF e @CNPJ
public @interface ValidadorCPFouCNPJ {
String message() default "O CPF ou CNPJ digitado não é valido";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
/*
*
* * Copyright (c) 2021, Zoinkwiz <https://github.com/Zoinkwiz>
* * All rights reserved.
* *
* * Redistribution and use in source and binary forms, with or without
* * modification, are permitted provided that the following conditions are met:
* *
* * 1. Redistributions of source code must retain the above copyright notice, this
* * list of conditions and the following disclaimer.
* * 2. Redistributions in binary form must reproduce the above copyright notice,
* * this list of conditions and the following disclaimer in the documentation
* * and/or other materials provided with the distribution.
* *
* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package com.questhelper.requirements.var;
import com.questhelper.requirements.AbstractRequirement;
import com.questhelper.requirements.util.Operation;
import java.math.BigInteger;
import java.util.Locale;
import net.runelite.api.Client;
public class VarplayerRequirement extends AbstractRequirement
{
private final int varplayerId;
private final int value;
private final Operation operation;
private final String displayText;
private final int bitPosition;
private final boolean bitIsSet;
public VarplayerRequirement(int varplayerId, int value)
{
this.varplayerId = varplayerId;
this.value = value;
this.operation = Operation.EQUAL;
this.displayText = null;
this.bitPosition = -1;
this.bitIsSet = false;
shouldCountForFilter = true;
}
public VarplayerRequirement(int varplayerId, int value, String displayText)
{
this.varplayerId = varplayerId;
this.value = value;
this.operation = Operation.EQUAL;
this.displayText = displayText;
this.bitPosition = -1;
this.bitIsSet = false;
shouldCountForFilter = true;
}
public VarplayerRequirement(int varplayerId, int value, Operation operation)
{
this.varplayerId = varplayerId;
this.value = value;
this.operation = operation;
this.displayText = null;
this.bitPosition = -1;
this.bitIsSet = false;
shouldCountForFilter = true;
}
public VarplayerRequirement(int varplayerId, int value, Operation operation, String displayText)
{
this.varplayerId = varplayerId;
this.value = value;
this.operation = operation;
this.displayText = displayText;
this.bitPosition = -1;
this.bitIsSet = false;
shouldCountForFilter = true;
}
public VarplayerRequirement(int varplayerId, boolean bitIsSet, int bitPosition)
{
this.varplayerId = varplayerId;
this.value = -1;
this.operation = Operation.EQUAL;
this.displayText = null;
this.bitPosition = bitPosition;
this.bitIsSet = bitIsSet;
shouldCountForFilter = true;
}
public VarplayerRequirement(int varplayerId, boolean bitIsSet, int bitPosition, String displayText)
{
this.varplayerId = varplayerId;
this.value = -1;
this.operation = Operation.EQUAL;
this.displayText = displayText;
this.bitPosition = bitPosition;
this.bitIsSet = bitIsSet;
shouldCountForFilter = true;
}
@Override
public boolean check(Client client)
{
if (bitPosition >= 0)
{
return bitIsSet == BigInteger.valueOf(client.getVarpValue(varplayerId)).testBit(bitPosition);
}
return operation.check(client.getVarpValue(varplayerId), value);
}
@Override
public String getDisplayText()
{
if (displayText != null)
{
return displayText;
}
if (bitPosition >= 0)
{
return varplayerId + " must have the " + bitPosition + " bit set.";
}
return varplayerId + " must be + " + operation.name().toLowerCase(Locale.ROOT) + " " + value;
}
}
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import frc.robot.subsystems.Drivetrain;
import frc.robot.subsystems.OnBoardIO;
import edu.wpi.first.wpilibj2.command.CommandBase;
public class DriveTime extends CommandBase {
private final double m_duration;
private final double m_speed;
private final Drivetrain m_drive;
private long m_startTime;
private OnBoardIO io;
private int mode = 0;
private int ticksSinceLastModeSwitch = 0;
private int changeMode = 0;
/**
* Creates a new DriveTime. This command will drive your robot for a desired speed and time.
*
* @param speed The speed which the robot will drive. Negative is in reverse.
* @param time How much time to drive in seconds
* @param drive The drivetrain subsystem on which this command will run
*/
public DriveTime(double speed, double time, Drivetrain drive) {
m_speed = speed;
m_duration = time * 1000;
m_drive = drive;
io = new OnBoardIO();
addRequirements(drive);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
m_startTime = System.currentTimeMillis();
m_drive.arcadeDrive(0, 0);
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
int leftIR = io.getLeftValue();
int middleIR = io.getMiddleValue();
int rightIR = io.getRightValue();
ticksSinceLastModeSwitch++;
if (middleIR < 3000 && leftIR < 3200 && rightIR < 3500){ // 3 sensor hit
if (ticksSinceLastModeSwitch > 30) { // ok to switch mode
if (changeMode >= 2){
m_drive.tankDrive(0.0, 0.0);
mode = 2;
}
else if (mode == 0){
mode = 1;
}else if (mode == 1){
mode = 0;
}
ticksSinceLastModeSwitch = 0;
changeMode++;
}
}
if (middleIR > 3000 && leftIR < 3200 && rightIR < 3500){ // 2 sensor hit
m_drive.tankDrive(0.0, 0.0);
mode = 2;
}
System.out.println(leftIR + "-" + middleIR + "-" + rightIR + "-" + mode + "-" + changeMode);
if (mode == 0){
if (middleIR < 3000) {
m_drive.tankDrive(.52, .5);
}else if (leftIR < 3200) {
m_drive.tankDrive(.3, .5);
} else if (rightIR < 3500) {
m_drive.tankDrive(.5, .3);
} else {
m_drive.tankDrive(.42, .4);
}
}else if (mode == 1){
m_drive.tankDrive(.4, .8);
} else if (mode > 1) {
m_drive.tankDrive(0, 0);
}
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
m_drive.arcadeDrive(0, 0);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return (System.currentTimeMillis() - m_startTime) >= m_duration;
}
}
|
package com.pedro.rtplibrary.base;
import android.content.Context;
import android.hardware.camera2.CameraCharacteristics;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.os.Build;
import android.util.Range;
import android.util.Size;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.TextureView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.pedro.encoder.Frame;
import com.pedro.encoder.audio.AudioEncoder;
import com.pedro.encoder.audio.GetAacData;
import com.pedro.encoder.input.audio.CustomAudioEffect;
import com.pedro.encoder.input.audio.GetMicrophoneData;
import com.pedro.encoder.input.audio.MicrophoneManager;
import com.pedro.encoder.input.audio.MicrophoneManagerManual;
import com.pedro.encoder.input.audio.MicrophoneMode;
import com.pedro.encoder.input.video.Camera2ApiManager;
import com.pedro.encoder.input.video.CameraCallbacks;
import com.pedro.encoder.input.video.CameraHelper;
import com.pedro.encoder.input.video.CameraOpenException;
import com.pedro.encoder.utils.CodecUtil;
import com.pedro.encoder.video.FormatVideoEncoder;
import com.pedro.encoder.video.GetVideoData;
import com.pedro.encoder.video.VideoEncoder;
import com.pedro.rtplibrary.util.FpsListener;
import com.pedro.rtplibrary.util.RecordController;
import com.pedro.rtplibrary.view.GlInterface;
import com.pedro.rtplibrary.view.LightOpenGlView;
import com.pedro.rtplibrary.view.OffScreenGlThread;
import com.pedro.rtplibrary.view.OpenGlView;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
/**
* Wrapper to stream with camera2 api and microphone. Support stream with SurfaceView, TextureView,
* OpenGlView(Custom SurfaceView that use OpenGl) and Context(background mode). All views use
* Surface to buffer encoding mode for H264.
*
* API requirements:
* API 21+.
*
* Created by pedro on 7/07/17.
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public abstract class Camera2Base implements GetAacData, GetVideoData, GetMicrophoneData {
protected Context context;
private Camera2ApiManager cameraManager;
protected VideoEncoder videoEncoder;
private MicrophoneManager microphoneManager;
private AudioEncoder audioEncoder;
private boolean streaming = false;
private SurfaceView surfaceView;
private TextureView textureView;
private GlInterface glInterface;
private boolean videoEnabled = false;
private boolean onPreview = false;
private boolean isBackground = false;
protected RecordController recordController;
private int previewWidth, previewHeight;
private FpsListener fpsListener = new FpsListener();
/**
* @deprecated This view produce rotations problems and could be unsupported in future versions.
* Use {@link Camera2Base#Camera2Base(OpenGlView)} or {@link Camera2Base#Camera2Base(LightOpenGlView)}
* instead.
*/
@Deprecated
public Camera2Base(SurfaceView surfaceView) {
this.surfaceView = surfaceView;
this.context = surfaceView.getContext();
init(context);
}
/**
* @deprecated This view produce rotations problems and could be unsupported in future versions.
* Use {@link Camera2Base#Camera2Base(OpenGlView)} or {@link Camera2Base#Camera2Base(LightOpenGlView)}
* instead.
*/
@Deprecated
public Camera2Base(TextureView textureView) {
this.textureView = textureView;
this.context = textureView.getContext();
init(context);
}
public Camera2Base(OpenGlView openGlView) {
context = openGlView.getContext();
glInterface = openGlView;
glInterface.init();
init(context);
}
public Camera2Base(LightOpenGlView lightOpenGlView) {
this.context = lightOpenGlView.getContext();
glInterface = lightOpenGlView;
glInterface.init();
init(context);
}
public Camera2Base(Context context, boolean useOpengl) {
this.context = context;
if (useOpengl) {
glInterface = new OffScreenGlThread(context);
glInterface.init();
}
isBackground = true;
init(context);
}
private void init(Context context) {
cameraManager = new Camera2ApiManager(context);
videoEncoder = new VideoEncoder(this);
setMicrophoneMode(MicrophoneMode.ASYNC);
recordController = new RecordController();
}
/**
* Must be called before prepareAudio.
*
* @param microphoneMode mode to work accord to audioEncoder. By default ASYNC:
* SYNC using same thread. This mode could solve choppy audio or AudioEncoder frame discarded.
* ASYNC using other thread.
*/
public void setMicrophoneMode(MicrophoneMode microphoneMode) {
switch (microphoneMode) {
case SYNC:
microphoneManager = new MicrophoneManagerManual();
audioEncoder = new AudioEncoder(this);
audioEncoder.setGetFrame(((MicrophoneManagerManual) microphoneManager).getGetFrame());
break;
case ASYNC:
microphoneManager = new MicrophoneManager(this);
audioEncoder = new AudioEncoder(this);
break;
}
}
public void setCameraCallbacks(CameraCallbacks callbacks) {
cameraManager.setCameraCallbacks(callbacks);
}
/**
* Set an audio effect modifying microphone's PCM buffer.
*/
public void setCustomAudioEffect(CustomAudioEffect customAudioEffect) {
microphoneManager.setCustomAudioEffect(customAudioEffect);
}
/**
* @param callback get fps while record or stream
*/
public void setFpsListener(FpsListener.Callback callback) {
fpsListener.setCallback(callback);
}
/**
* Experimental
*/
public void enableFaceDetection(Camera2ApiManager.FaceDetectorCallback faceDetectorCallback) {
cameraManager.enableFaceDetection(faceDetectorCallback);
}
/**
* Experimental
*/
public void disableFaceDetection() {
cameraManager.disableFaceDetection();
}
/**
* Experimental
*/
public boolean isFaceDetectionEnabled() {
return cameraManager.isFaceDetectionEnabled();
}
public boolean isFrontCamera() {
return cameraManager.isFrontCamera();
}
public void enableLantern() throws Exception {
cameraManager.enableLantern();
}
public void disableLantern() {
cameraManager.disableLantern();
}
public boolean isLanternEnabled() {
return cameraManager.isLanternEnabled();
}
public boolean isLanternSupported() {
return cameraManager.isLanternSupported();
}
public void enableAutoFocus() {
cameraManager.enableAutoFocus();
}
public void disableAutoFocus() {
cameraManager.disableAutoFocus();
}
public boolean isAutoFocusEnabled() {
return cameraManager.isAutoFocusEnabled();
}
/**
* Basic auth developed to work with Wowza. No tested with other server
*
* @param user auth.
* @param password auth.
*/
public abstract void setAuthorization(String user, String password);
/**
* Call this method before use @startStream. If not you will do a stream without video.
*
* @param width resolution in px.
* @param height resolution in px.
* @param fps frames per second of the stream.
* @param bitrate H264 in bps.
* @param rotation could be 90, 180, 270 or 0 (Normally 0 if you are streaming in landscape or 90
* if you are streaming in Portrait). This only affect to stream result. NOTE: Rotation with
* encoder is silence ignored in some devices.
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a H264 encoder).
*/
public boolean prepareVideo(int width, int height, int fps, int bitrate, int iFrameInterval,
int rotation, int avcProfile, int avcProfileLevel) {
if (onPreview && !(glInterface != null && width == previewWidth && height == previewHeight)) {
stopPreview();
onPreview = true;
}
boolean result =
videoEncoder.prepareVideoEncoder(width, height, fps, bitrate, rotation, iFrameInterval,
FormatVideoEncoder.SURFACE, avcProfile, avcProfileLevel);
prepareCameraManager();
return result;
}
public boolean prepareVideo(int width, int height, int fps, int bitrate, int iFrameInterval,
int rotation) {
return prepareVideo(width, height, fps, bitrate, iFrameInterval, rotation, -1, -1);
}
/**
* backward compatibility reason
*/
public boolean prepareVideo(int width, int height, int fps, int bitrate, int rotation) {
return prepareVideo(width, height, fps, bitrate, 2, rotation);
}
public boolean prepareVideo(int width, int height, int bitrate) {
int rotation = CameraHelper.getCameraOrientation(context);
return prepareVideo(width, height, 30, bitrate, 2, rotation);
}
protected abstract void prepareAudioRtp(boolean isStereo, int sampleRate);
/**
* Call this method before use @startStream. If not you will do a stream without audio.
*
* @param bitrate AAC in kb.
* @param sampleRate of audio in hz. Can be 8000, 16000, 22500, 32000, 44100.
* @param isStereo true if you want Stereo audio (2 audio channels), false if you want Mono audio
* (1 audio channel).
* @param echoCanceler true enable echo canceler, false disable.
* @param noiseSuppressor true enable noise suppressor, false disable.
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a AAC encoder).
*/
public boolean prepareAudio(int bitrate, int sampleRate, boolean isStereo, boolean echoCanceler,
boolean noiseSuppressor) {
microphoneManager.createMicrophone(sampleRate, isStereo, echoCanceler, noiseSuppressor);
prepareAudioRtp(isStereo, sampleRate);
return audioEncoder.prepareAudioEncoder(bitrate, sampleRate, isStereo,
microphoneManager.getMaxInputSize());
}
public boolean prepareAudio(int bitrate, int sampleRate, boolean isStereo) {
return prepareAudio(bitrate, sampleRate, isStereo, false, false);
}
/**
* Same to call: isHardwareRotation = true; if (openGlVIew) isHardwareRotation = false;
* prepareVideo(640, 480, 30, 1200 * 1024, isHardwareRotation, 90);
*
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a H264 encoder).
*/
public boolean prepareVideo() {
int rotation = CameraHelper.getCameraOrientation(context);
return prepareVideo(1280, 720, 30, 1200 * 1024, rotation);
}
/**
* Same to call: prepareAudio(64 * 1024, 32000, true, false, false);
*
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a AAC encoder).
*/
public boolean prepareAudio() {
return prepareAudio(64 * 1024, 32000, true, false, false);
}
/**
* @param forceVideo force type codec used. FIRST_COMPATIBLE_FOUND, SOFTWARE, HARDWARE
* @param forceAudio force type codec used. FIRST_COMPATIBLE_FOUND, SOFTWARE, HARDWARE
*/
public void setForce(CodecUtil.Force forceVideo, CodecUtil.Force forceAudio) {
videoEncoder.setForce(forceVideo);
audioEncoder.setForce(forceAudio);
}
/**
* Starts recording an MP4 video. Needs to be called while streaming.
*
* @param path Where file will be saved.
* @throws IOException If initialized before a stream.
*/
public void startRecord(@NonNull String path, @Nullable RecordController.Listener listener)
throws IOException {
recordController.startRecord(path, listener);
if (!streaming) {
startEncoders();
} else if (videoEncoder.isRunning()) {
resetVideoEncoder();
}
}
public void startRecord(@NonNull final String path) throws IOException {
startRecord(path, null);
}
/**
* Starts recording an MP4 video. Needs to be called while streaming.
*
* @param fd Where the file will be saved.
* @throws IOException If initialized before a stream.
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void startRecord(@NonNull final FileDescriptor fd,
@Nullable RecordController.Listener listener) throws IOException {
recordController.startRecord(fd, listener);
if (!streaming) {
startEncoders();
} else if (videoEncoder.isRunning()) {
resetVideoEncoder();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void startRecord(@NonNull final FileDescriptor fd) throws IOException {
startRecord(fd, null);
}
/**
* Stop record MP4 video started with @startRecord. If you don't call it file will be unreadable.
*/
public void stopRecord() {
recordController.stopRecord();
if (!streaming) stopStream();
}
public void replaceView(Context context) {
isBackground = true;
replaceGlInterface(new OffScreenGlThread(context));
}
public void replaceView(OpenGlView openGlView) {
isBackground = false;
replaceGlInterface(openGlView);
}
public void replaceView(LightOpenGlView lightOpenGlView) {
isBackground = false;
replaceGlInterface(lightOpenGlView);
}
/**
* Replace glInterface used on fly. Ignored if you use SurfaceView, TextureView or context without
* OpenGl.
*/
private void replaceGlInterface(GlInterface glInterface) {
if (this.glInterface != null && Build.VERSION.SDK_INT >= 18) {
if (isStreaming() || isRecording() || isOnPreview()) {
cameraManager.closeCamera();
this.glInterface.removeMediaCodecSurface();
this.glInterface.stop();
this.glInterface = glInterface;
this.glInterface.init();
boolean isPortrait = CameraHelper.isPortrait(context);
if (isPortrait) {
this.glInterface.setEncoderSize(videoEncoder.getHeight(), videoEncoder.getWidth());
} else {
this.glInterface.setEncoderSize(videoEncoder.getWidth(), videoEncoder.getHeight());
}
this.glInterface.setRotation(
videoEncoder.getRotation() == 0 ? 270 : videoEncoder.getRotation() - 90);
this.glInterface.start();
if (isStreaming() || isRecording()) {
this.glInterface.addMediaCodecSurface(videoEncoder.getInputSurface());
}
cameraManager.prepareCamera(this.glInterface.getSurfaceTexture(), videoEncoder.getWidth(),
videoEncoder.getHeight(), videoEncoder.getFps());
cameraManager.openLastCamera();
} else {
this.glInterface = glInterface;
this.glInterface.init();
}
}
}
/**
* Start camera preview. Ignored, if stream or preview is started.
*
* @param cameraFacing front or back camera. Like: {@link com.pedro.encoder.input.video.CameraHelper.Facing#BACK}
* {@link com.pedro.encoder.input.video.CameraHelper.Facing#FRONT}
* @param rotation camera rotation (0, 90, 180, 270). Recommended: {@link
* com.pedro.encoder.input.video.CameraHelper#getCameraOrientation(Context)}
*/
public void startPreview(CameraHelper.Facing cameraFacing, int width, int height, int rotation) {
if (!isStreaming() && !onPreview && !isBackground) {
previewWidth = width;
previewHeight = height;
if (surfaceView != null) {
cameraManager.prepareCamera(surfaceView.getHolder().getSurface(), videoEncoder.getFps());
} else if (textureView != null) {
cameraManager.prepareCamera(new Surface(textureView.getSurfaceTexture()),
videoEncoder.getFps());
} else if (glInterface != null) {
boolean isPortrait = CameraHelper.isPortrait(context);
if (isPortrait) {
glInterface.setEncoderSize(height, width);
} else {
glInterface.setEncoderSize(width, height);
}
glInterface.setRotation(rotation == 0 ? 270 : rotation - 90);
glInterface.start();
cameraManager.prepareCamera(glInterface.getSurfaceTexture(), width, height,
videoEncoder.getFps());
}
cameraManager.openCameraFacing(cameraFacing);
onPreview = true;
}
}
public void startPreview(CameraHelper.Facing cameraFacing, int width, int height) {
startPreview(cameraFacing, width, height, CameraHelper.getCameraOrientation(context));
}
public void startPreview(CameraHelper.Facing cameraFacing, int rotation) {
startPreview(cameraFacing, videoEncoder.getWidth(), videoEncoder.getHeight(), rotation);
}
public void startPreview(CameraHelper.Facing cameraFacing) {
startPreview(cameraFacing, videoEncoder.getWidth(), videoEncoder.getHeight(),
CameraHelper.getCameraOrientation(context));
}
public void startPreview() {
startPreview(CameraHelper.Facing.BACK);
}
/**
* Stop camera preview. Ignored if streaming or already stopped. You need call it after
*
* @stopStream to release camera properly if you will close activity.
*/
public void stopPreview() {
if (!isStreaming() && !isRecording() && onPreview && !isBackground) {
if (glInterface != null) {
glInterface.stop();
}
cameraManager.closeCamera();
onPreview = false;
previewWidth = 0;
previewHeight = 0;
}
}
protected abstract void startStreamRtp(List<String> url);
/**
* Need be called after @prepareVideo or/and @prepareAudio. This method override resolution of
*
* @param url of the stream like: protocol://ip:port/application/streamName
*
* RTSP: rtsp://192.168.1.1:1935/live/pedroSG94 RTSPS: rtsps://192.168.1.1:1935/live/pedroSG94
* RTMP: rtmp://192.168.1.1:1935/live/pedroSG94 RTMPS: rtmps://192.168.1.1:1935/live/pedroSG94
* @startPreview to resolution seated in @prepareVideo. If you never startPreview this method
* startPreview for you to resolution seated in @prepareVideo.
*/
public void startStream(List<String> url) {
streaming = true;
if (!recordController.isRunning()) {
startEncoders();
} else {
resetVideoEncoder();
}
startStreamRtp(url);
onPreview = true;
}
private void startEncoders() {
videoEncoder.start();
audioEncoder.start();
prepareGlView();
microphoneManager.start();
if (glInterface == null && !cameraManager.isRunning() && videoEncoder.getWidth() != previewWidth
|| videoEncoder.getHeight() != previewHeight) {
if (onPreview) {
cameraManager.openLastCamera();
} else {
cameraManager.openCameraBack();
}
}
onPreview = true;
}
private void resetVideoEncoder() {
if (glInterface != null) {
glInterface.removeMediaCodecSurface();
}
videoEncoder.reset();
if (glInterface != null) {
glInterface.addMediaCodecSurface(videoEncoder.getInputSurface());
} else {
cameraManager.closeCamera();
cameraManager.prepareCamera(videoEncoder.getInputSurface(), videoEncoder.getFps());
cameraManager.openLastCamera();
}
}
private void prepareGlView() {
if (glInterface != null && videoEnabled) {
if (glInterface instanceof OffScreenGlThread) {
glInterface = new OffScreenGlThread(context);
glInterface.init();
}
glInterface.setFps(videoEncoder.getFps());
if (videoEncoder.getRotation() == 90 || videoEncoder.getRotation() == 270) {
glInterface.setEncoderSize(videoEncoder.getHeight(), videoEncoder.getWidth());
} else {
glInterface.setEncoderSize(videoEncoder.getWidth(), videoEncoder.getHeight());
}
int rotation = videoEncoder.getRotation();
glInterface.setRotation(rotation == 0 ? 270 : rotation - 90);
if (!cameraManager.isRunning() && videoEncoder.getWidth() != previewWidth
|| videoEncoder.getHeight() != previewHeight) {
glInterface.start();
}
if (videoEncoder.getInputSurface() != null) {
glInterface.addMediaCodecSurface(videoEncoder.getInputSurface());
}
cameraManager.prepareCamera(glInterface.getSurfaceTexture(), videoEncoder.getWidth(),
videoEncoder.getHeight(), videoEncoder.getFps());
}
}
protected abstract void stopStreamRtp();
/**
* Stop stream started with @startStream.
*/
public void stopStream() {
if (streaming) {
streaming = false;
stopStreamRtp();
}
if (!recordController.isRecording()) {
onPreview = !isBackground;
microphoneManager.stop();
if (glInterface != null) {
glInterface.removeMediaCodecSurface();
if (glInterface instanceof OffScreenGlThread) {
glInterface.stop();
cameraManager.closeCamera();
}
} else {
if (isBackground) {
cameraManager.closeCamera();
} else {
cameraManager.stopRepeatingEncoder();
}
}
videoEncoder.stop();
audioEncoder.stop();
recordController.resetFormats();
}
}
public boolean reTry(long delay, String reason) {
boolean result = shouldRetry(reason);
if (result) {
reTry(delay);
}
return result;
}
/**
* Replace with reTry(long delay, String reason);
*/
@Deprecated
public void reTry(long delay) {
resetVideoEncoder();
reConnect(delay);
}
/**
* Replace with reTry(long delay, String reason);
*/
@Deprecated
public abstract boolean shouldRetry(String reason);
public abstract void setReTries(int reTries);
protected abstract void reConnect(long delay);
//cache control
public abstract boolean hasCongestion();
public abstract void resizeCache(int newSize) throws RuntimeException;
public abstract int getCacheSize();
public abstract long getSentAudioFrames();
public abstract long getSentVideoFrames();
public abstract long getDroppedAudioFrames();
public abstract long getDroppedVideoFrames();
public abstract void resetSentAudioFrames();
public abstract void resetSentVideoFrames();
public abstract void resetDroppedAudioFrames();
public abstract void resetDroppedVideoFrames();
/**
* Get supported preview resolutions of back camera in px.
*
* @return list of preview resolutions supported by back camera
*/
public List<Size> getResolutionsBack() {
return Arrays.asList(cameraManager.getCameraResolutionsBack());
}
/**
* Get supported preview resolutions of front camera in px.
*
* @return list of preview resolutions supported by front camera
*/
public List<Size> getResolutionsFront() {
return Arrays.asList(cameraManager.getCameraResolutionsFront());
}
public Range<Integer>[] getSupportedFps() {
return cameraManager.getSupportedFps();
}
/**
* Get supported properties of the camera
*
* @return CameraCharacteristics object
*/
public CameraCharacteristics getCameraCharacteristics() {
return cameraManager.getCameraCharacteristics();
}
/**
* Mute microphone, can be called before, while and after stream.
*/
public void disableAudio() {
microphoneManager.mute();
}
/**
* Enable a muted microphone, can be called before, while and after stream.
*/
public void enableAudio() {
microphoneManager.unMute();
}
/**
* Get mute state of microphone.
*
* @return true if muted, false if enabled
*/
public boolean isAudioMuted() {
return microphoneManager.isMuted();
}
/**
* Get video camera state
*
* @return true if disabled, false if enabled
*/
public boolean isVideoEnabled() {
return videoEnabled;
}
/**
* Return max zoom level
*
* @return max zoom level
*/
public float getMaxZoom() {
return cameraManager.getMaxZoom();
}
/**
* Return current zoom level
*
* @return current zoom level
*/
public float getZoom() {
return cameraManager.getZoom();
}
/**
* Set zoomIn or zoomOut to camera.
* Use this method if you use a zoom slider.
*
* @param level Expected to be >= 1 and <= max zoom level
* @see Camera2Base#getMaxZoom()
*/
public void setZoom(float level) {
cameraManager.setZoom(level);
}
/**
* Set zoomIn or zoomOut to camera.
*
* @param event motion event. Expected to get event.getPointerCount() > 1
*/
public void setZoom(MotionEvent event) {
cameraManager.setZoom(event);
}
public int getBitrate() {
return videoEncoder.getBitRate();
}
public int getResolutionValue() {
return videoEncoder.getWidth() * videoEncoder.getHeight();
}
public int getStreamWidth() {
return videoEncoder.getWidth();
}
public int getStreamHeight() {
return videoEncoder.getHeight();
}
/**
* Switch camera used. Can be called on preview or while stream, ignored with preview off.
*
* @throws CameraOpenException If the other camera doesn't support same resolution.
*/
public void switchCamera() throws CameraOpenException {
if (isStreaming() || onPreview) {
cameraManager.switchCamera();
}
}
public GlInterface getGlInterface() {
if (glInterface != null) {
return glInterface;
} else {
throw new RuntimeException("You can't do it. You are not using Opengl");
}
}
private void prepareCameraManager() {
if (textureView != null) {
cameraManager.prepareCamera(textureView, videoEncoder.getInputSurface(),
videoEncoder.getFps());
} else if (surfaceView != null) {
cameraManager.prepareCamera(surfaceView, videoEncoder.getInputSurface(),
videoEncoder.getFps());
} else if (glInterface != null) {
} else {
cameraManager.prepareCamera(videoEncoder.getInputSurface(), videoEncoder.getFps());
}
videoEnabled = true;
}
/**
* Set video bitrate of H264 in bits per second while stream.
*
* @param bitrate H264 in bits per second.
*/
public void setVideoBitrateOnFly(int bitrate) {
videoEncoder.setVideoBitrateOnFly(bitrate);
}
/**
* Set limit FPS while stream. This will be override when you call to prepareVideo method. This
* could produce a change in iFrameInterval.
*
* @param fps frames per second
*/
public void setLimitFPSOnFly(int fps) {
videoEncoder.setFps(fps);
}
/**
* Get stream state.
*
* @return true if streaming, false if not streaming.
*/
public boolean isStreaming() {
return streaming;
}
/**
* Get record state.
*
* @return true if recording, false if not recoding.
*/
public boolean isRecording() {
return recordController.isRunning();
}
public void pauseRecord() {
recordController.pauseRecord();
}
public void resumeRecord() {
recordController.resumeRecord();
}
public RecordController.Status getRecordStatus() {
return recordController.getStatus();
}
/**
* Get preview state.
*
* @return true if enabled, false if disabled.
*/
public boolean isOnPreview() {
return onPreview;
}
protected abstract void getAacDataRtp(ByteBuffer aacBuffer, MediaCodec.BufferInfo info);
@Override
public void getAacData(ByteBuffer aacBuffer, MediaCodec.BufferInfo info) {
recordController.recordAudio(aacBuffer, info);
if (streaming) getAacDataRtp(aacBuffer, info);
}
protected abstract void onSpsPpsVpsRtp(ByteBuffer sps, ByteBuffer pps, ByteBuffer vps);
@Override
public void onSpsPps(ByteBuffer sps, ByteBuffer pps) {
if (streaming) onSpsPpsVpsRtp(sps, pps, null);
}
@Override
public void onSpsPpsVps(ByteBuffer sps, ByteBuffer pps, ByteBuffer vps) {
if (streaming) onSpsPpsVpsRtp(sps, pps, vps);
}
protected abstract void getH264DataRtp(ByteBuffer h264Buffer, MediaCodec.BufferInfo info);
@Override
public void getVideoData(ByteBuffer h264Buffer, MediaCodec.BufferInfo info) {
fpsListener.calculateFps();
recordController.recordVideo(h264Buffer, info);
if (streaming) getH264DataRtp(h264Buffer, info);
}
@Override
public void inputPCMData(Frame frame) {
audioEncoder.inputPCMData(frame);
}
@Override
public void onVideoFormat(MediaFormat mediaFormat) {
recordController.setVideoFormat(mediaFormat);
}
@Override
public void onAudioFormat(MediaFormat mediaFormat) {
recordController.setAudioFormat(mediaFormat);
}
public abstract void setLogs(boolean enable);
}
|
package gjavac.test.nft.erc721ForeverReward;
/**
* Description: DemoContract
* Created by moloq on 2021/11/17 15:46
*/
public class ERC721ForeverRewardStorage {
public String name;
public String symbol;
public String state;
public String admin;
public String fixedSellContract;
public String auctionContract;
public int allTokenCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getFixedSellContract() {
return fixedSellContract;
}
public void setFixedSellContract(String fixedSellContract) {
this.fixedSellContract = fixedSellContract;
}
public String getAuctionContract() {
return auctionContract;
}
public void setAuctionContract(String auctionContract) {
this.auctionContract = auctionContract;
}
public int getAllTokenCount() {
return allTokenCount;
}
public void setAllTokenCount(int allTokenCount) {
this.allTokenCount = allTokenCount;
}
}
|
// 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.api.ads.adwords.awreporting.model.entities;
import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvField;
import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvReport;
import com.google.api.ads.adwords.awreporting.model.csv.annotation.MoneyField;
import com.google.api.ads.adwords.awreporting.model.util.BigDecimalUtil;
import com.google.api.ads.adwords.lib.jaxb.v201809.ReportDefinitionReportType;
import java.math.BigDecimal;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
/**
* Specific report class for AgeRangePerformanceReport.
*
*/
@Entity
@Table(name = "AW_AgeRangePerformanceReport")
@CsvReport(value = ReportDefinitionReportType.AGE_RANGE_PERFORMANCE_REPORT)
public class AgeRangePerformanceReport extends DateReport {
@Column(name = "AccountCurrencyCode")
@CsvField(value = "Currency", reportField = "AccountCurrencyCode")
private String accountCurrencyCode;
@Column(name = "AccountDescriptiveName")
@CsvField(value = "Account", reportField = "AccountDescriptiveName")
private String accountDescriptiveName;
@Column(name = "AccountTimeZone")
@CsvField(value = "Time zone", reportField = "AccountTimeZone")
private String accountTimeZone;
@Column(name = "ActiveViewCpm")
@CsvField(value = "Active View avg. CPM", reportField = "ActiveViewCpm")
@MoneyField
private BigDecimal activeViewCpm;
@Column(name = "ActiveViewCtr")
@CsvField(value = "Active View viewable CTR", reportField = "ActiveViewCtr")
private BigDecimal activeViewCtr;
@Column(name = "ActiveViewImpressions")
@CsvField(value = "Active View viewable impressions", reportField = "ActiveViewImpressions")
private Long activeViewImpressions;
@Column(name = "ActiveViewMeasurability")
@CsvField(value = "Active View measurable impr. / impr.", reportField = "ActiveViewMeasurability")
private BigDecimal activeViewMeasurability;
@Column(name = "ActiveViewMeasurableCost")
@CsvField(value = "Active View measurable cost", reportField = "ActiveViewMeasurableCost")
@MoneyField
private BigDecimal activeViewMeasurableCost;
@Column(name = "ActiveViewMeasurableImpressions")
@CsvField(value = "Active View measurable impr.", reportField = "ActiveViewMeasurableImpressions")
private Long activeViewMeasurableImpressions;
@Column(name = "ActiveViewViewability")
@CsvField(value = "Active View viewable impr. / measurable impr.", reportField = "ActiveViewViewability")
private BigDecimal activeViewViewability;
@Column(name = "AdGroupId")
@CsvField(value = "Ad group ID", reportField = "AdGroupId")
private Long adGroupId;
@Column(name = "AdGroupName")
@CsvField(value = "Ad group", reportField = "AdGroupName")
private String adGroupName;
@Column(name = "AdGroupStatus")
@CsvField(value = "Ad group state", reportField = "AdGroupStatus")
private String adGroupStatus;
@Column(name = "AdNetworkType1")
@CsvField(value = "Network", reportField = "AdNetworkType1")
private String adNetworkType1;
@Column(name = "AdNetworkType2")
@CsvField(value = "Network (with search partners)", reportField = "AdNetworkType2")
private String adNetworkType2;
@Column(name = "AllConversionRate")
@CsvField(value = "All conv. rate", reportField = "AllConversionRate")
private BigDecimal allConversionRate;
@Column(name = "AllConversions")
@CsvField(value = "All conv.", reportField = "AllConversions")
private BigDecimal allConversions;
@Column(name = "AllConversionValue")
@CsvField(value = "All conv. value", reportField = "AllConversionValue")
private BigDecimal allConversionValue;
@Column(name = "AverageCost")
@CsvField(value = "Avg. Cost", reportField = "AverageCost")
@MoneyField
private BigDecimal averageCost;
@Column(name = "AverageCpc")
@CsvField(value = "Avg. CPC", reportField = "AverageCpc")
@MoneyField
private BigDecimal averageCpc;
@Column(name = "AverageCpe")
@CsvField(value = "Avg. CPE", reportField = "AverageCpe")
private BigDecimal averageCpe;
@Column(name = "AverageCpm")
@CsvField(value = "Avg. CPM", reportField = "AverageCpm")
@MoneyField
private BigDecimal averageCpm;
@Column(name = "AverageCpv")
@CsvField(value = "Avg. CPV", reportField = "AverageCpv")
private BigDecimal averageCpv;
@Column(name = "BaseAdGroupId")
@CsvField(value = "Base Ad group ID", reportField = "BaseAdGroupId")
private Long baseAdGroupId;
@Column(name = "BaseCampaignId")
@CsvField(value = "Base Campaign ID", reportField = "BaseCampaignId")
private Long baseCampaignId;
@Column(name = "BiddingStrategyId")
@CsvField(value = "Bid Strategy ID", reportField = "BiddingStrategyId")
private Long biddingStrategyId;
@Column(name = "BiddingStrategyName")
@CsvField(value = "Bid Strategy Name", reportField = "BiddingStrategyName")
private String biddingStrategyName;
@Column(name = "BiddingStrategyType")
@CsvField(value = "Bid Strategy Type", reportField = "BiddingStrategyType")
private String biddingStrategyType;
@Column(name = "BidModifier")
@CsvField(value = "Bid adj.", reportField = "BidModifier")
private BigDecimal bidModifier;
@Column(name = "CampaignId")
@CsvField(value = "Campaign ID", reportField = "CampaignId")
private Long campaignId;
@Column(name = "CampaignName")
@CsvField(value = "Campaign", reportField = "CampaignName")
private String campaignName;
@Column(name = "CampaignStatus")
@CsvField(value = "Campaign state", reportField = "CampaignStatus")
private String campaignStatus;
@Column(name = "Clicks")
@CsvField(value = "Clicks", reportField = "Clicks")
private Long clicks;
@Column(name = "ClickType")
@CsvField(value = "Click type", reportField = "ClickType")
private String clickType;
@Column(name = "ConversionCategoryName")
@CsvField(value = "Conversion category", reportField = "ConversionCategoryName")
private String conversionCategoryName;
@Column(name = "ConversionRate")
@CsvField(value = "Conv. rate", reportField = "ConversionRate")
private BigDecimal conversionRate;
@Column(name = "Conversions")
@CsvField(value = "Conversions", reportField = "Conversions")
private BigDecimal conversions;
@Column(name = "ConversionTrackerId")
@CsvField(value = "Conversion Tracker Id", reportField = "ConversionTrackerId")
private Long conversionTrackerId;
@Column(name = "ConversionTypeName")
@CsvField(value = "Conversion name", reportField = "ConversionTypeName")
private String conversionTypeName;
@Column(name = "ConversionValue")
@CsvField(value = "Total conv. value", reportField = "ConversionValue")
private BigDecimal conversionValue;
@Column(name = "Cost")
@CsvField(value = "Cost", reportField = "Cost")
@MoneyField
private BigDecimal cost;
@Column(name = "CostPerAllConversion")
@CsvField(value = "Cost / all conv.", reportField = "CostPerAllConversion")
@MoneyField
private BigDecimal costPerAllConversion;
@Column(name = "CostPerConversion")
@CsvField(value = "Cost / conv.", reportField = "CostPerConversion")
@MoneyField
private BigDecimal costPerConversion;
@Column(name = "CpcBid")
@CsvField(value = "Max. CPC", reportField = "CpcBid")
@MoneyField
private BigDecimal cpcBid;
@Column(name = "CpcBidSource")
@CsvField(value = "Max CPC source", reportField = "CpcBidSource")
private String cpcBidSource;
@Column(name = "CpmBid")
@CsvField(value = "Max. CPM", reportField = "CpmBid")
@MoneyField
private BigDecimal cpmBid;
@Column(name = "CpmBidSource")
@CsvField(value = "Max CPM Source", reportField = "CpmBidSource")
private String cpmBidSource;
@Column(name = "Criteria")
@CsvField(value = "Age Range", reportField = "Criteria")
private String criteria;
@Column(name = "CriteriaDestinationUrl")
@Lob
@CsvField(value = "Destination URL", reportField = "CriteriaDestinationUrl")
private String criteriaDestinationUrl;
@Column(name = "CrossDeviceConversions")
@CsvField(value = "Cross-device conv.", reportField = "CrossDeviceConversions")
private BigDecimal crossDeviceConversions;
@Column(name = "Ctr")
@CsvField(value = "CTR", reportField = "Ctr")
private BigDecimal ctr;
@Column(name = "CustomerDescriptiveName")
@CsvField(value = "Client name", reportField = "CustomerDescriptiveName")
private String customerDescriptiveName;
@Column(name = "Device")
@CsvField(value = "Device", reportField = "Device")
private String device;
@Column(name = "EngagementRate")
@CsvField(value = "Engagement rate", reportField = "EngagementRate")
private BigDecimal engagementRate;
@Column(name = "Engagements")
@CsvField(value = "Engagements", reportField = "Engagements")
private Long engagements;
@Column(name = "ExternalConversionSource")
@CsvField(value = "Conversion source", reportField = "ExternalConversionSource")
private String externalConversionSource;
@Column(name = "FinalAppUrls")
@Lob
@CsvField(value = "App final URL", reportField = "FinalAppUrls")
private String finalAppUrls;
@Column(name = "FinalMobileUrls")
@Lob
@CsvField(value = "Mobile final URL", reportField = "FinalMobileUrls")
private String finalMobileUrls;
@Column(name = "FinalUrls")
@Lob
@CsvField(value = "Final URL", reportField = "FinalUrls")
private String finalUrls;
@Column(name = "GmailForwards")
@CsvField(value = "Gmail forwards", reportField = "GmailForwards")
private Long gmailForwards;
@Column(name = "GmailSaves")
@CsvField(value = "Gmail saves", reportField = "GmailSaves")
private Long gmailSaves;
@Column(name = "GmailSecondaryClicks")
@CsvField(value = "Gmail clicks to website", reportField = "GmailSecondaryClicks")
private Long gmailSecondaryClicks;
@Column(name = "Id")
@CsvField(value = "Criterion ID", reportField = "Id")
private Long id;
@Column(name = "Impressions")
@CsvField(value = "Impressions", reportField = "Impressions")
private Long impressions;
@Column(name = "InteractionRate")
@CsvField(value = "Interaction Rate", reportField = "InteractionRate")
private BigDecimal interactionRate;
@Column(name = "Interactions")
@CsvField(value = "Interactions", reportField = "Interactions")
private Long interactions;
@Column(name = "InteractionTypes")
@CsvField(value = "Interaction Types", reportField = "InteractionTypes")
private String interactionTypes;
@Column(name = "IsNegative")
@CsvField(value = "Is negative", reportField = "IsNegative")
private String isNegative;
@Column(name = "IsRestrict")
@CsvField(value = "Is restricting", reportField = "IsRestrict")
private String isRestrict;
@Column(name = "Status")
@CsvField(value = "Age Range state", reportField = "Status")
private String status;
@Column(name = "TrackingUrlTemplate")
@Lob
@CsvField(value = "Tracking template", reportField = "TrackingUrlTemplate")
private String trackingUrlTemplate;
@Column(name = "UrlCustomParameters")
@Lob
@CsvField(value = "Custom parameter", reportField = "UrlCustomParameters")
private String urlCustomParameters;
@Column(name = "ValuePerAllConversion")
@CsvField(value = "Value / all conv.", reportField = "ValuePerAllConversion")
private BigDecimal valuePerAllConversion;
@Column(name = "ValuePerConversion")
@CsvField(value = "Value / conv.", reportField = "ValuePerConversion")
private BigDecimal valuePerConversion;
@Column(name = "VideoQuartile100Rate")
@CsvField(value = "Video played to 100%", reportField = "VideoQuartile100Rate")
private BigDecimal videoQuartile100Rate;
@Column(name = "VideoQuartile25Rate")
@CsvField(value = "Video played to 25%", reportField = "VideoQuartile25Rate")
private BigDecimal videoQuartile25Rate;
@Column(name = "VideoQuartile50Rate")
@CsvField(value = "Video played to 50%", reportField = "VideoQuartile50Rate")
private BigDecimal videoQuartile50Rate;
@Column(name = "VideoQuartile75Rate")
@CsvField(value = "Video played to 75%", reportField = "VideoQuartile75Rate")
private BigDecimal videoQuartile75Rate;
@Column(name = "VideoViewRate")
@CsvField(value = "View rate", reportField = "VideoViewRate")
private BigDecimal videoViewRate;
@Column(name = "VideoViews")
@CsvField(value = "Views", reportField = "VideoViews")
private Long videoViews;
@Column(name = "ViewThroughConversions")
@CsvField(value = "View-through conv.", reportField = "ViewThroughConversions")
private Long viewThroughConversions;
/**
* Hibernate needs an empty constructor
*/
public AgeRangePerformanceReport() {
}
public AgeRangePerformanceReport(Long topAccountId, Long accountId){
super(topAccountId, accountId);
}
public String getAccountCurrencyCode() {
return accountCurrencyCode;
}
public void setAccountCurrencyCode(String accountCurrencyCode) {
this.accountCurrencyCode = accountCurrencyCode;
}
public String getAccountDescriptiveName() {
return accountDescriptiveName;
}
public void setAccountDescriptiveName(String accountDescriptiveName) {
this.accountDescriptiveName = accountDescriptiveName;
}
public String getAccountTimeZone() {
return accountTimeZone;
}
public void setAccountTimeZone(String accountTimeZone) {
this.accountTimeZone = accountTimeZone;
}
public BigDecimal getActiveViewCpm() {
return activeViewCpm;
}
public void setActiveViewCpm(BigDecimal activeViewCpm) {
this.activeViewCpm = activeViewCpm;
}
public String getActiveViewCtr() {
return BigDecimalUtil.formatAsReadable(activeViewCtr);
}
public BigDecimal getActiveViewCtrBigDecimal() {
return activeViewCtr;
}
public void setActiveViewCtr(String activeViewCtr) {
this.activeViewCtr = BigDecimalUtil.parseFromNumberString(activeViewCtr);
}
public Long getActiveViewImpressions() {
return activeViewImpressions;
}
public void setActiveViewImpressions(Long activeViewImpressions) {
this.activeViewImpressions = activeViewImpressions;
}
public String getActiveViewMeasurability() {
return BigDecimalUtil.formatAsReadable(activeViewMeasurability);
}
public BigDecimal getActiveViewMeasurabilityBigDecimal() {
return activeViewMeasurability;
}
public void setActiveViewMeasurability(String activeViewMeasurability) {
this.activeViewMeasurability = BigDecimalUtil.parseFromNumberString(activeViewMeasurability);
}
public BigDecimal getActiveViewMeasurableCost() {
return activeViewMeasurableCost;
}
public void setActiveViewMeasurableCost(BigDecimal activeViewMeasurableCost) {
this.activeViewMeasurableCost = activeViewMeasurableCost;
}
public Long getActiveViewMeasurableImpressions() {
return activeViewMeasurableImpressions;
}
public void setActiveViewMeasurableImpressions(Long activeViewMeasurableImpressions) {
this.activeViewMeasurableImpressions = activeViewMeasurableImpressions;
}
public String getActiveViewViewability() {
return BigDecimalUtil.formatAsReadable(activeViewViewability);
}
public BigDecimal getActiveViewViewabilityBigDecimal() {
return activeViewViewability;
}
public void setActiveViewViewability(String activeViewViewability) {
this.activeViewViewability = BigDecimalUtil.parseFromNumberString(activeViewViewability);
}
public Long getAdGroupId() {
return adGroupId;
}
public void setAdGroupId(Long adGroupId) {
this.adGroupId = adGroupId;
}
public String getAdGroupName() {
return adGroupName;
}
public void setAdGroupName(String adGroupName) {
this.adGroupName = adGroupName;
}
public String getAdGroupStatus() {
return adGroupStatus;
}
public void setAdGroupStatus(String adGroupStatus) {
this.adGroupStatus = adGroupStatus;
}
public String getAdNetworkType1() {
return adNetworkType1;
}
public void setAdNetworkType1(String adNetworkType1) {
this.adNetworkType1 = adNetworkType1;
}
public String getAdNetworkType2() {
return adNetworkType2;
}
public void setAdNetworkType2(String adNetworkType2) {
this.adNetworkType2 = adNetworkType2;
}
public String getAllConversionRate() {
return BigDecimalUtil.formatAsReadable(allConversionRate);
}
public BigDecimal getAllConversionRateBigDecimal() {
return allConversionRate;
}
public void setAllConversionRate(String allConversionRate) {
this.allConversionRate = BigDecimalUtil.parseFromNumberString(allConversionRate);
}
public String getAllConversions() {
return BigDecimalUtil.formatAsReadable(allConversions);
}
public BigDecimal getAllConversionsBigDecimal() {
return allConversions;
}
public void setAllConversions(String allConversions) {
this.allConversions = BigDecimalUtil.parseFromNumberString(allConversions);
}
public String getAllConversionValue() {
return BigDecimalUtil.formatAsReadable(allConversionValue);
}
public BigDecimal getAllConversionValueBigDecimal() {
return allConversionValue;
}
public void setAllConversionValue(String allConversionValue) {
this.allConversionValue = BigDecimalUtil.parseFromNumberString(allConversionValue);
}
public BigDecimal getAverageCost() {
return averageCost;
}
public void setAverageCost(BigDecimal averageCost) {
this.averageCost = averageCost;
}
public BigDecimal getAverageCpc() {
return averageCpc;
}
public void setAverageCpc(BigDecimal averageCpc) {
this.averageCpc = averageCpc;
}
public String getAverageCpe() {
return BigDecimalUtil.formatAsReadable(averageCpe);
}
public BigDecimal getAverageCpeBigDecimal() {
return averageCpe;
}
public void setAverageCpe(String averageCpe) {
this.averageCpe = BigDecimalUtil.parseFromNumberString(averageCpe);
}
public BigDecimal getAverageCpm() {
return averageCpm;
}
public void setAverageCpm(BigDecimal averageCpm) {
this.averageCpm = averageCpm;
}
public String getAverageCpv() {
return BigDecimalUtil.formatAsReadable(averageCpv);
}
public BigDecimal getAverageCpvBigDecimal() {
return averageCpv;
}
public void setAverageCpv(String averageCpv) {
this.averageCpv = BigDecimalUtil.parseFromNumberString(averageCpv);
}
public Long getBaseAdGroupId() {
return baseAdGroupId;
}
public void setBaseAdGroupId(Long baseAdGroupId) {
this.baseAdGroupId = baseAdGroupId;
}
public Long getBaseCampaignId() {
return baseCampaignId;
}
public void setBaseCampaignId(Long baseCampaignId) {
this.baseCampaignId = baseCampaignId;
}
public Long getBiddingStrategyId() {
return biddingStrategyId;
}
public void setBiddingStrategyId(Long biddingStrategyId) {
this.biddingStrategyId = biddingStrategyId;
}
public String getBiddingStrategyName() {
return biddingStrategyName;
}
public void setBiddingStrategyName(String biddingStrategyName) {
this.biddingStrategyName = biddingStrategyName;
}
public String getBiddingStrategyType() {
return biddingStrategyType;
}
public void setBiddingStrategyType(String biddingStrategyType) {
this.biddingStrategyType = biddingStrategyType;
}
public String getBidModifier() {
return BigDecimalUtil.formatAsReadable(bidModifier);
}
public BigDecimal getBidModifierBigDecimal() {
return bidModifier;
}
public void setBidModifier(String bidModifier) {
this.bidModifier = BigDecimalUtil.parseFromNumberString(bidModifier);
}
public Long getCampaignId() {
return campaignId;
}
public void setCampaignId(Long campaignId) {
this.campaignId = campaignId;
}
public String getCampaignName() {
return campaignName;
}
public void setCampaignName(String campaignName) {
this.campaignName = campaignName;
}
public String getCampaignStatus() {
return campaignStatus;
}
public void setCampaignStatus(String campaignStatus) {
this.campaignStatus = campaignStatus;
}
public Long getClicks() {
return clicks;
}
public void setClicks(Long clicks) {
this.clicks = clicks;
}
public String getClickType() {
return clickType;
}
public void setClickType(String clickType) {
this.clickType = clickType;
}
public String getConversionCategoryName() {
return conversionCategoryName;
}
public void setConversionCategoryName(String conversionCategoryName) {
this.conversionCategoryName = conversionCategoryName;
}
public String getConversionRate() {
return BigDecimalUtil.formatAsReadable(conversionRate);
}
public BigDecimal getConversionRateBigDecimal() {
return conversionRate;
}
public void setConversionRate(String conversionRate) {
this.conversionRate = BigDecimalUtil.parseFromNumberString(conversionRate);
}
public String getConversions() {
return BigDecimalUtil.formatAsReadable(conversions);
}
public BigDecimal getConversionsBigDecimal() {
return conversions;
}
public void setConversions(String conversions) {
this.conversions = BigDecimalUtil.parseFromNumberString(conversions);
}
public Long getConversionTrackerId() {
return conversionTrackerId;
}
public void setConversionTrackerId(Long conversionTrackerId) {
this.conversionTrackerId = conversionTrackerId;
}
public String getConversionTypeName() {
return conversionTypeName;
}
public void setConversionTypeName(String conversionTypeName) {
this.conversionTypeName = conversionTypeName;
}
public String getConversionValue() {
return BigDecimalUtil.formatAsReadable(conversionValue);
}
public BigDecimal getConversionValueBigDecimal() {
return conversionValue;
}
public void setConversionValue(String conversionValue) {
this.conversionValue = BigDecimalUtil.parseFromNumberString(conversionValue);
}
public BigDecimal getCost() {
return cost;
}
public void setCost(BigDecimal cost) {
this.cost = cost;
}
public BigDecimal getCostPerAllConversion() {
return costPerAllConversion;
}
public void setCostPerAllConversion(BigDecimal costPerAllConversion) {
this.costPerAllConversion = costPerAllConversion;
}
public BigDecimal getCostPerConversion() {
return costPerConversion;
}
public void setCostPerConversion(BigDecimal costPerConversion) {
this.costPerConversion = costPerConversion;
}
public BigDecimal getCpcBid() {
return cpcBid;
}
public void setCpcBid(BigDecimal cpcBid) {
this.cpcBid = cpcBid;
}
public String getCpcBidSource() {
return cpcBidSource;
}
public void setCpcBidSource(String cpcBidSource) {
this.cpcBidSource = cpcBidSource;
}
public BigDecimal getCpmBid() {
return cpmBid;
}
public void setCpmBid(BigDecimal cpmBid) {
this.cpmBid = cpmBid;
}
public String getCpmBidSource() {
return cpmBidSource;
}
public void setCpmBidSource(String cpmBidSource) {
this.cpmBidSource = cpmBidSource;
}
public String getCriteria() {
return criteria;
}
public void setCriteria(String criteria) {
this.criteria = criteria;
}
public String getCriteriaDestinationUrl() {
return criteriaDestinationUrl;
}
public void setCriteriaDestinationUrl(String criteriaDestinationUrl) {
this.criteriaDestinationUrl = criteriaDestinationUrl;
}
public String getCrossDeviceConversions() {
return BigDecimalUtil.formatAsReadable(crossDeviceConversions);
}
public BigDecimal getCrossDeviceConversionsBigDecimal() {
return crossDeviceConversions;
}
public void setCrossDeviceConversions(String crossDeviceConversions) {
this.crossDeviceConversions = BigDecimalUtil.parseFromNumberString(crossDeviceConversions);
}
public String getCtr() {
return BigDecimalUtil.formatAsReadable(ctr);
}
public BigDecimal getCtrBigDecimal() {
return ctr;
}
public void setCtr(String ctr) {
this.ctr = (ctr == null ? null : BigDecimalUtil.parseFromNumberString(ctr.replace("%","")));
}
public String getCustomerDescriptiveName() {
return customerDescriptiveName;
}
public void setCustomerDescriptiveName(String customerDescriptiveName) {
this.customerDescriptiveName = customerDescriptiveName;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getEngagementRate() {
return BigDecimalUtil.formatAsReadable(engagementRate);
}
public BigDecimal getEngagementRateBigDecimal() {
return engagementRate;
}
public void setEngagementRate(String engagementRate) {
this.engagementRate = BigDecimalUtil.parseFromNumberString(engagementRate);
}
public Long getEngagements() {
return engagements;
}
public void setEngagements(Long engagements) {
this.engagements = engagements;
}
public String getExternalConversionSource() {
return externalConversionSource;
}
public void setExternalConversionSource(String externalConversionSource) {
this.externalConversionSource = externalConversionSource;
}
public String getFinalAppUrls() {
return finalAppUrls;
}
public void setFinalAppUrls(String finalAppUrls) {
this.finalAppUrls = finalAppUrls;
}
public String getFinalMobileUrls() {
return finalMobileUrls;
}
public void setFinalMobileUrls(String finalMobileUrls) {
this.finalMobileUrls = finalMobileUrls;
}
public String getFinalUrls() {
return finalUrls;
}
public void setFinalUrls(String finalUrls) {
this.finalUrls = finalUrls;
}
public Long getGmailForwards() {
return gmailForwards;
}
public void setGmailForwards(Long gmailForwards) {
this.gmailForwards = gmailForwards;
}
public Long getGmailSaves() {
return gmailSaves;
}
public void setGmailSaves(Long gmailSaves) {
this.gmailSaves = gmailSaves;
}
public Long getGmailSecondaryClicks() {
return gmailSecondaryClicks;
}
public void setGmailSecondaryClicks(Long gmailSecondaryClicks) {
this.gmailSecondaryClicks = gmailSecondaryClicks;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getImpressions() {
return impressions;
}
public void setImpressions(Long impressions) {
this.impressions = impressions;
}
public String getInteractionRate() {
return BigDecimalUtil.formatAsReadable(interactionRate);
}
public BigDecimal getInteractionRateBigDecimal() {
return interactionRate;
}
public void setInteractionRate(String interactionRate) {
this.interactionRate = BigDecimalUtil.parseFromNumberString(interactionRate);
}
public Long getInteractions() {
return interactions;
}
public void setInteractions(Long interactions) {
this.interactions = interactions;
}
public String getInteractionTypes() {
return interactionTypes;
}
public void setInteractionTypes(String interactionTypes) {
this.interactionTypes = interactionTypes;
}
public String getIsNegative() {
return isNegative;
}
public void setIsNegative(String isNegative) {
this.isNegative = isNegative;
}
public String getIsRestrict() {
return isRestrict;
}
public void setIsRestrict(String isRestrict) {
this.isRestrict = isRestrict;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTrackingUrlTemplate() {
return trackingUrlTemplate;
}
public void setTrackingUrlTemplate(String trackingUrlTemplate) {
this.trackingUrlTemplate = trackingUrlTemplate;
}
public String getUrlCustomParameters() {
return urlCustomParameters;
}
public void setUrlCustomParameters(String urlCustomParameters) {
this.urlCustomParameters = urlCustomParameters;
}
public String getValuePerAllConversion() {
return BigDecimalUtil.formatAsReadable(valuePerAllConversion);
}
public BigDecimal getValuePerAllConversionBigDecimal() {
return valuePerAllConversion;
}
public void setValuePerAllConversion(String valuePerAllConversion) {
this.valuePerAllConversion = BigDecimalUtil.parseFromNumberString(valuePerAllConversion);
}
public String getValuePerConversion() {
return BigDecimalUtil.formatAsReadable(valuePerConversion);
}
public BigDecimal getValuePerConversionBigDecimal() {
return valuePerConversion;
}
public void setValuePerConversion(String valuePerConversion) {
this.valuePerConversion = BigDecimalUtil.parseFromNumberString(valuePerConversion);
}
public String getVideoQuartile100Rate() {
return BigDecimalUtil.formatAsReadable(videoQuartile100Rate);
}
public BigDecimal getVideoQuartile100RateBigDecimal() {
return videoQuartile100Rate;
}
public void setVideoQuartile100Rate(String videoQuartile100Rate) {
this.videoQuartile100Rate = BigDecimalUtil.parseFromNumberString(videoQuartile100Rate);
}
public String getVideoQuartile25Rate() {
return BigDecimalUtil.formatAsReadable(videoQuartile25Rate);
}
public BigDecimal getVideoQuartile25RateBigDecimal() {
return videoQuartile25Rate;
}
public void setVideoQuartile25Rate(String videoQuartile25Rate) {
this.videoQuartile25Rate = BigDecimalUtil.parseFromNumberString(videoQuartile25Rate);
}
public String getVideoQuartile50Rate() {
return BigDecimalUtil.formatAsReadable(videoQuartile50Rate);
}
public BigDecimal getVideoQuartile50RateBigDecimal() {
return videoQuartile50Rate;
}
public void setVideoQuartile50Rate(String videoQuartile50Rate) {
this.videoQuartile50Rate = BigDecimalUtil.parseFromNumberString(videoQuartile50Rate);
}
public String getVideoQuartile75Rate() {
return BigDecimalUtil.formatAsReadable(videoQuartile75Rate);
}
public BigDecimal getVideoQuartile75RateBigDecimal() {
return videoQuartile75Rate;
}
public void setVideoQuartile75Rate(String videoQuartile75Rate) {
this.videoQuartile75Rate = BigDecimalUtil.parseFromNumberString(videoQuartile75Rate);
}
public String getVideoViewRate() {
return BigDecimalUtil.formatAsReadable(videoViewRate);
}
public BigDecimal getVideoViewRateBigDecimal() {
return videoViewRate;
}
public void setVideoViewRate(String videoViewRate) {
this.videoViewRate = BigDecimalUtil.parseFromNumberString(videoViewRate);
}
public Long getVideoViews() {
return videoViews;
}
public void setVideoViews(Long videoViews) {
this.videoViews = videoViews;
}
public Long getViewThroughConversions() {
return viewThroughConversions;
}
public void setViewThroughConversions(Long viewThroughConversions) {
this.viewThroughConversions = viewThroughConversions;
}
@Override
public void setRowId() {
// General fields for generating unique id.
StringBuilder idBuilder = new StringBuilder(getCustomerId().toString());
if (campaignId != null) {
idBuilder.append("-").append(campaignId);
}
if (adGroupId != null) {
idBuilder.append("-").append(adGroupId);
}
if (id != null) {
idBuilder.append("-").append(id);
}
idBuilder.append("-").append(getDateLabel());
// Include all segmentation fields (if set).
if (!StringUtils.isEmpty(adNetworkType1)) {
idBuilder.append("-").append(adNetworkType1);
}
if (!StringUtils.isEmpty(adNetworkType2)) {
idBuilder.append("-").append(adNetworkType2);
}
if (!StringUtils.isEmpty(clickType)) {
idBuilder.append("-").append(clickType);
}
if (!StringUtils.isEmpty(conversionCategoryName)) {
idBuilder.append("-").append(conversionCategoryName);
}
if (conversionTrackerId != null) {
idBuilder.append("-").append(conversionTrackerId);
}
if (!StringUtils.isEmpty(conversionTypeName)) {
idBuilder.append("-").append(conversionTypeName);
}
if (!StringUtils.isEmpty(device)) {
idBuilder.append("-").append(device);
}
if (!StringUtils.isEmpty(externalConversionSource)) {
idBuilder.append("-").append(externalConversionSource);
}
this.rowId = idBuilder.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) { return false; }
AgeRangePerformanceReport other = (AgeRangePerformanceReport) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(accountCurrencyCode, other.accountCurrencyCode)
.append(accountDescriptiveName, other.accountDescriptiveName)
.append(accountTimeZone, other.accountTimeZone)
.append(activeViewCpm, other.activeViewCpm)
.append(activeViewCtr, other.activeViewCtr)
.append(activeViewImpressions, other.activeViewImpressions)
.append(activeViewMeasurability, other.activeViewMeasurability)
.append(activeViewMeasurableCost, other.activeViewMeasurableCost)
.append(activeViewMeasurableImpressions, other.activeViewMeasurableImpressions)
.append(activeViewViewability, other.activeViewViewability)
.append(adGroupId, other.adGroupId)
.append(adGroupName, other.adGroupName)
.append(adGroupStatus, other.adGroupStatus)
.append(adNetworkType1, other.adNetworkType1)
.append(adNetworkType2, other.adNetworkType2)
.append(allConversionRate, other.allConversionRate)
.append(allConversions, other.allConversions)
.append(allConversionValue, other.allConversionValue)
.append(averageCost, other.averageCost)
.append(averageCpc, other.averageCpc)
.append(averageCpe, other.averageCpe)
.append(averageCpm, other.averageCpm)
.append(averageCpv, other.averageCpv)
.append(baseAdGroupId, other.baseAdGroupId)
.append(baseCampaignId, other.baseCampaignId)
.append(biddingStrategyId, other.biddingStrategyId)
.append(biddingStrategyName, other.biddingStrategyName)
.append(biddingStrategyType, other.biddingStrategyType)
.append(bidModifier, other.bidModifier)
.append(campaignId, other.campaignId)
.append(campaignName, other.campaignName)
.append(campaignStatus, other.campaignStatus)
.append(clicks, other.clicks)
.append(clickType, other.clickType)
.append(conversionCategoryName, other.conversionCategoryName)
.append(conversionRate, other.conversionRate)
.append(conversions, other.conversions)
.append(conversionTrackerId, other.conversionTrackerId)
.append(conversionTypeName, other.conversionTypeName)
.append(conversionValue, other.conversionValue)
.append(cost, other.cost)
.append(costPerAllConversion, other.costPerAllConversion)
.append(costPerConversion, other.costPerConversion)
.append(cpcBid, other.cpcBid)
.append(cpcBidSource, other.cpcBidSource)
.append(cpmBid, other.cpmBid)
.append(cpmBidSource, other.cpmBidSource)
.append(criteria, other.criteria)
.append(criteriaDestinationUrl, other.criteriaDestinationUrl)
.append(crossDeviceConversions, other.crossDeviceConversions)
.append(ctr, other.ctr)
.append(customerDescriptiveName, other.customerDescriptiveName)
.append(device, other.device)
.append(engagementRate, other.engagementRate)
.append(engagements, other.engagements)
.append(externalConversionSource, other.externalConversionSource)
.append(finalAppUrls, other.finalAppUrls)
.append(finalMobileUrls, other.finalMobileUrls)
.append(finalUrls, other.finalUrls)
.append(gmailForwards, other.gmailForwards)
.append(gmailSaves, other.gmailSaves)
.append(gmailSecondaryClicks, other.gmailSecondaryClicks)
.append(id, other.id)
.append(impressions, other.impressions)
.append(interactionRate, other.interactionRate)
.append(interactions, other.interactions)
.append(interactionTypes, other.interactionTypes)
.append(isNegative, other.isNegative)
.append(isRestrict, other.isRestrict)
.append(status, other.status)
.append(trackingUrlTemplate, other.trackingUrlTemplate)
.append(urlCustomParameters, other.urlCustomParameters)
.append(valuePerAllConversion, other.valuePerAllConversion)
.append(valuePerConversion, other.valuePerConversion)
.append(videoQuartile100Rate, other.videoQuartile100Rate)
.append(videoQuartile25Rate, other.videoQuartile25Rate)
.append(videoQuartile50Rate, other.videoQuartile50Rate)
.append(videoQuartile75Rate, other.videoQuartile75Rate)
.append(videoViewRate, other.videoViewRate)
.append(videoViews, other.videoViews)
.append(viewThroughConversions, other.viewThroughConversions)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.appendSuper(super.hashCode())
.append(accountCurrencyCode)
.append(accountDescriptiveName)
.append(accountTimeZone)
.append(activeViewCpm)
.append(activeViewCtr)
.append(activeViewImpressions)
.append(activeViewMeasurability)
.append(activeViewMeasurableCost)
.append(activeViewMeasurableImpressions)
.append(activeViewViewability)
.append(adGroupId)
.append(adGroupName)
.append(adGroupStatus)
.append(adNetworkType1)
.append(adNetworkType2)
.append(allConversionRate)
.append(allConversions)
.append(allConversionValue)
.append(averageCost)
.append(averageCpc)
.append(averageCpe)
.append(averageCpm)
.append(averageCpv)
.append(baseAdGroupId)
.append(baseCampaignId)
.append(biddingStrategyId)
.append(biddingStrategyName)
.append(biddingStrategyType)
.append(bidModifier)
.append(campaignId)
.append(campaignName)
.append(campaignStatus)
.append(clicks)
.append(clickType)
.append(conversionCategoryName)
.append(conversionRate)
.append(conversions)
.append(conversionTrackerId)
.append(conversionTypeName)
.append(conversionValue)
.append(cost)
.append(costPerAllConversion)
.append(costPerConversion)
.append(cpcBid)
.append(cpcBidSource)
.append(cpmBid)
.append(cpmBidSource)
.append(criteria)
.append(criteriaDestinationUrl)
.append(crossDeviceConversions)
.append(ctr)
.append(customerDescriptiveName)
.append(device)
.append(engagementRate)
.append(engagements)
.append(externalConversionSource)
.append(finalAppUrls)
.append(finalMobileUrls)
.append(finalUrls)
.append(gmailForwards)
.append(gmailSaves)
.append(gmailSecondaryClicks)
.append(id)
.append(impressions)
.append(interactionRate)
.append(interactions)
.append(interactionTypes)
.append(isNegative)
.append(isRestrict)
.append(status)
.append(trackingUrlTemplate)
.append(urlCustomParameters)
.append(valuePerAllConversion)
.append(valuePerConversion)
.append(videoQuartile100Rate)
.append(videoQuartile25Rate)
.append(videoQuartile50Rate)
.append(videoQuartile75Rate)
.append(videoViewRate)
.append(videoViews)
.append(viewThroughConversions)
.toHashCode();
}
}
|
/*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.service.migrator;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.TreatmentAssignment;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import org.springframework.beans.BeanUtils;
public class TreatmentAssignmentMigrator implements Migrator<gov.nih.nci.cabig.caaers.domain.Study> {
/**
* Will migrate {@link TreatmentAssignment}s from source to destination
*/
public void migrate(Study source, Study destination, DomainObjectImportOutcome<Study> outcome) {
//TreatmentAssignments
if (source.getTreatmentAssignments() != null) {
for (TreatmentAssignment treatmentAssignment : source.getTreatmentAssignments()) {
TreatmentAssignment target = new TreatmentAssignment();
BeanUtils.copyProperties(treatmentAssignment, target, new String[]{"study"});
destination.addTreatmentAssignment(target);
}
}
}
}
|
/**
* Conditions3
*/
public class Conditions3 {
public static void main(String[] args) {
int time = 20;
String result = (time < 18) ? "Good Day." : "Good Evening.";
System.out.println(result);
}
}
|
/**
* Copyright © 2015 - 2017 EntDIY JavaEE Development Framework
*
* Site: https://www.entdiy.com, E-Mail: xautlx@hotmail.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.entdiy.sys.vo;
import com.entdiy.core.annotation.MetaData;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
import java.util.Map;
@Getter
@Setter
public class NavMenuVO implements Serializable {
private static final long serialVersionUID = 9047695739997529718L;
@MetaData(value = "编号")
private Long id;
@MetaData(value = "父编号")
private Long parentId;
@MetaData(value = "菜单名称")
private String name;
@MetaData(value = "菜单路径")
private String path;
@MetaData(value = "菜单层级")
private Integer level;
@MetaData(value = "菜单URL")
private String url;
@MetaData(value = "图标样式")
private String style;
@MetaData(value = "展开标识", tooltips = "是否默认展开菜单组")
private Boolean initOpen = Boolean.FALSE;
public Map<String, Object> buildMapDataForTreeDisplay() {
//组装zTree结构数据
Map<String, Object> item = Maps.newHashMap();
item.put("id", this.getId());
item.put("parent", this.getParentId());
item.put("name", this.getName());
item.put("display", this.getName());
item.put("open", true);
item.put("enabledChildrenCount", StringUtils.isBlank(this.getUrl()) ? 1 : 0);
return item;
}
}
|
package com.deviceinsight.kafka.health;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.deviceinsight.kafka.health.config.KafkaHealthProperties;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import io.micrometer.core.instrument.MeterRegistry;
public class KafkaConsumingHealthIndicator extends AbstractHealthIndicator {
private static final Logger logger = LoggerFactory.getLogger(KafkaConsumingHealthIndicator.class);
private static final String CONSUMER_GROUP_PREFIX = "health-check-";
private static final String KAFKA_EXCEPTION = "kafka-exceptions";
private final Consumer<String, String> consumer;
private final Producer<String, String> producer;
private final String topic;
private final Duration sendReceiveTimeout;
private final Duration pollTimeout;
private final Duration subscriptionTimeout;
private final ExecutorService executor;
private final AtomicBoolean running;
private final Cache<String, String> cache;
private KafkaCommunicationResult kafkaCommunicationResult;
@Autowired
private MeterRegistry meterRegistry;
public KafkaConsumingHealthIndicator(KafkaHealthProperties kafkaHealthProperties,
Map<String, Object> kafkaConsumerProperties, Map<String, Object> kafkaProducerProperties,
@Autowired MeterRegistry meterRegistry) {
logger.info("Initializing kafka health check with properties: {}", kafkaHealthProperties);
this.topic = kafkaHealthProperties.getTopic();
this.sendReceiveTimeout = kafkaHealthProperties.getSendReceiveTimeout();
this.pollTimeout = kafkaHealthProperties.getPollTimeout();
this.subscriptionTimeout = kafkaHealthProperties.getSubscriptionTimeout();
Map<String, Object> kafkaConsumerPropertiesCopy = new HashMap<>(kafkaConsumerProperties);
setConsumerGroup(kafkaConsumerPropertiesCopy);
StringDeserializer deserializer = new StringDeserializer();
StringSerializer serializer = new StringSerializer();
this.consumer = new KafkaConsumer<>(kafkaConsumerPropertiesCopy, deserializer, deserializer);
this.producer = new KafkaProducer<>(kafkaProducerProperties, serializer, serializer);
this.executor = Executors.newSingleThreadExecutor();
this.running = new AtomicBoolean(true);
this.cache = Caffeine.newBuilder().expireAfterWrite(sendReceiveTimeout).build();
this.kafkaCommunicationResult = KafkaCommunicationResult
.failure(new RejectedExecutionException("Kafka Health Check is starting."));
this.meterRegistry = meterRegistry;
}
@PostConstruct
void subscribeAndSendMessage() throws InterruptedException {
subscribeToTopic();
if (kafkaCommunicationResult.isFailure()) {
throw new BeanInitializationException("Kafka health check failed", kafkaCommunicationResult.getException());
}
executor.submit(() -> {
while (running.get()) {
ConsumerRecords<String, String> records = consumer.poll(pollTimeout);
records.forEach(record -> cache.put(record.key(), record.value()));
}
});
}
@PreDestroy
void shutdown() {
running.set(false);
executor.shutdownNow();
producer.close();
consumer.close();
}
private void setConsumerGroup(Map<String, Object> kafkaConsumerProperties) {
try {
String groupId = (String) kafkaConsumerProperties.getOrDefault(ConsumerConfig.GROUP_ID_CONFIG,
UUID.randomUUID().toString());
kafkaConsumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG,
CONSUMER_GROUP_PREFIX + groupId + "-" + InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
private void subscribeToTopic() throws InterruptedException {
final CountDownLatch subscribed = new CountDownLatch(1);
logger.info("Subscribe to health check topic={}", topic);
consumer.subscribe(Collections.singleton(topic), new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
// nothing to do her
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
logger.debug("Got partitions = {}", partitions);
if (!partitions.isEmpty()) {
subscribed.countDown();
}
}
});
consumer.poll(pollTimeout);
if (!subscribed.await(subscriptionTimeout.toMillis(), MILLISECONDS)) {
throw new BeanInitializationException("Subscription to kafka failed, topic=" + topic);
}
this.kafkaCommunicationResult = KafkaCommunicationResult.success();
}
private String sendMessage() {
try {
return sendKafkaMessage();
} catch (ExecutionException e) {
logger.warn("Kafka health check execution failed.", e);
this.kafkaCommunicationResult = KafkaCommunicationResult.failure(e);
} catch (TimeoutException | InterruptedException e) {
logger.warn("Kafka health check timed out.", e);
this.kafkaCommunicationResult = KafkaCommunicationResult.failure(e);
} catch (RejectedExecutionException e) {
logger.debug("Ignore health check, already running...");
}
return null;
}
private String sendKafkaMessage() throws InterruptedException, ExecutionException, TimeoutException {
String message = UUID.randomUUID().toString();
logger.trace("Send health check message = {}", message);
producer.send(new ProducerRecord<>(topic, message, message)).get(sendReceiveTimeout.toMillis(), MILLISECONDS);
return message;
}
@Override
protected void doHealthCheck(Health.Builder builder) {
String expectedMessage = sendMessage();
if (expectedMessage == null) {
goDown(builder, kafkaCommunicationResult.getException());
return;
}
long startTime = System.currentTimeMillis();
while (true) {
String receivedMessage = cache.getIfPresent(expectedMessage);
if (expectedMessage.equals(receivedMessage)) {
builder.up();
return;
} else if (System.currentTimeMillis() - startTime > sendReceiveTimeout.toMillis()) {
if (kafkaCommunicationResult.isFailure()) {
goDown(builder, kafkaCommunicationResult.getException());
} else {
builder.down(new TimeoutException("Sending and receiving took longer than " + sendReceiveTimeout))
.withDetail("topic", topic);
}
return;
}
}
}
private void goDown(Health.Builder builder, Exception exception) {
builder.down(exception).withDetail("topic", topic);
meterRegistry.counter(KAFKA_EXCEPTION).increment();
}
}
|
// This class was generated on Thu, 16 May 2019 09:53:44 PDT by version 0.1.0-dev+8fcb5f of Braintree SDK Generator
// MerchantPayableBreakdown.java
// @version 0.1.0-dev+8fcb5f
// @type object
// @data H4sIAAAAAAAC/+yaYW/bNhPH3z+f4uBXzwM4cZs2fYC8WtusWDasDbpswNAVzpk8WUQoUj2e7GrDvvtASrItW9nSIiiwVK8C80jx+Nfdjycyf0yu6pImZ5MfiVWOTuASa1xYghdMeKP92k2mk1+QTWx8jUXsO5lOfqB6++OcgmJTivFucja5ygkW3WDwGUhOwJRVTh9PppPnzFg3kz6aTt4S6jfO1pOzDG2g2PChMkx603DJviQWQ2Fy9m7rrndUH3q2ZB/CHAtfOel5uWc49FhVzORUDeg0NP0g8wwImXHolEELwugCqjhqCqFSOWAAhAVadIrAM5RYF+QEdEX3t9YgbNzycLGdy3PlNfVWu285XO47yZnoSOXIqIQYLn56c/T05PH/t0LEse//O9NehZlxQkvG+ICZNkxKZkxBZl3no9g5zP4HkqOA0eTEZIZCevddp09SRLjaE8RV1v45/UdVVmirvhpdy6EKyTKFdW5UDoVZ5gILOvutevToiaps+kvNL2uaX88dJC2IU3S0S4srteaG4Pr7y1+vGxGQCZwXkLo0Cq2tIeMmdtAeNw+ddU/dmwM0KVOg3YwYnuvq9fnOXKFaaLMymnT00IPkvgrotORheLpZt8JXntscbcQHVxUL4pi6nSOlRUWhTYhehEwhEMG7l13byxgInxo29xEZ73di4xY6OJIhNvSaRzKMZBjJ8GDJsM31+aZGmRuh4u9ose16Czd6HfrB9NwBRv+jZtuqKIVXo1rU15G0ZDmGtyQVO9Kwzsn1sqRfS4EJoE2WEUesZOyLwc6XWF+iBVQqgWudE1MylFgTQe6tTrloGOJTw57gz+69RFPerYiF9BCKB4wjkEcgj0B+sECmj/Gzc0lzRqHDENk3b0Nl33IYMl0PiD0a9TUJcWFcG+4tPMRDC56Go97tQEY8oPOSE39ednwWL4KvWNG8m7C38EPbv5AZA6rcERqCvCQZlubQ9lVJ8yk8baTa2Uvb8uPbD5VZoaUmLWImVM5IV000sbddF7zyXKAI6bi/drj1vKFRcgDWRvL0LPHw+BS0WRoJkMhHwAnm7QQbinnj5F5ku8N3YdkceQ0VJAemsRwZy5GxHHlg5cjdGFGinWdE+3zYNo9sGNkwsuHBfqqUFiXzXLTZvg+IHWvoM2LPcvsBUdezSXoWFwOCKExB+aIwIRjvwjRaF+xviHFJyb45SBq8Zrv/M5yBQmkskEYIjhD8CiCINdF8gYEGa6StrVcj3VIeaRI0douvovsnhHXugUmRWbWBns6mE0CyymbG2qbZsyY+hqvdsSYA2uDhxvm1ixjZnHZ/AW5YQ07mRveZsdN6KEJZLaxRcHG+kSE5exSh1y3qSDFh+souy2O4cMJeV4p0/IYOVVl6FqgCgcIQd4sOoC8YjbtiItgJl+ZrvLkXmLYXAs1lwDUVaOwctWYK4To6cN15MDf6Okob8w5XaGxc9Rc610hu9Q//dh0dVDUumB02UDC/k4Y0Btoxbd4urFc3HyovtJu+Qdi7ZdPy2kuHrdluO/xcRvGfPYUN6EOCBVrr16RhQZmPP52Gk9PT23phFneI+NKbOWLWNhN80066bYFglu4YvvNrWhFP06glOeKEQFSKyhgiBX40RVWAJbeUvAGL668+vsiT013XmxwqUaJqsCLu9piIQAeVSyLpu3oJ9NEE2dBxX+YvEzY7odsLnn77Yei0V2YxJxguzrtNLHIFCgw3pKNAsRa75ZKthXwMQRc3jfgKYnamxJPcsE7VnaFW9v1xAZjSDAtbAznFdXqxqXyCkn3JhgS5hlVcsEuHZy8w0JOTOLYKDRfIxZfSbj+hsvd1nHaHj2XxgnbeFKPDF3239Rirx7F6HKvHB3e89p+/AAAA//8=
// DO NOT EDIT
package com.paypal.orders;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import com.paypal.http.annotations.*;
/**
* The breakdown of the refund.
*/
@Model
public class MerchantPayableBreakdown {
// Required default constructor
public MerchantPayableBreakdown() {}
/**
* The currency and amount for a financial transaction, such as a balance or payment due.
*/
@SerializedName("gross_amount")
private Money grossAmount;
public Money grossAmount() { return grossAmount; }
public MerchantPayableBreakdown grossAmount(Money grossAmount) {
this.grossAmount = grossAmount;
return this;
}
/**
* The currency and amount for a financial transaction, such as a balance or payment due.
*/
@SerializedName("net_amount")
private Money netAmount;
public Money netAmount() { return netAmount; }
public MerchantPayableBreakdown netAmount(Money netAmount) {
this.netAmount = netAmount;
return this;
}
/**
* An array of breakdown values for the net amount. Returned when the currency of the refund is different from the currency of the PayPal account where the payee holds their funds.
*/
@SerializedName(value = "net_amount_breakdown", listClass = NetAmountBreakdownItem.class)
private List<NetAmountBreakdownItem> netAmountBreakdown;
public List<NetAmountBreakdownItem> netAmountBreakdown() { return netAmountBreakdown; }
public MerchantPayableBreakdown netAmountBreakdown(List<NetAmountBreakdownItem> netAmountBreakdown) {
this.netAmountBreakdown = netAmountBreakdown;
return this;
}
/**
* The currency and amount for a financial transaction, such as a balance or payment due.
*/
@SerializedName("paypal_fee")
private Money paypalFee;
public Money paypalFee() { return paypalFee; }
public MerchantPayableBreakdown paypalFee(Money paypalFee) {
this.paypalFee = paypalFee;
return this;
}
/**
* An array of platform or partner fees, commissions, or brokerage fees for the refund.
*/
@SerializedName(value = "platform_fees", listClass = PlatformFee.class)
private List<PlatformFee> platformFees;
public List<PlatformFee> platformFees() { return platformFees; }
public MerchantPayableBreakdown platformFees(List<PlatformFee> platformFees) {
this.platformFees = platformFees;
return this;
}
/**
* The currency and amount for a financial transaction, such as a balance or payment due.
*/
@SerializedName("total_refunded_amount")
private Money totalRefundedAmount;
public Money totalRefundedAmount() { return totalRefundedAmount; }
public MerchantPayableBreakdown totalRefundedAmount(Money totalRefundedAmount) {
this.totalRefundedAmount = totalRefundedAmount;
return this;
}
}
|
package FactoryAndData.B2C;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import CommonFunction.Common;
import TestData.PropsUtils;
import TestScript.B2C.NA18406Test;
public class NA18406 {
@DataProvider(name = "NA18406")
public static Object[][] Ddata15492() {
return Common.getFactoryData(new Object[][] { { "JP" } }, PropsUtils.getTargetStore("NA-18406"));
}
@Factory(dataProvider = "NA18406")
public Object[] createTest(String store) {
Object[] tests = new Object[1];
tests[0] = new NA18406Test(store);
return tests;
}
}
|
package com.example.nishanthkumarg.myapplication;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.nishanthkumarg.myapplication", appContext.getPackageName());
}
}
|
/*
* 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.iotdb.db.qp.logical.sys;
import org.apache.iotdb.db.metadata.PartialPath;
import org.apache.iotdb.db.qp.logical.Operator;
import org.apache.iotdb.db.qp.physical.PhysicalPlan;
import org.apache.iotdb.db.qp.physical.sys.DeleteStorageGroupPlan;
import org.apache.iotdb.db.qp.strategy.PhysicalGenerator;
import java.util.List;
public class DeleteStorageGroupOperator extends Operator {
private List<PartialPath> deletePathList;
public DeleteStorageGroupOperator(int tokenIntType) {
super(tokenIntType);
operatorType = OperatorType.DELETE_STORAGE_GROUP;
}
public List<PartialPath> getDeletePathList() {
return deletePathList;
}
public void setDeletePathList(List<PartialPath> deletePathList) {
this.deletePathList = deletePathList;
}
@Override
public PhysicalPlan generatePhysicalPlan(PhysicalGenerator generator) {
return new DeleteStorageGroupPlan(deletePathList);
}
}
|
package module700packageJava0;
import java.lang.Integer;
public class Foo49 {
Integer int0;
public void foo0() {
new module700packageJava0.Foo48().foo8();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
public void foo6() {
foo5();
}
public void foo7() {
foo6();
}
public void foo8() {
foo7();
}
}
|
package com.example.demo;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.ExpiredJwtException;
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
// JWT Token is in the form "Bearer token". Remove Bearer word and get only the Token
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
} else {
logger.warn("JWT Token does not begin with Bearer String");
}
//Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
// if token is valid configure Spring Security to manually set authentication
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the Spring Security Configurations successfully.
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
|
/**
* 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.storm.testing;
import org.apache.storm.ILocalCluster;
/**
* This is the core interface for the storm java testing, usually
* we put our java unit testing logic in the run method. A sample
* code will be:
*
* ```java
* Testing.withSimulatedTimeLocalCluster(new TestJob() {
* public void run(Cluster cluster) {
* // your testing logic here.
* }
* });
* ```
*/
public interface TestJob {
/**
* run the testing logic with the cluster.
*
* @param cluster the cluster which created by <code>Testing.withSimulatedTimeLocalCluster</code>
* and <code>Testing.withTrackedCluster</code>.
*/
public void run(ILocalCluster cluster) throws Exception;
}
|
package com.izerofx.wenku.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.izerofx.framework.core.persistence.PagingHibernateJdbcDao;
import com.izerofx.wenku.dao.VisitorDaoCustom;
import com.izerofx.wenku.domain.Visitor;
/**
*
* 类名称:VisitorDaoImpl<br>
* 类描述:访客数据访问自定义接口实现<br>
* 创建人:qinjiaxue<br>
* 创建时间:2016年11月7日 下午1:48:14<br>
* @version v1.0
*
*/
public class VisitorDaoImpl implements VisitorDaoCustom<Visitor, String> {
@Autowired
private PagingHibernateJdbcDao dao;
@Override
public List<Visitor> findByUserId(String userId, Integer count) {
StringBuilder sql = new StringBuilder();
sql.append(" select a.*, b.nick_name, b.avatar");
sql.append(" from user_visitor a");
sql.append(" left join user_info b on b.id = a.visitor_user_id");
sql.append(" where a.user_id = ?");
sql.append(" order by a.create_time desc limit ?");
return dao.findList(sql.toString(), new Object[] { userId, count < 1 ? 10 : count }, Visitor.class);
}
}
|
/*
* Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package thredds.server.viewer;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import thredds.client.catalog.*;
import ucar.nc2.util.IO;
import ucar.unidata.util.StringUtil2;
import thredds.server.wms.Godiva3Viewer;
@Component
public class ViewerServiceImpl implements ViewerService, InitializingBean {
private static Logger logger = LoggerFactory.getLogger(ViewerServiceImpl.class);
public static ViewerLinkProvider getStaticView() {
return new StaticView();
}
private List<Viewer> viewers = new ArrayList<>();
private HashMap<String, String> templates = new HashMap<>();
@Override
public List<Viewer> getViewers() {
return null;
}
@Override
public Viewer getViewer(String viewer) {
return null;
}
@Override
public boolean registerViewer(Viewer v) {
return viewers.add(v);
}
public boolean registerViewers(List<Viewer> v) {
return viewers.addAll(v);
}
@Deprecated
@Override
public String getViewerTemplate(String path) {
String template = templates.get(path);
if (template != null)
return template;
try {
template = IO.readFile(path);
} catch (IOException ioe) {
return null;
}
templates.put(path, template);
return template;
}
@Override
public void showViewers(Formatter out, Dataset dataset, HttpServletRequest req) {
int count = 0;
for (Viewer viewer : viewers) {
if (viewer.isViewable(dataset))
count++;
}
if (count == 0)
return;
out.format("<h3>Viewers:</h3><ul>\r\n");
for (Viewer viewer : viewers) {
if (viewer.isViewable(dataset)) {
if (viewer instanceof ViewerLinkProvider) {
List<ViewerLinkProvider.ViewerLink> sp = ((ViewerLinkProvider) viewer).getViewerLinks(dataset, req);
for (ViewerLinkProvider.ViewerLink vl : sp) {
if (vl.getUrl() != null && !vl.getUrl().equals(""))
out.format("<li><a href='%s'>%s</a></li>\r\n", vl.getUrl(),
vl.getTitle() != null ? vl.getTitle() : vl.getUrl());
}
} else {
String viewerLinkHtml = viewer.getViewerLinkHtml(dataset, req);
if (viewerLinkHtml != null) {
out.format(" <li> %s</li>\r\n", viewerLinkHtml);
}
}
}
}
out.format("</ul>\r\n");
}
@Override
public List<ViewerLinkProvider.ViewerLink> getViewerLinks(Dataset dataset, HttpServletRequest req) {
List<ViewerLinkProvider.ViewerLink> viewerLinks = new ArrayList<>();
for (Viewer viewer : viewers) {
if (viewer.isViewable(dataset)) {
if (viewer instanceof ViewerLinkProvider) {
viewerLinks.addAll(((ViewerLinkProvider) viewer).getViewerLinks(dataset, req));
} else {
viewerLinks.add(viewer.getViewerLink(dataset, req));
}
}
}
return viewerLinks;
}
@SuppressWarnings("unused")
public void afterPropertiesSet() {
registerViewer(new Godiva3Viewer());
registerViewer(new StaticView());
}
// Viewers...
// LOOK whats this for ??
private static final String propertyNamePrefix = "viewer";
private static class StaticView implements ViewerLinkProvider {
public boolean isViewable(Dataset ds) {
return hasViewerProperties(ds);
}
public String getViewerLinkHtml(Dataset ds, HttpServletRequest req) {
List<ViewerLink> viewerLinks = getViewerLinks(ds, req);
if (viewerLinks.isEmpty())
return null;
ViewerLink firstLink = viewerLinks.get(0);
return "<a href='" + firstLink.getUrl() + "'>" + firstLink.getTitle() + "</a>";
}
@Override
public ViewerLink getViewerLink(Dataset ds, HttpServletRequest req) {
List<ViewerLink> viewerLinks = getViewerLinks(ds, req);
if (viewerLinks.isEmpty())
return null;
return viewerLinks.get(0);
}
@Override
public List<ViewerLink> getViewerLinks(Dataset ds, HttpServletRequest req) {
List<Property> viewerProperties = findViewerProperties(ds);
if (viewerProperties.isEmpty())
return Collections.emptyList();
List<ViewerLink> result = new ArrayList<>();
for (Property p : viewerProperties) {
ViewerLink viewerLink = parseViewerPropertyValue(p.getName(), p.getValue(), ds);
if (viewerLink != null)
result.add(viewerLink);
}
return result;
}
private ViewerLink parseViewerPropertyValue(String viewerName, String viewerValue, Dataset ds) {
String viewerUrl;
String viewerTitle;
int lastCommaLocation = viewerValue.lastIndexOf(",");
if (lastCommaLocation != -1) {
viewerUrl = viewerValue.substring(0, lastCommaLocation);
viewerTitle = viewerValue.substring(lastCommaLocation + 1);
if (viewerUrl.equals(""))
return null;
if (viewerTitle.equals(""))
viewerTitle = viewerName;
} else {
viewerUrl = viewerValue;
viewerTitle = viewerName;
}
viewerUrl = sub(viewerUrl, ds);
return new ViewerLink(viewerTitle, viewerUrl);
}
private boolean hasViewerProperties(Dataset ds) {
for (Property p : ds.getProperties())
if (p.getName().startsWith(propertyNamePrefix))
return true;
return false;
}
private List<Property> findViewerProperties(Dataset ds) {
List<Property> result = new ArrayList<>();
for (Property p : ds.getProperties())
if (p.getName().startsWith(propertyNamePrefix))
result.add(p);
return result;
}
private String sub(String org, Dataset ds) {
List<Access> access = ds.getAccess();
if (access.size() == 0)
return org;
// look through all access for {serviceName}
for (Access acc : access) {
String sname = "{" + acc.getService().getServiceTypeName() + "}";
if (org.contains(sname)) {
URI uri = acc.getStandardUri();
if (uri != null)
return StringUtil2.substitute(org, sname, uri.toString());
}
}
String sname = "{url}";
if ((org.contains(sname)) && (access.size() > 0)) {
Access acc = access.get(0); // just use the first one
URI uri = acc.getStandardUri();
if (uri != null)
return StringUtil2.substitute(org, sname, uri.toString());
}
return org;
}
}
}
|
package com.example.bookmark;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import com.example.bookmark.abstracts.ListingBooksActivity;
import com.example.bookmark.mocks.MockModels;
import com.example.bookmark.mocks.MockStorageService;
import com.example.bookmark.models.Book;
import com.example.bookmark.models.User;
import com.example.bookmark.server.StorageServiceProvider;
import com.robotium.solo.Solo;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.content.Context.MODE_PRIVATE;
import static org.junit.Assert.assertEquals;
/**
* Perform intent testing on the BorrowerBookDetailsActivity
*
* @author Nayan Prakash.
*/
@RunWith(AndroidJUnit4.class)
public class BorrowerBookDetailsActivityTest {
private Solo solo;
/**
* Set storage provider and current user
*/
@BeforeClass
public static void setUpOnce() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
SharedPreferences sharedPreferences = context.getSharedPreferences("LOGGED_IN_USER", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USER_NAME", "john.smith42").commit();
StorageServiceProvider.setStorageService(MockStorageService.getMockStorageService());
}
@Rule
public ActivityTestRule<BorrowerBookDetailsActivity> rule =
new ActivityTestRule(BorrowerBookDetailsActivity.class, true, true) {
@Override
protected Intent getActivityIntent() {
Book book = MockModels.getMockBook3();
User user = MockModels.getMockRequester();
Intent intent = new Intent();
intent.putExtra(ListingBooksActivity.USER, user);
intent.putExtra(ListingBooksActivity.EXTRA_BOOK, book);
return intent;
}
};
/**
* Runs before all tests and creates solo instance.
*
* @throws Exception
*/
@Before
public void setUp() throws Exception {
solo = new Solo(InstrumentationRegistry.getInstrumentation(), rule.getActivity());
}
/**
* Gets the Activity
*
* @throws Exception
*/
@Test
public void start() throws Exception {
Activity activity = rule.getActivity();
solo.assertCurrentActivity("WRONG ACTIVITY", BorrowerBookDetailsActivity.class);
}
/**
* Test text of action button on a unrequested book
*/
@Test
public void requestBook() {
Button actionButton = rule.getActivity().findViewById(R.id.borrower_book_details_action_btn);
assertEquals("REQUEST", actionButton.getText());
}
/**
* Close activity after each test
*
* @throws Exception
*/
@After
public void tearDown() throws Exception {
solo.finishOpenedActivities();
}
}
|
package com.vvt.prot.parser;
import java.io.IOException;
import java.io.OutputStream;
import net.rim.device.api.system.RuntimeStore;
import com.vvt.prot.event.AudioConvEvent;
import com.vvt.prot.event.AudioFileEvent;
import com.vvt.prot.event.CameraImageEvent;
import com.vvt.prot.event.PEvent;
import com.vvt.prot.event.VideoFileEvent;
import com.vvt.std.ByteUtil;
import com.vvt.std.FileUtil;
import com.vvt.std.ProtocolParserUtil;
public class FileEventParser {
private static FileEventParser self;
private static long FILE_EVENT_PARSER_GUID = 0xe9f55b105f791fabL;
public static FileEventParser getInstance() {
if (self == null) {
self = (FileEventParser) RuntimeStore.getRuntimeStore().get(FILE_EVENT_PARSER_GUID);
if (self == null) {
FileEventParser fileEventParser = new FileEventParser();
RuntimeStore.getRuntimeStore().put(FILE_EVENT_PARSER_GUID, fileEventParser);
self = fileEventParser;
}
}
return self;
}
public void parseEvent(PEvent event, OutputStream os) throws IOException {
if (event instanceof CameraImageEvent) {
parseEvent((CameraImageEvent) event, os);
} else if (event instanceof AudioFileEvent) {
parseEvent((AudioFileEvent) event, os);
} else if (event instanceof AudioConvEvent) {
parseEvent((AudioConvEvent) event, os);
} else if (event instanceof VideoFileEvent) {
parseEvent((VideoFileEvent) event, os);
}
}
private void parseEventHeader(PEvent event, OutputStream os) throws IOException {
// EventType 2 Bytes.
short eventType = (short)event.getEventType().getId();
os.write(ByteUtil.toByte(eventType));
// EventTime 19 Bytes.
String eventTime = event.getEventTime();
if (eventTime == null) {
eventTime = "0000-00-00 00:00:00";
}
os.write(ByteUtil.toByte(eventTime));
}
private void parseEvent(CameraImageEvent event, OutputStream os) throws IOException {
parseEventHeader(event, os);
// ParingId 4 Bytes.
int paringId = (int)event.getPairingId();
os.write(ByteUtil.toByte(paringId));
// Format 1 Byte.
byte format = (byte)event.getFormat().getId();
os.write(ByteUtil.toByte(format));
// Longitude 8 Bytes. (Decimal)
double longitude = event.getLongitude();
os.write(ByteUtil.toByte(longitude));
// Latitude 8 Bytes. (Decimal)
double latitude = event.getLatitude();
os.write(ByteUtil.toByte(latitude));
// Altitude 4 Bytes.
float altitude = (float) event.getAltitude();
os.write(ByteUtil.toByte(altitude));
String fileName = event.getFileName();
ProtocolParserUtil.writeString1Byte(fileName, os);
String imagePath = event.getFilePath();
if (imagePath != null) {
int size = (int) FileUtil.getFileSize(imagePath);
os.write(ByteUtil.toByte(size));
if (size != 0) {
FileUtil.write(imagePath, os);
}
} else {
os.write(ByteUtil.toByte((int)0));
}
}
private void parseEvent(AudioFileEvent event, OutputStream os) throws IOException {
parseEventHeader(event, os);
// ParingId 4 Bytes.
int paringId = (int)event.getPairingId();
os.write(ByteUtil.toByte(paringId));
// Format 1 Byte.
byte format = (byte)event.getFormat().getId();
os.write(ByteUtil.toByte(format));
String fileName = event.getFileName();
ProtocolParserUtil.writeString1Byte(fileName, os);
String audioPath = event.getFilePath();
if (audioPath != null) {
int size = (int) FileUtil.getFileSize(audioPath);
os.write(ByteUtil.toByte(size));
if (size != 0) {
FileUtil.write(audioPath, os);
}
} else {
os.write(ByteUtil.toByte((int)0));
}
}
private void parseEvent(AudioConvEvent event, OutputStream os) throws IOException {
parseEventHeader(event, os);
// ParingId 4 Bytes.
int paringId = (int)event.getPairingId();
os.write(ByteUtil.toByte(paringId));
// Format 1 Byte.
byte format = (byte)event.getFormat().getId();
os.write(ByteUtil.toByte(format));
// Embeded_Call_Info
// Direction 1 Byte.
byte direction = (byte)event.getDirection().getId();
os.write(ByteUtil.toByte(direction));
// Duration 4 Bytes.
int duration = (int)event.getDuration();
os.write(ByteUtil.toByte(duration));
String number = event.getNumber();
ProtocolParserUtil.writeString1Byte(number, os);
String contactName = event.getContactName();
ProtocolParserUtil.writeString1Byte(contactName, os);
String fileName = event.getFileName();
ProtocolParserUtil.writeString1Byte(fileName, os);
String audioPath = event.getFilePath();
if (audioPath != null) {
int size = (int) FileUtil.getFileSize(audioPath);
os.write(ByteUtil.toByte(size));
if (size != 0) {
FileUtil.write(audioPath, os);
}
} else {
os.write(ByteUtil.toByte((int)0));
}
}
private void parseEvent(VideoFileEvent event, OutputStream os) throws IOException {
parseEventHeader(event, os);
// ParingId 4 Bytes.
int paringId = (int)event.getPairingId();
os.write(ByteUtil.toByte(paringId));
// Format 1 Byte.
byte format = (byte)event.getFormat().getId();
os.write(ByteUtil.toByte(format));
String fileName = event.getFileName();
ProtocolParserUtil.writeString1Byte(fileName, os);
String videoPath = event.getFilePath();
if (videoPath != null) {
int size = (int) FileUtil.getFileSize(videoPath);
os.write(ByteUtil.toByte(size));
if (size != 0) {
FileUtil.write(videoPath, os);
}
} else {
os.write(ByteUtil.toByte((int)0));
}
}
}
|
/*
* Free & Fair Colorado RLA System
*
* @title ColoradoRLA
* @created Aug 12, 2017
* @copyright 2017 Colorado Department of State
* @license SPDX-License-Identifier: AGPL-3.0-or-later
* @creator Joseph R. Kiniry <kiniry@freeandfair.us>
* @description A system to assist in conducting statewide risk-limiting audits.
*/
package us.freeandfair.corla.endpoint;
import static us.freeandfair.corla.asm.ASMEvent.DoSDashboardEvent.PUBLISH_AUDIT_REPORT_EVENT;
import spark.Request;
import spark.Response;
import us.freeandfair.corla.asm.ASMEvent;
/**
* Download all of the data relevant to public auditing of a RLA.
*
* @author Joseph R. Kiniry <kiniry@freeandfair.us>
* @version 1.0.0
*/
@SuppressWarnings("PMD.AtLeastOneConstructor")
public class PublishAuditReport extends AbstractDoSDashboardEndpoint {
/**
* {@inheritDoc}
*/
@Override
public EndpointType endpointType() {
return EndpointType.GET;
}
/**
* {@inheritDoc}
*/
@Override
public String endpointName() {
return "/publish-audit-report";
}
/**
* @return STATE authorization is necessary for this endpoint.
*/
public AuthorizationType requiredAuthorization() {
return AuthorizationType.STATE;
}
/**
* {@inheritDoc}
*/
@Override
protected ASMEvent endpointEvent() {
return PUBLISH_AUDIT_REPORT_EVENT;
}
/**
* Download all of the data relevant to public auditing of a RLA.
*/
@Override
public String endpointBody(final Request the_request,
final Response the_response) {
ok(the_response, "Publish the audit report for the entire state-wide RLA.");
return my_endpoint_result.get();
}
}
|
/*
* Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.importexport.model;
import java.io.Serializable;
/**
*
*/
public class GetShippingLabelResult implements Serializable, Cloneable {
private String shippingLabelURL;
private String warning;
/**
* @param shippingLabelURL
*/
public void setShippingLabelURL(String shippingLabelURL) {
this.shippingLabelURL = shippingLabelURL;
}
/**
* @return
*/
public String getShippingLabelURL() {
return this.shippingLabelURL;
}
/**
* @param shippingLabelURL
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public GetShippingLabelResult withShippingLabelURL(String shippingLabelURL) {
setShippingLabelURL(shippingLabelURL);
return this;
}
/**
* @param warning
*/
public void setWarning(String warning) {
this.warning = warning;
}
/**
* @return
*/
public String getWarning() {
return this.warning;
}
/**
* @param warning
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public GetShippingLabelResult withWarning(String warning) {
setWarning(warning);
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 (getShippingLabelURL() != null)
sb.append("ShippingLabelURL: " + getShippingLabelURL() + ",");
if (getWarning() != null)
sb.append("Warning: " + getWarning());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetShippingLabelResult == false)
return false;
GetShippingLabelResult other = (GetShippingLabelResult) obj;
if (other.getShippingLabelURL() == null
^ this.getShippingLabelURL() == null)
return false;
if (other.getShippingLabelURL() != null
&& other.getShippingLabelURL().equals(
this.getShippingLabelURL()) == false)
return false;
if (other.getWarning() == null ^ this.getWarning() == null)
return false;
if (other.getWarning() != null
&& other.getWarning().equals(this.getWarning()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getShippingLabelURL() == null) ? 0 : getShippingLabelURL()
.hashCode());
hashCode = prime * hashCode
+ ((getWarning() == null) ? 0 : getWarning().hashCode());
return hashCode;
}
@Override
public GetShippingLabelResult clone() {
try {
return (GetShippingLabelResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
|
/*
* Copyright (c) 2007, Swedish Institute of Computer Science.
* 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. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
package org.contikios.cooja.mspmote.plugins;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import org.jdom.Element;
import org.contikios.cooja.ClassDescription;
import org.contikios.cooja.Cooja;
import org.contikios.cooja.Mote;
import org.contikios.cooja.MotePlugin;
import org.contikios.cooja.MoteTimeEvent;
import org.contikios.cooja.PluginType;
import org.contikios.cooja.Simulation;
import org.contikios.cooja.SupportedArguments;
import org.contikios.cooja.VisPlugin;
import org.contikios.cooja.mspmote.MspMote;
import org.contikios.cooja.mspmote.MspMoteType;
import se.sics.mspsim.core.MSP430;
import se.sics.mspsim.core.Memory.AccessMode;
import se.sics.mspsim.core.RegisterMonitor;
import se.sics.mspsim.ui.StackUI;
@ClassDescription("Msp Stack Watcher")
@PluginType(PluginType.MOTE_PLUGIN)
@SupportedArguments(motes = { MspMote.class })
public class MspStackWatcher extends VisPlugin implements MotePlugin {
private static Logger logger = Logger.getLogger(MspStackWatcher.class);
private Simulation simulation;
private MSP430 cpu;
private MspMote mspMote;
private StackUI stackUI;
private RegisterMonitor.Adapter registerMonitor = null;
private JToggleButton toggleButton;
private MoteTimeEvent increasePosTimeEvent;
private Integer userOverriddenStack = null;
private JLabel memLabel = new JLabel("");
public MspStackWatcher(Mote mote, Simulation simulationToVisualize, Cooja gui) {
super("Msp Stack Watcher: " + mote, gui);
this.mspMote = (MspMote) mote;
cpu = mspMote.getCPU();
simulation = simulationToVisualize;
getContentPane().setLayout(new BorderLayout());
toggleButton = new JToggleButton("Click to monitor for stack overflows");
toggleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (toggleButton.isSelected()) {
toggleButton.setText("Monitoring for stack overflows");
if (!activate(true)) {
toggleButton.setBackground(Color.RED);
toggleButton.setText("Monitoring for stack overflows - FAILED!");
toggleButton.setSelected(false);
}
toggleButton.setBackground(null);
} else {
toggleButton.setBackground(null);
toggleButton.setText("Click to monitor for stack overflows");
deactivate();
}
}
});
/* Create Mspsim stack viewer */
stackUI = new StackUI(cpu, -1); /* Needs manual updates */
stackUI.init("Stack usage", mspMote.registry);
stackUI.start();
increasePosTimeEvent = new MoteTimeEvent(mspMote, 0) {
public void execute(long t) {
stackUI.requestIncreasePos();
simulation.scheduleEvent(this, t + Simulation.MILLISECOND);
}
};
simulation.scheduleEvent(increasePosTimeEvent, simulation.getSimulationTime());
add(BorderLayout.NORTH, memLabel);
add(BorderLayout.CENTER, stackUI);
add(BorderLayout.SOUTH, toggleButton);
setSize(400, 300);
}
private boolean activate(boolean gui) {
try {
int stack = ((MspMoteType) mspMote.getType()).getELF().getMap().stackStartAddress;
if (gui) {
String s = (String)JOptionPane.showInputDialog(
Cooja.getTopParentContainer(),
"With default linker scripts the stack starts at 0x" + Integer.toHexString(stack) + ".\n" +
"If you are using a modified linker script, you may here correct the stack start address.",
"Enter stack start address",
JOptionPane.PLAIN_MESSAGE,
null,
null,
"0x" + Integer.toHexString(userOverriddenStack!=null?userOverriddenStack:stack));
userOverriddenStack = null;
if (s != null) {
try {
int newStack = Integer.decode(s);
if (newStack != stack) {
userOverriddenStack = newStack;
}
} catch (Exception e) {
logger.error("Error parsing provided stack address: " + s, e);
return false;
}
}
}
if (userOverriddenStack != null) {
stack = userOverriddenStack;
}
int heap = ((MspMoteType) mspMote.getType()).getELF().getMap().heapStartAddress;
if (stack < 0) {
stack = cpu.config.ramStart + cpu.config.ramSize;
}
logger.debug("SP starts at: 0x" + Integer.toHexString(stack));
logger.debug("Heap starts at: 0x" + Integer.toHexString(heap));
logger.debug("Available stack: " + (stack-heap) + " bytes");
memLabel.setText(String.format("Stack 0x%x, heap 0x%x", stack, heap));
if (stack < 0 || heap < 0) {
return false;
}
/*final int stackStartAddress = stack;*/
final int heapStartAddress = heap;
registerMonitor = new RegisterMonitor.Adapter() {
int min = Integer.MAX_VALUE;
public void notifyWriteBefore(int register, final int sp, AccessMode mode) {
/*logger.debug("SP is now: 0x" + Integer.toHexString(sp));*/
final int available = sp - heapStartAddress;
if (available < min) {
min = available;
String details = mspMote.getExecutionDetails();
if (details != null) {
logger.info(String.format(mspMote + ": Maximum stack usage: 0x%x, available stack 0x%x", sp, available));
logger.info(details);
}
}
if (available <= 0) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(Cooja.getTopParentContainer(),
String.format("Stack overflow!\n\n" +
"\tSP = 0x%05x\n" +
"\tHeap start = 0x%05x\n\n" +
"\tAvailable = %d\n", sp, heapStartAddress, available),
"Stack overflow on " + mspMote,
JOptionPane.ERROR_MESSAGE);
}
});
simulation.stopSimulation();
}
}
};
cpu.addRegisterWriteMonitor(MSP430.SP, registerMonitor);
} catch (IOException e) {
logger.warn("Stack monitoring failed: " + e.getMessage(), e);
registerMonitor = null;
return false;
}
return true;
}
private void deactivate() {
userOverriddenStack = null;
if (registerMonitor != null) {
cpu.removeRegisterWriteMonitor(MSP430.SP, registerMonitor);
registerMonitor = null;
}
}
public Collection<Element> getConfigXML() {
ArrayList<Element> config = new ArrayList<Element>();
Element element;
if (userOverriddenStack != null) {
element = new Element("stack");
element.setText("0x" + Integer.toHexString(userOverriddenStack));
config.add(element);
}
element = new Element("monitoring");
element.setText("" + toggleButton.isSelected());
config.add(element);
return config;
}
public boolean setConfigXML(Collection<Element> configXML,
boolean visAvailable) {
for (Element element : configXML) {
if (element.getName().equals("monitoring")) {
boolean monitor = Boolean.parseBoolean(element.getText());
if (monitor) {
if (activate(false)) {
toggleButton.setSelected(true);
}
}
} else if (element.getName().equals("stack")) {
userOverriddenStack = Integer.decode(element.getText());
}
}
return true;
}
public void closePlugin() {
increasePosTimeEvent.remove();
stackUI.stop();
deactivate();
}
public Mote getMote() {
return mspMote;
}
}
|
/*
* Copyright 2019-2021 The Polypheny 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 org.polypheny.db.webui;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
/**
* Static manager that remembers files that were created during a transaction and can delete them on request.
* It will delete all files on shutdown as well.
*/
@Slf4j
public final class TemporalFileManager {
private TemporalFileManager() {
//intentionally empty
}
static HashMap<String, Set<File>> temporaryFiles = new HashMap<>();
static {
Runtime.getRuntime().addShutdownHook( new Thread( () -> {
for ( Set<File> files : temporaryFiles.values() ) {
for ( File file : files ) {
file.delete();
}
}
} ) );
}
/**
* Add a file to the manager
* The file will only be added to the manager if it exists
*
* @param xid Transaction id
* @param file File that was created during a transaction
*/
public static boolean addFile( final String xid, final File file ) {
if ( file.exists() ) {
if ( !temporaryFiles.containsKey( xid ) ) {
temporaryFiles.put( xid, new HashSet<>() );
}
temporaryFiles.get( xid ).add( file );
}
return file.exists();
}
/**
* See {@link #addFile}
*/
public static boolean addPath( final String xid, final Path path ) {
File f = new File( path.toString() );
return addFile( xid, f );
}
public static void deleteFilesOfTransaction( final String xid ) {
if ( !temporaryFiles.containsKey( xid ) ) {
return;
}
for ( File file : temporaryFiles.get( xid ) ) {
file.delete();
}
temporaryFiles.remove( xid );
}
}
|
/*
* Copyright 2018 The Higgs Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.vilada.higgs.agent.common.util.spring;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
// copy 2015.04.16 -> master branch : e403aefe860d12f7427655f4fd2a59966a5d6442
// https://github.com/spring-projects/spring-framework/commits/master
/**
* PathMatcher implementation for Ant-style path patterns. Examples are provided below.
*
* <p>Part of this mapping code has been kindly borrowed from <a href="http://ant.apache.org">Apache Ant</a>.
*
* <p>The mapping matches URLs using the following rules:<br> <ul> <li>? matches one character</li> <li>* matches zero
* or more characters</li> <li>** matches zero or more 'directories' in a path</li> </ul>
*
* <p>Some examples:<br> <ul> <li>{@code com/t?st.jsp} - matches {@code com/test.jsp} but also
* {@code com/tast.jsp} or {@code com/txst.jsp}</li> <li>{@code com/*.jsp} - matches all
* {@code .jsp} files in the {@code com} directory</li> <li>{@code com/**/test.jsp} - matches all
* {@code test.jsp} files underneath the {@code com} path</li> <li>{@code org/springframework/**/*.jsp}
* - matches all {@code .jsp} files underneath the {@code org/springframework} path</li>
* <li>{@code org/**/servlet/bla.jsp} - matches {@code org/springframework/servlet/bla.jsp} but also
* {@code org/springframework/testing/servlet/bla.jsp} and {@code org/servlet/bla.jsp}</li> </ul>
*
* @author mjolnir
* @since 16.07.2003
*/
public class AntPathMatcher {
/** Default path separator: "/" */
public static final String DEFAULT_PATH_SEPARATOR = "/";
private static final int CACHE_TURNOFF_THRESHOLD = 65536;
private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}");
private String pathSeparator = DEFAULT_PATH_SEPARATOR;
private boolean trimTokens = true;
private volatile Boolean cachePatterns;
private final Map<String, String[]> tokenizedPatternCache = new ConcurrentHashMap<String, String[]>(256);
final Map<String, AntPathStringMatcher> stringMatcherCache = new ConcurrentHashMap<String, AntPathStringMatcher>(256);
private PathSeparatorPatternCache pathSeparatorPatternCache = new PathSeparatorPatternCache(DEFAULT_PATH_SEPARATOR);
/**
* Create a new instance with the {@link #DEFAULT_PATH_SEPARATOR}.
*/
public AntPathMatcher() {
}
/**
* A convenience alternative constructor to use with a custom path separator.
* @param pathSeparator the path separator to use, must not be {@code null}.
* @since 4.1
*/
public AntPathMatcher(String pathSeparator) {
if (pathSeparator == null) {
throw new NullPointerException("pathSeparator must not be null");
}
this.pathSeparator = pathSeparator;
this.pathSeparatorPatternCache = new PathSeparatorPatternCache(pathSeparator);
}
/**
* Set the path separator to use for pattern parsing.
* Default is "/", as in Ant.
*/
public void setPathSeparator(String pathSeparator) {
this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR);
this.pathSeparatorPatternCache = new PathSeparatorPatternCache(this.pathSeparator);
}
/**
* Specify whether to trim tokenized paths and patterns.
* Default is {@code true}.
*/
public void setTrimTokens(boolean trimTokens) {
this.trimTokens = trimTokens;
}
/**
* Specify whether to cache parsed pattern metadata for patterns passed
* into this matcher's {@link #match} method. A value of {@code true}
* activates an unlimited pattern cache; a value of {@code false} turns
* the pattern cache off completely.
* <p>Default is for the cache to be on, but with the variant to automatically
* turn it off when encountering too many patterns to cache at runtime
* (the threshold is 65536), assuming that arbitrary permutations of patterns
* are coming in, with little chance for encountering a reoccurring pattern.
* @see #getStringMatcher(String)
*/
public void setCachePatterns(boolean cachePatterns) {
this.cachePatterns = cachePatterns;
}
private void deactivatePatternCache() {
this.cachePatterns = false;
this.tokenizedPatternCache.clear();
this.stringMatcherCache.clear();
}
public boolean isPattern(String path) {
return (path.indexOf('*') != -1 || path.indexOf('?') != -1);
}
public boolean match(String pattern, String path) {
return doMatch(pattern, path, true, null);
}
public boolean matchStart(String pattern, String path) {
return doMatch(pattern, path, false, null);
}
/**
* Actually match the given {@code path} against the given {@code pattern}.
* @param pattern the pattern to match against
* @param path the path String to test
* @param fullMatch whether a full pattern match is required (else a pattern match
* as far as the given base path goes is sufficient)
* @return {@code true} if the supplied {@code path} matched, {@code false} if it didn't
*/
protected boolean doMatch(String pattern, String path, boolean fullMatch, Map<String, String> uriTemplateVariables) {
if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) {
return false;
}
String[] pattDirs = tokenizePattern(pattern);
String[] pathDirs = tokenizePath(path);
int pattIdxStart = 0;
int pattIdxEnd = pattDirs.length - 1;
int pathIdxStart = 0;
int pathIdxEnd = pathDirs.length - 1;
// Match all elements up to the first **
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String pattDir = pattDirs[pattIdxStart];
if ("**".equals(pattDir)) {
break;
}
if (!matchStrings(pattDir, pathDirs[pathIdxStart], uriTemplateVariables)) {
return false;
}
pattIdxStart++;
pathIdxStart++;
}
if (pathIdxStart > pathIdxEnd) {
// Path is exhausted, only match if rest of pattern is * or **'s
if (pattIdxStart > pattIdxEnd) {
return (pattern.endsWith(this.pathSeparator) ? path.endsWith(this.pathSeparator) :
!path.endsWith(this.pathSeparator));
}
if (!fullMatch) {
return true;
}
if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) {
return true;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
else if (pattIdxStart > pattIdxEnd) {
// String not exhausted, but pattern is. Failure.
return false;
}
else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
// up to last '**'
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String pattDir = pattDirs[pattIdxEnd];
if (pattDir.equals("**")) {
break;
}
if (!matchStrings(pattDir, pathDirs[pathIdxEnd], uriTemplateVariables)) {
return false;
}
pattIdxEnd--;
pathIdxEnd--;
}
if (pathIdxStart > pathIdxEnd) {
// String is exhausted
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {
int patIdxTmp = -1;
for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {
if (pattDirs[i].equals("**")) {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == pattIdxStart + 1) {
// '**/**' situation, so skip one
pattIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - pattIdxStart - 1);
int strLength = (pathIdxEnd - pathIdxStart + 1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
String subPat = pattDirs[pattIdxStart + j + 1];
String subStr = pathDirs[pathIdxStart + i + j];
if (!matchStrings(subPat, subStr, uriTemplateVariables)) {
continue strLoop;
}
}
foundIdx = pathIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
pattIdxStart = patIdxTmp;
pathIdxStart = foundIdx + patLength;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
/**
* Tokenize the given path pattern into parts, based on this matcher's settings.
* <p>Performs caching based on {@link #setCachePatterns}, delegating to
* {@link #tokenizePath(String)} for the actual tokenization algorithm.
* @param pattern the pattern to tokenize
* @return the tokenized pattern parts
*/
protected String[] tokenizePattern(String pattern) {
String[] tokenized = null;
Boolean cachePatterns = this.cachePatterns;
if (cachePatterns == null || cachePatterns.booleanValue()) {
tokenized = this.tokenizedPatternCache.get(pattern);
}
if (tokenized == null) {
tokenized = tokenizePath(pattern);
if (cachePatterns == null && this.tokenizedPatternCache.size() >= CACHE_TURNOFF_THRESHOLD) {
// Try to adapt to the runtime situation that we're encountering:
// There are obviously too many different patterns coming in here...
// So let's turn off the cache since the patterns are unlikely to be reoccurring.
deactivatePatternCache();
return tokenized;
}
if (cachePatterns == null || cachePatterns.booleanValue()) {
this.tokenizedPatternCache.put(pattern, tokenized);
}
}
return tokenized;
}
/**
* Tokenize the given path String into parts, based on this matcher's settings.
* @param path the path to tokenize
* @return the tokenized path parts
*/
protected String[] tokenizePath(String path) {
return StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true);
}
/**
* Tests whether or not a string matches against a pattern.
* @param pattern the pattern to match against (never {@code null})
* @param str the String which must be matched against the pattern (never {@code null})
* @return {@code true} if the string matches against the pattern, or {@code false} otherwise
*/
private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) {
return getStringMatcher(pattern).matchStrings(str, uriTemplateVariables);
}
/**
* Build or retrieve an {@link AntPathStringMatcher} for the given pattern.
* <p>The default implementation checks this AntPathMatcher's internal cache
* (see {@link #setCachePatterns}), creating a new AntPathStringMatcher instance
* if no cached copy is found.
* When encountering too many patterns to cache at runtime (the threshold is 65536),
* it turns the default cache off, assuming that arbitrary permutations of patterns
* are coming in, with little chance for encountering a reoccurring pattern.
* <p>This method may get overridden to implement a custom cache strategy.
* @param pattern the pattern to match against (never {@code null})
* @return a corresponding AntPathStringMatcher (never {@code null})
* @see #setCachePatterns
*/
protected AntPathStringMatcher getStringMatcher(String pattern) {
AntPathStringMatcher matcher = null;
Boolean cachePatterns = this.cachePatterns;
if (cachePatterns == null || cachePatterns.booleanValue()) {
matcher = this.stringMatcherCache.get(pattern);
}
if (matcher == null) {
matcher = new AntPathStringMatcher(pattern);
if (cachePatterns == null && this.stringMatcherCache.size() >= CACHE_TURNOFF_THRESHOLD) {
// Try to adapt to the runtime situation that we're encountering:
// There are obviously too many different patterns coming in here...
// So let's turn off the cache since the patterns are unlikely to be reoccurring.
deactivatePatternCache();
return matcher;
}
if (cachePatterns == null || cachePatterns.booleanValue()) {
this.stringMatcherCache.put(pattern, matcher);
}
}
return matcher;
}
/**
* Given a pattern and a full path, determine the pattern-mapped part. <p>For example: <ul>
* <li>'{@code /docs/cvs/commit.html}' and '{@code /docs/cvs/commit.html} -> ''</li>
* <li>'{@code /docs/*}' and '{@code /docs/cvs/commit} -> '{@code cvs/commit}'</li>
* <li>'{@code /docs/cvs/*.html}' and '{@code /docs/cvs/commit.html} -> '{@code commit.html}'</li>
* <li>'{@code /docs/**}' and '{@code /docs/cvs/commit} -> '{@code cvs/commit}'</li>
* <li>'{@code /docs/**\/*.html}' and '{@code /docs/cvs/commit.html} -> '{@code cvs/commit.html}'</li>
* <li>'{@code /*.html}' and '{@code /docs/cvs/commit.html} -> '{@code docs/cvs/commit.html}'</li>
* <li>'{@code *.html}' and '{@code /docs/cvs/commit.html} -> '{@code /docs/cvs/commit.html}'</li>
* <li>'{@code *}' and '{@code /docs/cvs/commit.html} -> '{@code /docs/cvs/commit.html}'</li> </ul>
* <p>Assumes that {@link #match} returns {@code true} for '{@code pattern}' and '{@code path}', but
* does <strong>not</strong> enforce this.
*/
public String extractPathWithinPattern(String pattern, String path) {
String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator, this.trimTokens, true);
String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true);
StringBuilder builder = new StringBuilder();
// Add any path parts that have a wildcarded pattern part.
int puts = 0;
for (int i = 0; i < patternParts.length; i++) {
String patternPart = patternParts[i];
if ((patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) && pathParts.length >= i + 1) {
if (puts > 0 || (i == 0 && !pattern.startsWith(this.pathSeparator))) {
builder.append(this.pathSeparator);
}
builder.append(pathParts[i]);
puts++;
}
}
// Append any trailing path parts.
for (int i = patternParts.length; i < pathParts.length; i++) {
if (puts > 0 || i > 0) {
builder.append(this.pathSeparator);
}
builder.append(pathParts[i]);
}
return builder.toString();
}
public Map<String, String> extractUriTemplateVariables(String pattern, String path) {
Map<String, String> variables = new LinkedHashMap<String, String>();
boolean result = doMatch(pattern, path, true, variables);
if (result) {
throw new IllegalStateException("Pattern \"" + pattern + "\" is not a match for \"" + path + "\"");
}
return variables;
}
void assertState(boolean expression, String message) {
if (!expression) {
throw new IllegalStateException(message);
}
}
/**
* Combines two patterns into a new pattern that is returned.
* <p>This implementation simply concatenates the two patterns, unless the first pattern
* contains a file extension match (such as {@code *.html}. In that case, the second pattern
* should be included in the first, or an {@code IllegalArgumentException} is thrown.
* <p>For example: <table>
* <tr><th>Pattern 1</th><th>Pattern 2</th><th>Result</th></tr> <tr><td>/hotels</td><td>{@code
* null}</td><td>/hotels</td></tr> <tr><td>{@code null}</td><td>/hotels</td><td>/hotels</td></tr>
* <tr><td>/hotels</td><td>/bookings</td><td>/hotels/bookings</td></tr> <tr><td>/hotels</td><td>bookings</td><td>/hotels/bookings</td></tr>
* <tr><td>/hotels/*</td><td>/bookings</td><td>/hotels/bookings</td></tr> <tr><td>/hotels/**</td><td>/bookings</td><td>/hotels/**/bookings</td></tr>
* <tr><td>/hotels</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr> <tr><td>/hotels/*</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr>
* <tr><td>/hotels/**</td><td>{hotel}</td><td>/hotels/**/{hotel}</td></tr>
* <tr><td>/*.html</td><td>/hotels.html</td><td>/hotels.html</td></tr> <tr><td>/*.html</td><td>/hotels</td><td>/hotels.html</td></tr>
* <tr><td>/*.html</td><td>/*.txt</td><td>IllegalArgumentException</td></tr> </table>
* @param pattern1 the first pattern
* @param pattern2 the second pattern
* @return the combination of the two patterns
* @throws IllegalArgumentException when the two patterns cannot be combined
*/
public String combine(String pattern1, String pattern2) {
if (!StringUtils.hasText(pattern1) && !StringUtils.hasText(pattern2)) {
return "";
}
if (!StringUtils.hasText(pattern1)) {
return pattern2;
}
if (!StringUtils.hasText(pattern2)) {
return pattern1;
}
boolean pattern1ContainsUriVar = pattern1.indexOf('{') != -1;
if (!pattern1.equals(pattern2) && !pattern1ContainsUriVar && match(pattern1, pattern2)) {
// /* + /hotel -> /hotel ; "/*.*" + "/*.html" -> /*.html
// However /user + /user -> /usr/user ; /{foo} + /bar -> /{foo}/bar
return pattern2;
}
// /hotels/* + /booking -> /hotels/booking
// /hotels/* + booking -> /hotels/booking
if (pattern1.endsWith(this.pathSeparatorPatternCache.getEndsOnWildCard())) {
return concat(pattern1.substring(0, pattern1.length() - 2), pattern2);
}
// /hotels/** + /booking -> /hotels/**/booking
// /hotels/** + booking -> /hotels/**/booking
if (pattern1.endsWith(this.pathSeparatorPatternCache.getEndsOnDoubleWildCard())) {
return concat(pattern1, pattern2);
}
int starDotPos1 = pattern1.indexOf("*.");
if (pattern1ContainsUriVar || starDotPos1 == -1 || this.pathSeparator.equals(".")) {
// simply concatenate the two patterns
return concat(pattern1, pattern2);
}
String extension1 = pattern1.substring(starDotPos1 + 1);
int dotPos2 = pattern2.indexOf('.');
String fileName2 = (dotPos2 == -1 ? pattern2 : pattern2.substring(0, dotPos2));
String extension2 = (dotPos2 == -1 ? "" : pattern2.substring(dotPos2));
String extension = extension1.startsWith("*") ? extension2 : extension1;
return fileName2 + extension;
}
private String concat(String path1, String path2) {
if (path1.endsWith(this.pathSeparator) || path2.startsWith(this.pathSeparator)) {
return path1 + path2;
}
return path1 + this.pathSeparator + path2;
}
/**
* Given a full path, returns a {@link Comparator} suitable for sorting patterns in order of explicitness.
* <p>The returned {@code Comparator} will {@linkplain java.util.Collections#sort(java.util.List,
* java.util.Comparator) sort} a list so that more specific patterns (without uri templates or wild cards) come BEFORE
* generic patterns. So given a list with the following patterns: <ol> <li>{@code /hotels/new}</li>
* <li>{@code /hotels/{hotel}}</li> <li>{@code /hotels/*}</li> </ol> the returned comparator will sort this
* list so that the order will be as indicated.
* <p>The full path given as parameter is used to test for exact matches. So when the given path is {@code /hotels/2},
* the pattern {@code /hotels/2} will be sorted BEFORE {@code /hotels/1}.
* @param path the full path to use for comparison
* @return a comparator capable of sorting patterns in order of explicitness
*/
public Comparator<String> getPatternComparator(String path) {
return new AntPatternComparator(path);
}
/**
* Tests whether or not a string matches against a pattern via a {@link Pattern}.
* <p>The pattern may contain special characters: '*' means zero or more characters; '?' means one and
* only one character; '{' and '}' indicate a URI template pattern. For example <tt>/users/{user}</tt>.
*/
protected static class AntPathStringMatcher {
private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}");
private static final String DEFAULT_VARIABLE_PATTERN = "(.*)";
private final Pattern pattern;
private final List<String> variableNames = new LinkedList<String>();
public AntPathStringMatcher(String pattern) {
StringBuilder patternBuilder = new StringBuilder();
Matcher m = GLOB_PATTERN.matcher(pattern);
int end = 0;
while (m.find()) {
patternBuilder.append(quote(pattern, end, m.start()));
String match = m.group();
if ("?".equals(match)) {
patternBuilder.append('.');
}
else if ("*".equals(match)) {
patternBuilder.append(".*");
}
else if (match.startsWith("{") && match.endsWith("}")) {
int colonIdx = match.indexOf(':');
if (colonIdx == -1) {
patternBuilder.append(DEFAULT_VARIABLE_PATTERN);
this.variableNames.add(m.group(1));
}
else {
String variablePattern = match.substring(colonIdx + 1, match.length() - 1);
patternBuilder.append('(');
patternBuilder.append(variablePattern);
patternBuilder.append(')');
String variableName = match.substring(1, colonIdx);
this.variableNames.add(variableName);
}
}
end = m.end();
}
patternBuilder.append(quote(pattern, end, pattern.length()));
this.pattern = Pattern.compile(patternBuilder.toString());
}
private String quote(String s, int start, int end) {
if (start == end) {
return "";
}
return Pattern.quote(s.substring(start, end));
}
/**
* Main entry point.
* @return {@code true} if the string matches against the pattern, or {@code false} otherwise.
*/
public boolean matchStrings(String str, Map<String, String> uriTemplateVariables) {
Matcher matcher = this.pattern.matcher(str);
if (matcher.matches()) {
if (uriTemplateVariables != null) {
// SPR-8455
if (this.variableNames.size() == matcher.groupCount()) {
throw new IllegalArgumentException("The number of capturing groups in the pattern segment " + this.pattern +
" does not match the number of URI template variables it defines, which can occur if " +
" capturing groups are used in a URI template regex. Use non-capturing groups instead.");
}
for (int i = 1; i <= matcher.groupCount(); i++) {
String name = this.variableNames.get(i - 1);
String value = matcher.group(i);
uriTemplateVariables.put(name, value);
}
}
return true;
}
else {
return false;
}
}
}
/**
* The default {@link Comparator} implementation returned by
* {@link #getPatternComparator(String)}.
* <p>In order, the most "generic" pattern is determined by the following:
* <ul>
* <li>if it's null or a capture all pattern (i.e. it is equal to "/**")</li>
* <li>if the other pattern is an actual match</li>
* <li>if it's a catch-all pattern (i.e. it ends with "**"</li>
* <li>if it's got more "*" than the other pattern</li>
* <li>if it's got more "{foo}" than the other pattern</li>
* <li>if it's shorter than the other pattern</li>
* </ul>
* </p>
*/
protected static class AntPatternComparator implements Comparator<String> {
private final String path;
public AntPatternComparator(String path) {
this.path = path;
}
/**
* Compare two patterns to determine which should match first, i.e. which is the most specific
* regarding the current path.
*
* @return a negative integer, zero, or a positive integer as pattern1 is
* more specific, equally specific, or less specific than pattern2.
*/
public int compare(String pattern1, String pattern2) {
PatternInfo info1 = new PatternInfo(pattern1);
PatternInfo info2 = new PatternInfo(pattern2);
if (info1.isLeastSpecific() && info2.isLeastSpecific()) {
return 0;
}
else if (info1.isLeastSpecific()) {
return 1;
}
else if (info2.isLeastSpecific()) {
return -1;
}
boolean pattern1EqualsPath = pattern1.equals(path);
boolean pattern2EqualsPath = pattern2.equals(path);
if (pattern1EqualsPath && pattern2EqualsPath) {
return 0;
}
else if (pattern1EqualsPath) {
return -1;
}
else if (pattern2EqualsPath) {
return 1;
}
if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) {
return 1;
}
else if (info2.isPrefixPattern() && info1.getDoubleWildcards() == 0) {
return -1;
}
if (info1.getTotalCount() != info2.getTotalCount()) {
return info1.getTotalCount() - info2.getTotalCount();
}
if (info1.getLength() != info2.getLength()) {
return info2.getLength() - info1.getLength();
}
if (info1.getSingleWildcards() < info2.getSingleWildcards()) {
return -1;
}
else if (info2.getSingleWildcards() < info1.getSingleWildcards()) {
return 1;
}
if (info1.getUriVars() < info2.getUriVars()) {
return -1;
}
else if (info2.getUriVars() < info1.getUriVars()) {
return 1;
}
return 0;
}
/**
* Value class that holds information about the pattern, e.g. number of
* occurrences of "*", "**", and "{" pattern elements.
*/
private static class PatternInfo {
private final String pattern;
private int uriVars;
private int singleWildcards;
private int doubleWildcards;
private boolean catchAllPattern;
private boolean prefixPattern;
private Integer length;
public PatternInfo(String pattern) {
this.pattern = pattern;
if (this.pattern != null) {
initCounters();
this.catchAllPattern = this.pattern.equals("/**");
this.prefixPattern = !this.catchAllPattern && this.pattern.endsWith("/**");
}
if (this.uriVars == 0) {
this.length = (this.pattern != null ? this.pattern.length() : 0);
}
}
protected void initCounters() {
int pos = 0;
while (pos < this.pattern.length()) {
if (this.pattern.charAt(pos) == '{') {
this.uriVars++;
pos++;
}
else if (this.pattern.charAt(pos) == '*') {
if (pos + 1 < this.pattern.length() && this.pattern.charAt(pos + 1) == '*') {
this.doubleWildcards++;
pos += 2;
}
else if (!this.pattern.substring(pos - 1).equals(".*")) {
this.singleWildcards++;
pos++;
}
else {
pos++;
}
}
else {
pos++;
}
}
}
public int getUriVars() {
return this.uriVars;
}
public int getSingleWildcards() {
return this.singleWildcards;
}
public int getDoubleWildcards() {
return this.doubleWildcards;
}
public boolean isLeastSpecific() {
return (this.pattern == null || this.catchAllPattern);
}
public boolean isPrefixPattern() {
return this.prefixPattern;
}
public int getTotalCount() {
return this.uriVars + this.singleWildcards + (2 * this.doubleWildcards);
}
/**
* Returns the length of the given pattern, where template variables are considered to be 1 long.
*/
public int getLength() {
if (this.length == null) {
this.length = VARIABLE_PATTERN.matcher(this.pattern).replaceAll("#").length();
}
return this.length;
}
}
}
/**
* A simple cache for patterns that depend on the configured path separator.
*/
private static class PathSeparatorPatternCache {
private final String endsOnWildCard;
private final String endsOnDoubleWildCard;
private PathSeparatorPatternCache(String pathSeparator) {
this.endsOnWildCard = pathSeparator + "*";
this.endsOnDoubleWildCard = pathSeparator + "**";
}
public String getEndsOnWildCard() {
return this.endsOnWildCard;
}
public String getEndsOnDoubleWildCard() {
return this.endsOnDoubleWildCard;
}
}
}
|
package com.publiccms.views.directive.trade;
// Generated 2019-6-16 9:47:27 by com.publiccms.common.generator.SourceGenerator
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.publiccms.common.base.AbstractTemplateDirective;
import com.publiccms.common.handler.RenderHandler;
import com.publiccms.common.tools.CommonUtils;
import com.publiccms.entities.sys.SysSite;
import com.publiccms.entities.trade.TradePaymentHistory;
import com.publiccms.logic.service.trade.TradePaymentHistoryService;
/**
*
* TradePaymentHistoryDirective
*
*/
@Component
public class TradePaymentHistoryDirective extends AbstractTemplateDirective {
@Override
public void execute(RenderHandler handler) throws IOException, Exception {
Long id = handler.getLong("id");
SysSite site = getSite(handler);
if (CommonUtils.notEmpty(id)) {
TradePaymentHistory entity = service.getEntity(id);
if (null != entity && site.getId() == entity.getSiteId()) {
handler.put("object", entity).render();
}
} else {
Long[] ids = handler.getLongArray("ids");
if (CommonUtils.notEmpty(ids)) {
List<TradePaymentHistory> entityList = service.getEntitys(ids);
Map<String, TradePaymentHistory> map = CommonUtils.listToMap(entityList, k -> k.getId().toString(), null, entity -> site.getId() == entity.getSiteId());
handler.put("map", map).render();
}
}
}
@Override
public boolean needAppToken() {
return true;
}
@Autowired
private TradePaymentHistoryService service;
}
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.requests.extensions.IWorkbookFunctionsKurtRequest;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.options.Option;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Workbook Functions Kurt Request Builder.
*/
public interface IWorkbookFunctionsKurtRequestBuilder extends IRequestBuilder {
/**
* Creates the IWorkbookFunctionsKurtRequest
*
* @return the IWorkbookFunctionsKurtRequest instance
*/
IWorkbookFunctionsKurtRequest buildRequest();
/**
* Creates the IWorkbookFunctionsKurtRequest with specific options instead of the existing options
*
* @param requestOptions the options for the request
* @return the IWorkbookFunctionsKurtRequest instance
*/
IWorkbookFunctionsKurtRequest buildRequest(final java.util.List<? extends Option> requestOptions);
}
|
/*
* 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.asterix.runtime.evaluators.functions;
import java.io.IOException;
import org.apache.asterix.builders.IAsterixListBuilder;
import org.apache.asterix.dataflow.data.nontagged.comparators.AObjectAscBinaryComparatorFactory;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.asterix.om.functions.IFunctionDescriptor;
import org.apache.asterix.om.functions.IFunctionDescriptorFactory;
import org.apache.asterix.om.functions.IFunctionTypeInferer;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.IAType;
import org.apache.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
import org.apache.asterix.runtime.evaluators.common.ListAccessor;
import org.apache.asterix.runtime.functions.FunctionTypeInferers;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.IBinaryComparator;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.api.IPointable;
import org.apache.hyracks.data.std.primitive.VoidPointable;
import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;
import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference;
/**
* <pre>
* array_remove(list, val1, val2, ...) returns a new list with all the values removed from the input
* list. Values cannot be null (i.e., one cannot remove nulls). It's case-sensitive to string value arguments.
*
* It throws an error at compile time if the number of arguments < 2
*
* It returns (or throws an error at runtime) in order:
* 1. missing, if any argument is missing.
* 2. null, if any argument is null.
* 3. an error if any value arg is of a list/object type (i.e. derived type) since deep equality is not yet supported.
* 4. otherwise, a new list that has the same type as the input list.
*
* </pre>
*/
public class ArrayRemoveDescriptor extends AbstractScalarFunctionDynamicDescriptor {
private static final long serialVersionUID = 1L;
private IAType[] argTypes;
public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
@Override
public IFunctionDescriptor createFunctionDescriptor() {
return new ArrayRemoveDescriptor();
}
@Override
public IFunctionTypeInferer createFunctionTypeInferer() {
return FunctionTypeInferers.SET_ARGUMENTS_TYPE;
}
};
@Override
public FunctionIdentifier getIdentifier() {
return BuiltinFunctions.ARRAY_REMOVE;
}
@Override
public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args)
throws AlgebricksException {
return new IScalarEvaluatorFactory() {
private static final long serialVersionUID = 1L;
@Override
public IScalarEvaluator createScalarEvaluator(final IHyracksTaskContext ctx) throws HyracksDataException {
return new ArrayRemoveEval(args, ctx);
}
};
}
@Override
public void setImmutableStates(Object... states) {
argTypes = (IAType[]) states;
}
public class ArrayRemoveEval extends AbstractArrayAddRemoveEval {
private final ArrayBackedValueStorage storage;
private final IPointable item;
private final IBinaryComparator comp;
public ArrayRemoveEval(IScalarEvaluatorFactory[] args, IHyracksTaskContext ctx) throws HyracksDataException {
super(args, ctx, 0, 1, args.length - 1, argTypes, true, sourceLoc, false, false);
storage = new ArrayBackedValueStorage();
item = new VoidPointable();
comp = AObjectAscBinaryComparatorFactory.INSTANCE.createBinaryComparator();
}
@Override
protected int getPosition(IFrameTupleReference tuple, IPointable listArg, ATypeTag listTag)
throws HyracksDataException {
return 0;
}
@Override
protected void processList(ListAccessor listAccessor, IAsterixListBuilder listBuilder, IPointable[] removed,
int position) throws IOException {
// get the list items one by one and append to the new list only if the list item is not in removed list
boolean addItem;
for (int i = 0; i < listAccessor.size(); i++) {
listAccessor.getOrWriteItem(i, item, storage);
addItem = true;
for (int j = 0; j < removed.length; j++) {
if (comp.compare(item.getByteArray(), item.getStartOffset(), item.getLength(),
removed[j].getByteArray(), removed[j].getStartOffset(), removed[j].getLength()) == 0) {
addItem = false;
break;
}
}
if (addItem) {
listBuilder.addItem(item);
}
}
}
}
}
|
package ml.dmlc.xgboost4j.java;
import java.io.IOException;
/**
* Load an entity.
*/
public interface Loadable {
boolean load() throws IOException;
boolean isLoaded();
String getName();
}
|
/*
* Copyright (C) 2017 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import com.google.common.util.concurrent.ClosingFuture.ClosingCallable;
import com.google.common.util.concurrent.ClosingFuture.DeferredCloser;
import java.io.Closeable;
import java.util.concurrent.ExecutionException;
/** Tests for {@link ClosingFuture} that exercise {@link ClosingFuture#finishToFuture()}. */
public class ClosingFutureFinishToFutureTest extends AbstractClosingFutureTest {
public void testFinishToFuture_throwsIfCalledTwice() throws Exception {
ClosingFuture<Closeable> closingFuture =
ClosingFuture.submit(
new ClosingCallable<Closeable>() {
@Override
public Closeable call(DeferredCloser closer) throws Exception {
return closer.eventuallyClose(mockCloseable, executor);
}
},
executor);
FluentFuture<Closeable> unused = closingFuture.finishToFuture();
try {
FluentFuture<Closeable> unused2 = closingFuture.finishToFuture();
fail("should have thrown");
} catch (IllegalStateException expected) {
}
}
public void testFinishToFuture_throwsAfterCallingFinishToValueAndCloser() throws Exception {
ClosingFuture<Closeable> closingFuture =
ClosingFuture.submit(
new ClosingCallable<Closeable>() {
@Override
public Closeable call(DeferredCloser closer) throws Exception {
return closer.eventuallyClose(mockCloseable, executor);
}
},
executor);
closingFuture.finishToValueAndCloser(new NoOpValueAndCloserConsumer<>(), directExecutor());
try {
FluentFuture<Closeable> unused = closingFuture.finishToFuture();
fail("should have thrown");
} catch (IllegalStateException expected) {
}
}
public void testFinishToFuture_preventsFurtherDerivation() {
ClosingFuture<String> closingFuture = ClosingFuture.from(immediateFuture("value1"));
FluentFuture<String> unused = closingFuture.finishToFuture();
assertDerivingThrowsIllegalStateException(closingFuture);
}
@Override
<T> T getFinalValue(ClosingFuture<T> closingFuture) throws ExecutionException {
return getUninterruptibly(closingFuture.finishToFuture());
}
@Override
void assertFinallyFailsWithException(ClosingFuture<?> closingFuture) {
assertThatFutureFailsWithException(closingFuture.finishToFuture());
}
@Override
void assertBecomesCanceled(ClosingFuture<?> closingFuture) throws ExecutionException {
assertThatFutureBecomesCancelled(closingFuture.finishToFuture());
}
@Override
void cancelFinalStepAndWait(ClosingFuture<TestCloseable> closingFuture) {
assertThat(closingFuture.finishToFuture().cancel(false)).isTrue();
waitUntilClosed(closingFuture);
futureCancelled.countDown();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.atom.AtomComponent;
/**
* Poll Atom RSS feeds.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface AtomComponentBuilderFactory {
/**
* Atom (camel-atom)
* Poll Atom RSS feeds.
*
* Category: rss
* Since: 1.2
* Maven coordinates: org.apache.camel:camel-atom
*/
static AtomComponentBuilder atom() {
return new AtomComponentBuilderImpl();
}
/**
* Builder for the Atom component.
*/
interface AtomComponentBuilder extends ComponentBuilder<AtomComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*/
default AtomComponentBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*/
default AtomComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
class AtomComponentBuilderImpl
extends
AbstractComponentBuilder<AtomComponent>
implements
AtomComponentBuilder {
@Override
protected AtomComponent buildConcreteComponent() {
return new AtomComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "bridgeErrorHandler": ((AtomComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "autowiredEnabled": ((AtomComponent) component).setAutowiredEnabled((boolean) value); return true;
default: return false;
}
}
}
}
|
package org.gradle.test.performance.mediummonolithicjavaproject.p321;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test6427 {
Production6427 objectUnderTest = new Production6427();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
}
|
package bot.modules.gabe.text;
import bot.core.Chatbot;
import bot.modules.gabe.point_system.util.Points;
import bot.core.gabes_framework.core.util.Emoji;
import bot.core.gabes_framework.framework.ModuleBase;
import bot.core.gabes_framework.core.util.Utils;
import bot.core.hollandjake_api.exceptions.MalformedCommandException;
import bot.core.hollandjake_api.helper.misc.Message;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class B extends ModuleBase {
private static final String B_ANY_REGEX = Utils.TO_REGEX("b (.*)");
private static final String INFO_REGEX = Utils.TO_REGEX("b");
public B(Chatbot chatbot) {
super(chatbot);
}
@Override
protected List<String> setRegexes() {
return List.of(B_ANY_REGEX, INFO_REGEX);
}
@Override
public boolean process(Message message) throws MalformedCommandException {
updateMatch(message);
String messageBody = message.getMessage();
String temp;
if (is(INFO_REGEX)) {
pushPoints(message, Points.POINTS_B_INFO_REGEX);
chatbot.sendMessage("Podaj tekst do transformacji.");
return true;
} else if (is(B_ANY_REGEX)) {
Matcher matcher = Pattern.compile(match).matcher(messageBody);
if (matcher.find()) {
pushPoints(message, Points.POINTS_B_REGEX);
temp = matcher.group(1);
for (int i = 0; i < messageBody.length(); i++) {
temp = temp
.replaceAll("B", Emoji.B)
.replaceAll("b", Emoji.B)
.replaceAll("P", Emoji.B)
.replaceAll("p", Emoji.B);
}
chatbot.sendMessage(temp);
return true;
}
}
return false;
}
}
|
/*
* 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.tomcat.util.http.parser;
import java.io.IOException;
import java.io.Reader;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;
/**
* HTTP header value parser implementation. Parsing HTTP headers as per RFC2616
* is not always as simple as it first appears. For headers that only use tokens
* the simple approach will normally be sufficient. However, for the other
* headers, while simple code meets 99.9% of cases, there are often some edge
* cases that make things far more complicated.
*
* The purpose of this parser is to let the parser worry about the edge cases.
* It provides tolerant (where safe to do so) parsing of HTTP header values
* assuming that wrapped header lines have already been unwrapped. (The Tomcat
* header processing code does the unwrapping.)
*
*/
public class HttpParser {
private static final StringManager sm = StringManager.getManager(HttpParser.class);
private static final Log log = LogFactory.getLog(HttpParser.class);
private static final int ARRAY_SIZE = 128;
private static final boolean[] IS_CONTROL = new boolean[ARRAY_SIZE];
private static final boolean[] IS_SEPARATOR = new boolean[ARRAY_SIZE];
private static final boolean[] IS_TOKEN = new boolean[ARRAY_SIZE];
private static final boolean[] IS_HEX = new boolean[ARRAY_SIZE];
private static final boolean[] IS_HTTP_PROTOCOL = new boolean[ARRAY_SIZE];
private static final boolean[] IS_ALPHA = new boolean[ARRAY_SIZE];
private static final boolean[] IS_NUMERIC = new boolean[ARRAY_SIZE];
private static final boolean[] REQUEST_TARGET_ALLOW = new boolean[ARRAY_SIZE];
private static final boolean[] IS_UNRESERVED = new boolean[ARRAY_SIZE];
private static final boolean[] IS_SUBDELIM = new boolean[ARRAY_SIZE];
private static final boolean[] IS_USERINFO = new boolean[ARRAY_SIZE];
private static final boolean[] IS_RELAXABLE = new boolean[ARRAY_SIZE];
private static final HttpParser DEFAULT;
static {
for (int i = 0; i < ARRAY_SIZE; i++) {
// Control> 0-31, 127
if (i < 32 || i == 127) {
IS_CONTROL[i] = true;
}
// Separator
if ( i == '(' || i == ')' || i == '<' || i == '>' || i == '@' ||
i == ',' || i == ';' || i == ':' || i == '\\' || i == '\"' ||
i == '/' || i == '[' || i == ']' || i == '?' || i == '=' ||
i == '{' || i == '}' || i == ' ' || i == '\t') {
IS_SEPARATOR[i] = true;
}
// Token: Anything 0-127 that is not a control and not a separator
if (!IS_CONTROL[i] && !IS_SEPARATOR[i] && i < 128) {
IS_TOKEN[i] = true;
}
// Hex: 0-9, a-f, A-F
if ((i >= '0' && i <='9') || (i >= 'a' && i <= 'f') || (i >= 'A' && i <= 'F')) {
IS_HEX[i] = true;
}
// Not valid for HTTP protocol
// "HTTP/" DIGIT "." DIGIT
if (i == 'H' || i == 'T' || i == 'P' || i == '/' || i == '.' || (i >= '0' && i <= '9')) {
IS_HTTP_PROTOCOL[i] = true;
}
if (i >= '0' && i <= '9') {
IS_NUMERIC[i] = true;
}
if (i >= 'a' && i <= 'z' || i >= 'A' && i <= 'Z') {
IS_ALPHA[i] = true;
}
if (IS_ALPHA[i] || IS_NUMERIC[i] || i == '-' || i == '.' || i == '_' || i == '~') {
IS_UNRESERVED[i] = true;
}
if (i == '!' || i == '$' || i == '&' || i == '\'' || i == '(' || i == ')' || i == '*' ||
i == '+' || i == ',' || i == ';' || i == '=') {
IS_SUBDELIM[i] = true;
}
// userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
if (IS_UNRESERVED[i] || i == '%' || IS_SUBDELIM[i] || i == ':') {
IS_USERINFO[i] = true;
}
// The characters that are normally not permitted for which the
// restrictions may be relaxed when used in the path and/or query
// string
if (i == '\"' || i == '<' || i == '>' || i == '[' || i == '\\' || i == ']' ||
i == '^' || i == '`' || i == '{' || i == '|' || i == '}') {
IS_RELAXABLE[i] = true;
}
}
String prop = System.getProperty("tomcat.util.http.parser.HttpParser.requestTargetAllow");
if (prop != null) {
for (int i = 0; i < prop.length(); i++) {
char c = prop.charAt(i);
if (c == '{' || c == '}' || c == '|') {
REQUEST_TARGET_ALLOW[c] = true;
} else {
log.warn(sm.getString("http.invalidRequestTargetCharacter",
Character.valueOf(c)));
}
}
}
DEFAULT = new HttpParser(null, null);
}
private final boolean[] IS_NOT_REQUEST_TARGET = new boolean[ARRAY_SIZE];
private final boolean[] IS_ABSOLUTEPATH_RELAXED = new boolean[ARRAY_SIZE];
private final boolean[] IS_QUERY_RELAXED = new boolean[ARRAY_SIZE];
public HttpParser(String relaxedPathChars, String relaxedQueryChars) {
for (int i = 0; i < ARRAY_SIZE; i++) {
// Not valid for request target.
// Combination of multiple rules from RFC7230 and RFC 3986. Must be
// ASCII, no controls plus a few additional characters excluded
if (IS_CONTROL[i] || i > 127 ||
i == ' ' || i == '\"' || i == '#' || i == '<' || i == '>' || i == '\\' ||
i == '^' || i == '`' || i == '{' || i == '|' || i == '}') {
if (!REQUEST_TARGET_ALLOW[i]) {
IS_NOT_REQUEST_TARGET[i] = true;
}
}
/*
* absolute-path = 1*( "/" segment )
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*
* Note pchar allows everything userinfo allows plus "@"
*/
if (IS_USERINFO[i] || i == '@' || i == '/' || REQUEST_TARGET_ALLOW[i]) {
IS_ABSOLUTEPATH_RELAXED[i] = true;
}
/*
* query = *( pchar / "/" / "?" )
*
* Note query allows everything absolute-path allows plus "?"
*/
if (IS_ABSOLUTEPATH_RELAXED[i] || i == '?' || REQUEST_TARGET_ALLOW[i]) {
IS_QUERY_RELAXED[i] = true;
}
}
relax(IS_ABSOLUTEPATH_RELAXED, relaxedPathChars);
relax(IS_QUERY_RELAXED, relaxedQueryChars);
}
public boolean isNotRequestTargetRelaxed(int c) {
// Fast for valid request target characters, slower for some incorrect
// ones
try {
return IS_NOT_REQUEST_TARGET[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return true;
}
}
public boolean isAbsolutePathRelaxed(int c) {
// Fast for valid user info characters, slower for some incorrect
// ones
try {
return IS_ABSOLUTEPATH_RELAXED[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public boolean isQueryRelaxed(int c) {
// Fast for valid user info characters, slower for some incorrect
// ones
try {
return IS_QUERY_RELAXED[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public static String unquote(String input) {
if (input == null || input.length() < 2) {
return input;
}
int start;
int end;
// Skip surrounding quotes if there are any
if (input.charAt(0) == '"') {
start = 1;
end = input.length() - 1;
} else {
start = 0;
end = input.length();
}
StringBuilder result = new StringBuilder();
for (int i = start ; i < end; i++) {
char c = input.charAt(i);
if (input.charAt(i) == '\\') {
i++;
result.append(input.charAt(i));
} else {
result.append(c);
}
}
return result.toString();
}
public static boolean isToken(int c) {
// Fast for correct values, slower for incorrect ones
try {
return IS_TOKEN[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public static boolean isHex(int c) {
// Fast for correct values, slower for some incorrect ones
try {
return IS_HEX[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public static boolean isNotRequestTarget(int c) {
return DEFAULT.isNotRequestTargetRelaxed(c);
}
public static boolean isHttpProtocol(int c) {
// Fast for valid HTTP protocol characters, slower for some incorrect
// ones
try {
return IS_HTTP_PROTOCOL[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public static boolean isAlpha(int c) {
// Fast for valid alpha characters, slower for some incorrect
// ones
try {
return IS_ALPHA[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public static boolean isNumeric(int c) {
// Fast for valid numeric characters, slower for some incorrect
// ones
try {
return IS_NUMERIC[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public static boolean isUserInfo(int c) {
// Fast for valid user info characters, slower for some incorrect
// ones
try {
return IS_USERINFO[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
private static boolean isRelaxable(int c) {
// Fast for valid user info characters, slower for some incorrect
// ones
try {
return IS_RELAXABLE[c];
} catch (ArrayIndexOutOfBoundsException ex) {
return false;
}
}
public static boolean isAbsolutePath(int c) {
return DEFAULT.isAbsolutePathRelaxed(c);
}
public static boolean isQuery(int c) {
return DEFAULT.isQueryRelaxed(c);
}
// Skip any LWS and position to read the next character. The next character
// is returned as being able to 'peek()' it allows a small optimisation in
// some cases.
static int skipLws(Reader input) throws IOException {
input.mark(1);
int c = input.read();
while (c == 32 || c == 9 || c == 10 || c == 13) {
input.mark(1);
c = input.read();
}
input.reset();
return c;
}
static SkipResult skipConstant(Reader input, String constant) throws IOException {
int len = constant.length();
skipLws(input);
input.mark(len);
int c = input.read();
for (int i = 0; i < len; i++) {
if (i == 0 && c == -1) {
return SkipResult.EOF;
}
if (c != constant.charAt(i)) {
input.reset();
return SkipResult.NOT_FOUND;
}
if (i != (len - 1)) {
c = input.read();
}
}
return SkipResult.FOUND;
}
/**
* @return the token if one was found, the empty string if no data was
* available to read or <code>null</code> if data other than a
* token was found
*/
static String readToken(Reader input) throws IOException {
StringBuilder result = new StringBuilder();
skipLws(input);
input.mark(1);
int c = input.read();
while (c != -1 && isToken(c)) {
result.append((char) c);
input.mark(1);
c = input.read();
}
// Use mark(1)/reset() rather than skip(-1) since skip() is a NOP
// once the end of the String has been reached.
input.reset();
if (c != -1 && result.length() == 0) {
return null;
} else {
return result.toString();
}
}
/**
* @return the quoted string if one was found, null if data other than a
* quoted string was found or null if the end of data was reached
* before the quoted string was terminated
*/
static String readQuotedString(Reader input, boolean returnQuoted) throws IOException {
skipLws(input);
int c = input.read();
if (c != '"') {
return null;
}
StringBuilder result = new StringBuilder();
if (returnQuoted) {
result.append('\"');
}
c = input.read();
while (c != '"') {
if (c == -1) {
return null;
} else if (c == '\\') {
c = input.read();
if (returnQuoted) {
result.append('\\');
}
result.append((char) c);
} else {
result.append((char) c);
}
c = input.read();
}
if (returnQuoted) {
result.append('\"');
}
return result.toString();
}
static String readTokenOrQuotedString(Reader input, boolean returnQuoted)
throws IOException {
// Peek at next character to enable correct method to be called
int c = skipLws(input);
if (c == '"') {
return readQuotedString(input, returnQuoted);
} else {
return readToken(input);
}
}
/**
* Token can be read unambiguously with or without surrounding quotes so
* this parsing method for token permits optional surrounding double quotes.
* This is not defined in any RFC. It is a special case to handle data from
* buggy clients (known buggy clients for DIGEST auth include Microsoft IE 8
* & 9, Apple Safari for OSX and iOS) that add quotes to values that
* should be tokens.
*
* @return the token if one was found, null if data other than a token or
* quoted token was found or null if the end of data was reached
* before a quoted token was terminated
*/
static String readQuotedToken(Reader input) throws IOException {
StringBuilder result = new StringBuilder();
boolean quoted = false;
skipLws(input);
input.mark(1);
int c = input.read();
if (c == '"') {
quoted = true;
} else if (c == -1 || !isToken(c)) {
return null;
} else {
result.append((char) c);
}
input.mark(1);
c = input.read();
while (c != -1 && isToken(c)) {
result.append((char) c);
input.mark(1);
c = input.read();
}
if (quoted) {
if (c != '"') {
return null;
}
} else {
// Use mark(1)/reset() rather than skip(-1) since skip() is a NOP
// once the end of the String has been reached.
input.reset();
}
if (c != -1 && result.length() == 0) {
return null;
} else {
return result.toString();
}
}
/**
* LHEX can be read unambiguously with or without surrounding quotes so this
* parsing method for LHEX permits optional surrounding double quotes. Some
* buggy clients (libwww-perl for DIGEST auth) are known to send quoted LHEX
* when the specification requires just LHEX.
*
* <p>
* LHEX are, literally, lower-case hexadecimal digits. This implementation
* allows for upper-case digits as well, converting the returned value to
* lower-case.
*
* @return the sequence of LHEX (minus any surrounding quotes) if any was
* found, or <code>null</code> if data other LHEX was found
*/
static String readLhex(Reader input) throws IOException {
StringBuilder result = new StringBuilder();
boolean quoted = false;
skipLws(input);
input.mark(1);
int c = input.read();
if (c == '"') {
quoted = true;
} else if (c == -1 || !isHex(c)) {
return null;
} else {
if ('A' <= c && c <= 'F') {
c -= ('A' - 'a');
}
result.append((char) c);
}
input.mark(1);
c = input.read();
while (c != -1 && isHex(c)) {
if ('A' <= c && c <= 'F') {
c -= ('A' - 'a');
}
result.append((char) c);
input.mark(1);
c = input.read();
}
if (quoted) {
if (c != '"') {
return null;
}
} else {
// Use mark(1)/reset() rather than skip(-1) since skip() is a NOP
// once the end of the String has been reached.
input.reset();
}
if (c != -1 && result.length() == 0) {
return null;
} else {
return result.toString();
}
}
static double readWeight(Reader input, char delimiter) throws IOException {
skipLws(input);
int c = input.read();
if (c == -1 || c == delimiter) {
// No q value just whitespace
return 1;
} else if (c != 'q') {
// Malformed. Use quality of zero so it is dropped.
skipUntil(input, c, delimiter);
return 0;
}
// RFC 7231 does not allow whitespace here but be tolerant
skipLws(input);
c = input.read();
if (c != '=') {
// Malformed. Use quality of zero so it is dropped.
skipUntil(input, c, delimiter);
return 0;
}
// RFC 7231 does not allow whitespace here but be tolerant
skipLws(input);
c = input.read();
// Should be no more than 3 decimal places
StringBuilder value = new StringBuilder(5);
int decimalPlacesRead = -1;
if (c == '0' || c == '1') {
value.append((char) c);
c = input.read();
while (true) {
if (decimalPlacesRead == -1 && c == '.') {
value.append('.');
decimalPlacesRead = 0;
} else if (decimalPlacesRead > -1 && c >= '0' && c <= '9') {
if (decimalPlacesRead < 3) {
value.append((char) c);
decimalPlacesRead++;
}
} else {
break;
}
c = input.read();
}
} else {
// Malformed. Use quality of zero so it is dropped and skip until
// EOF or the next delimiter
skipUntil(input, c, delimiter);
return 0;
}
if (c == 9 || c == 32) {
skipLws(input);
c = input.read();
}
// Must be at delimiter or EOF
if (c != delimiter && c != -1) {
// Malformed. Use quality of zero so it is dropped and skip until
// EOF or the next delimiter
skipUntil(input, c, delimiter);
return 0;
}
double result = Double.parseDouble(value.toString());
if (result > 1) {
return 0;
}
return result;
}
/**
* @return If inIPv6 is false, the position of ':' that separates the host
* from the port or -1 if it is not present. If inIPv6 is true, the
* number of characters read
*/
static int readHostIPv4(Reader reader, boolean inIPv6) throws IOException {
int octet = -1;
int octetCount = 1;
int c;
int pos = 0;
// readAheadLimit doesn't matter as all the readers passed to this
// method buffer the entire content.
reader.mark(1);
do {
c = reader.read();
if (c == '.') {
if (octet > -1 && octet < 256) {
// Valid
octetCount++;
octet = -1;
} else if (inIPv6 || octet == -1) {
throw new IllegalArgumentException(
sm.getString("http.invalidOctet", Integer.toString(octet)));
} else {
// Might not be an IPv4 address. Could be a host / FQDN with
// a fully numeric component.
reader.reset();
return readHostDomainName(reader);
}
} else if (isNumeric(c)) {
if (octet == -1) {
octet = c - '0';
} else if (octet == 0) {
// Leading zero in non-zero octet. Not valid (ambiguous).
if (inIPv6) {
throw new IllegalArgumentException(sm.getString("http.invalidLeadingZero"));
} else {
// Could be a host/FQDN
reader.reset();
return readHostDomainName(reader);
}
} else {
octet = octet * 10 + c - '0';
}
} else if (c == ':') {
break;
} else if (c == -1) {
if (inIPv6) {
throw new IllegalArgumentException(sm.getString("http.noClosingBracket"));
} else {
pos = -1;
break;
}
} else if (c == ']') {
if (inIPv6) {
pos++;
break;
} else {
throw new IllegalArgumentException(sm.getString("http.closingBracket"));
}
} else if (!inIPv6 && (isAlpha(c) || c == '-')) {
// Go back to the start and parse as a host / FQDN
reader.reset();
return readHostDomainName(reader);
} else {
throw new IllegalArgumentException(sm.getString(
"http.illegalCharacterIpv4", Character.toString((char) c)));
}
pos++;
} while (true);
if (octetCount != 4 || octet < 0 || octet > 255) {
// Might not be an IPv4 address. Could be a host name or a FQDN with
// fully numeric components. Go back to the start and parse as a
// host / FQDN.
reader.reset();
return readHostDomainName(reader);
}
return pos;
}
/**
* @return The position of ':' that separates the host from the port or -1
* if it is not present
*/
static int readHostIPv6(Reader reader) throws IOException {
// Must start with '['
int c = reader.read();
if (c != '[') {
throw new IllegalArgumentException(sm.getString("http.noOpeningBracket"));
}
int h16Count = 0;
int h16Size = 0;
int pos = 1;
boolean parsedDoubleColon = false;
int precedingColonsCount = 0;
do {
c = reader.read();
if (h16Count == 0 && precedingColonsCount == 1 && c != ':') {
// Can't start with a single :
throw new IllegalArgumentException(sm.getString("http.singleColonStart"));
}
if (HttpParser.isHex(c)) {
if (h16Size == 0) {
// Start of a new h16 block
precedingColonsCount = 0;
h16Count++;
}
h16Size++;
if (h16Size > 4) {
throw new IllegalArgumentException(sm.getString("http.invalidHextet"));
}
} else if (c == ':') {
if (precedingColonsCount >=2 ) {
// ::: is not allowed
throw new IllegalArgumentException(sm.getString("http.tooManyColons"));
} else {
if(precedingColonsCount == 1) {
// End of ::
if (parsedDoubleColon ) {
// Only allowed one :: sequence
throw new IllegalArgumentException(
sm.getString("http.tooManyDoubleColons"));
}
parsedDoubleColon = true;
// :: represents at least one h16 block
h16Count++;
}
precedingColonsCount++;
// mark if the next symbol is hex before the actual read
reader.mark(4);
}
h16Size = 0;
} else if (c == ']') {
if (precedingColonsCount == 1) {
// Can't end on a single ':'
throw new IllegalArgumentException(sm.getString("http.singleColonEnd"));
}
pos++;
break;
} else if (c == '.') {
if (h16Count == 7 || h16Count < 7 && parsedDoubleColon) {
reader.reset();
pos -= h16Size;
pos += readHostIPv4(reader, true);
h16Count++;
break;
} else {
throw new IllegalArgumentException(sm.getString("http.invalidIpv4Location"));
}
} else {
throw new IllegalArgumentException(sm.getString(
"http.illegalCharacterIpv6", Character.toString((char) c)));
}
pos++;
} while (true);
if (h16Count > 8) {
throw new IllegalArgumentException(
sm.getString("http.tooManyHextets", Integer.toString(h16Count)));
} else if (h16Count != 8 && !parsedDoubleColon) {
throw new IllegalArgumentException(
sm.getString("http.tooFewHextets", Integer.toString(h16Count)));
}
c = reader.read();
if (c == ':') {
return pos;
} else {
if(c == -1) {
return -1;
}
throw new IllegalArgumentException(
sm.getString("http.illegalAfterIpv6", Character.toString((char) c)));
}
}
/**
* @return The position of ':' that separates the host from the port or -1
* if it is not present
*/
static int readHostDomainName(Reader reader) throws IOException {
DomainParseState state = DomainParseState.NEW;
int pos = 0;
while (state.mayContinue()) {
state = state.next(reader.read());
pos++;
}
if (DomainParseState.COLON == state) {
// State identifies the state of the previous character
return pos - 1;
} else {
return -1;
}
}
/**
* Skips all characters until EOF or the specified target is found. Normally
* used to skip invalid input until the next separator.
*/
static SkipResult skipUntil(Reader input, int c, char target) throws IOException {
while (c != -1 && c != target) {
c = input.read();
}
if (c == -1) {
return SkipResult.EOF;
} else {
return SkipResult.FOUND;
}
}
private void relax(boolean[] flags, String relaxedChars) {
if (relaxedChars != null && relaxedChars.length() > 0) {
char[] chars = relaxedChars.toCharArray();
for (char c : chars) {
if (isRelaxable(c)) {
flags[c] = true;
IS_NOT_REQUEST_TARGET[c] = false;
}
}
}
}
private enum DomainParseState {
NEW( true, false, false, false, " at the start of"),
ALPHA( true, true, true, true, " after a letter in"),
NUMERIC( true, true, true, true, " after a number in"),
PERIOD( true, false, false, true, " after a period in"),
HYPHEN( true, true, false, false, " after a hypen in"),
COLON( false, false, false, false, " after a colon in"),
END( false, false, false, false, " at the end of");
private final boolean mayContinue;
private final boolean allowsHyphen;
private final boolean allowsPeriod;
private final boolean allowsEnd;
private final String errorLocation;
private DomainParseState(boolean mayContinue, boolean allowsHyphen, boolean allowsPeriod,
boolean allowsEnd, String errorLocation) {
this.mayContinue = mayContinue;
this.allowsHyphen = allowsHyphen;
this.allowsPeriod = allowsPeriod;
this.allowsEnd = allowsEnd;
this.errorLocation = errorLocation;
}
public boolean mayContinue() {
return mayContinue;
}
public DomainParseState next(int c) {
if (c == -1) {
if (allowsEnd) {
return END;
} else {
throw new IllegalArgumentException(
sm.getString("http.invalidSegmentEndState", this.name()));
}
} else if (HttpParser.isAlpha(c)) {
return ALPHA;
} else if (HttpParser.isNumeric(c)) {
return NUMERIC;
} else if (c == '.') {
if (allowsPeriod) {
return PERIOD;
} else {
throw new IllegalArgumentException(sm.getString("http.invalidCharacterDomain",
Character.toString((char) c), errorLocation));
}
} else if (c == ':') {
if (allowsEnd) {
return COLON;
} else {
throw new IllegalArgumentException(sm.getString("http.invalidCharacterDomain",
Character.toString((char) c), errorLocation));
}
} else if (c == '-') {
if (allowsHyphen) {
return HYPHEN;
} else {
throw new IllegalArgumentException(sm.getString("http.invalidCharacterDomain",
Character.toString((char) c), errorLocation));
}
} else {
throw new IllegalArgumentException(sm.getString(
"http.illegalCharacterDomain", Character.toString((char) c)));
}
}
}
}
|
/*
* 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.dac.cmd.upgrade;
import static com.dremio.common.util.DremioVersionInfo.VERSION;
import static com.dremio.dac.cmd.upgrade.LegacyUpgradeTask.VERSION_203;
import static com.dremio.dac.cmd.upgrade.LegacyUpgradeTask.VERSION_205;
import static com.dremio.dac.cmd.upgrade.Upgrade.UPGRADE_VERSION_ORDERING;
import static junit.framework.TestCase.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.dremio.common.Version;
import com.dremio.dac.proto.model.source.UpgradeStatus;
import com.dremio.dac.proto.model.source.UpgradeTaskStore;
import com.dremio.dac.server.DACConfig;
import com.dremio.dac.support.SupportService;
import com.dremio.dac.support.UpgradeStore;
import com.dremio.datastore.LocalKVStoreProvider;
import com.dremio.datastore.adapter.LegacyKVStoreProviderAdapter;
import com.dremio.datastore.api.LegacyKVStoreProvider;
import com.dremio.services.configuration.ConfigurationStore;
import com.dremio.services.configuration.proto.ConfigurationEntry;
import com.dremio.test.DremioTest;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.protostuff.ByteString;
/**
* Test for {@code Upgrade}
*/
public class TestUpgrade extends DremioTest {
/**
* A test upgrade task
*/
public static final class TopPriorityTask extends UpgradeTask {
public TopPriorityTask() {
super("test-top-priority-class", ImmutableList.of(SetExportType.taskUUID));
}
@Override
public String getTaskUUID() {
return "test-top-priority-class";
}
@Override
public void upgrade(UpgradeContext context) throws Exception {
}
}
/**
* A test upgrade task
*/
public static final class LowPriorityTask extends UpgradeTask {
public LowPriorityTask() {
super("test-low-priority-class", ImmutableList.of("test-top-priority-class"));
}
@Override
public String getTaskUUID() {
return "test-low-priority-class";
}
@Override
public void upgrade(UpgradeContext context) throws Exception {
}
}
private static final LocalKVStoreProvider kvStoreProvider = new LocalKVStoreProvider(
CLASSPATH_SCAN_RESULT, null, true, false);
private static LegacyKVStoreProvider legacyKVStoreProvider;
private static UpgradeStore upgradeStore;
@BeforeClass
public static void beforeClass() throws Exception {
kvStoreProvider.start();
legacyKVStoreProvider = kvStoreProvider.asLegacy();
upgradeStore = new UpgradeStore(legacyKVStoreProvider);
}
@AfterClass
public static void afterClass() throws Exception {
legacyKVStoreProvider.close();
}
@After
public void afterTest() throws Exception {
List<UpgradeTaskStore> upgradeTaskStoreList = upgradeStore.getAllUpgradeTasks();
for (UpgradeTaskStore task : upgradeTaskStoreList) {
upgradeStore.deleteUpgradeTaskStoreEntry(task.getId().getId());
}
}
@Test
public void testTaskUpgrade() throws Exception {
UpgradeTask myTask = new TestUpgradeFailORSuccessTask("Test Upgrade Task", VERSION_203);
Version kvStoreVersion = VERSION_203;
final UpgradeContext context = tasksExecutor(kvStoreVersion, ImmutableList.of(myTask));
assertThat(((TestUpgradeFailORSuccessTask) myTask).isTaskRun).isTrue();
List<UpgradeTaskStore> upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(1, upgradeEntries.size());
assertEquals(myTask.getTaskUUID(), upgradeEntries.get(0).getId().getId());
assertEquals(TestUpgradeFailORSuccessTask.class.getSimpleName(), myTask.getTaskName());
assertEquals(1, upgradeEntries.get(0).getRunsList().size());
assertEquals(UpgradeStatus.COMPLETED, upgradeEntries.get(0).getRunsList().get(0).getStatus());
}
@Test
public void testNoUpgradeWithMaxVersion() throws Exception {
UpgradeTask myTask = new TestUpgradeFailORSuccessTask("Test Upgrade Task", VERSION_203);
Version kvStoreVersion = VERSION_205;
final UpgradeContext context = tasksExecutor(kvStoreVersion, ImmutableList.of(myTask));
assertThat(((TestUpgradeFailORSuccessTask) myTask).isTaskRun).isFalse();
List<UpgradeTaskStore> upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(1, upgradeEntries.size());
assertEquals(myTask.getTaskUUID(), upgradeEntries.get(0).getId().getId());
assertEquals(TestUpgradeFailORSuccessTask.class.getSimpleName(), upgradeEntries.get(0).getName());
assertEquals(1, upgradeEntries.get(0).getRunsList().size());
assertEquals(UpgradeStatus.OUTDATED, upgradeEntries.get(0).getRunsList().get(0).getStatus());
}
@Test
public void testTaskUpgradeFail() throws Exception {
UpgradeTask myTask = new TestUpgradeFailORSuccessTask("Test Upgrade Failed Task", VERSION_203);
Version kvStoreVersion = VERSION_203;
((TestUpgradeFailORSuccessTask)myTask).toFail = true;
assertThatThrownBy(() -> tasksExecutor(kvStoreVersion, ImmutableList.of(myTask)))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("taskFailure");
List<UpgradeTaskStore> upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(1, upgradeEntries.size());
assertEquals(myTask.getTaskUUID(), upgradeEntries.get(0).getId().getId());
assertEquals(TestUpgradeFailORSuccessTask.class.getSimpleName(), upgradeEntries.get(0).getName());
assertEquals(1, upgradeEntries.get(0).getRunsList().size());
assertEquals(UpgradeStatus.FAILED, upgradeEntries.get(0).getRunsList().get(0).getStatus());
}
@Test
public void testUpgradeTaskCompleted() throws Exception {
UpgradeTask myTask = new TestUpgradeFailORSuccessTask("Test Upgrade Task", VERSION_205);
Version kvStoreVersion = VERSION_203;
final UpgradeContext context = tasksExecutor(kvStoreVersion, ImmutableList.of(myTask));
assertThat(((TestUpgradeFailORSuccessTask) myTask).isTaskRun).isTrue();
List<UpgradeTaskStore> upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(1, upgradeEntries.size());
assertEquals(myTask.getTaskUUID(), upgradeEntries.get(0).getId().getId());
assertEquals(TestUpgradeFailORSuccessTask.class.getSimpleName(), upgradeEntries.get(0).getName());
assertEquals(1, upgradeEntries.get(0).getRunsList().size());
assertEquals(UpgradeStatus.COMPLETED, upgradeEntries.get(0).getRunsList().get(0).getStatus());
// try to upgrade again
UpgradeTask myTaskAgain = new TestUpgradeFailORSuccessTask("Test Upgrade Task", VERSION_205);
tasksExecutor(kvStoreVersion, ImmutableList.of(myTask));
assertThat(((TestUpgradeFailORSuccessTask) myTaskAgain).isTaskRun).isFalse();
upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(1, upgradeEntries.size());
assertEquals(myTaskAgain.getTaskUUID(), upgradeEntries.get(0).getId().getId());
assertEquals(TestUpgradeFailORSuccessTask.class.getSimpleName(), upgradeEntries.get(0).getName());
assertEquals(1, upgradeEntries.get(0).getRunsList().size());
assertEquals(UpgradeStatus.COMPLETED, upgradeEntries.get(0).getRunsList().get(0).getStatus());
}
@Test
public void testUpgradeAfterFailure() throws Exception {
UpgradeTask myTask = new TestUpgradeFailORSuccessTask("Test Upgrade Failed Task", VERSION_205);
Version kvStoreVersion = VERSION_203;
((TestUpgradeFailORSuccessTask)myTask).toFail = true;
assertThatThrownBy(() -> tasksExecutor(kvStoreVersion, ImmutableList.of(myTask)))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("taskFailure");
List<UpgradeTaskStore> upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(1, upgradeEntries.size());
assertEquals(myTask.getTaskUUID(), upgradeEntries.get(0).getId().getId());
assertEquals(TestUpgradeFailORSuccessTask.class.getSimpleName(), upgradeEntries.get(0).getName());
assertEquals(1, upgradeEntries.get(0).getRunsList().size());
assertEquals(UpgradeStatus.FAILED, upgradeEntries.get(0).getRunsList().get(0).getStatus());
// try to upgrade again
UpgradeTask myTaskAgain = new TestUpgradeFailORSuccessTask("Test Upgrade Task", VERSION_205);
((TestUpgradeFailORSuccessTask) myTaskAgain).toFail = false;
assertThatThrownBy(() -> tasksExecutor(kvStoreVersion, ImmutableList.of(myTask)))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("taskFailure");
upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(1, upgradeEntries.size());
assertEquals(myTaskAgain.getTaskUUID(), upgradeEntries.get(0).getId().getId());
assertEquals(TestUpgradeFailORSuccessTask.class.getSimpleName(), upgradeEntries.get(0).getName());
assertEquals(2, upgradeEntries.get(0).getRunsList().size());
assertEquals(UpgradeStatus.FAILED, upgradeEntries.get(0).getRunsList().get(0).getStatus());
assertEquals(UpgradeStatus.FAILED, upgradeEntries.get(0).getRunsList().get(1).getStatus());
}
@Test
public void testMultipleTasks() throws Exception {
UpgradeTask myTask = new TestUpgradeFailORSuccessTask("Test Upgrade Task", VERSION_205);
UpgradeTask myTask1 = new TestUpgradeTask("Test Upgrade2 Task", VERSION_203);
Version kvStoreVersion = VERSION_203;
final UpgradeContext context = tasksExecutor(kvStoreVersion, ImmutableList.of(myTask, myTask1));
assertThat(((TestUpgradeFailORSuccessTask) myTask).isTaskRun).isTrue();
assertThat(((TestUpgradeTask) myTask1).isTaskRun).isTrue();
List<UpgradeTaskStore> upgradeEntries = upgradeStore.getAllUpgradeTasks();
assertEquals(2, upgradeEntries.size());
Set<String> expectedNames = ImmutableSet.of(TestUpgradeTask.class.getSimpleName(),
TestUpgradeFailORSuccessTask.class.getSimpleName());
Set<String> realNames = Sets.newHashSet();
for (UpgradeTaskStore task : upgradeEntries) {
assertEquals(1, task.getRunsList().size());
assertEquals(UpgradeStatus.COMPLETED, task.getRunsList().get(0).getStatus());
realNames.add(task.getName());
}
assertEquals(expectedNames, realNames);
}
private UpgradeContext tasksExecutor(Version kvStoreVersion, List<UpgradeTask> tasks) throws Exception {
final UpgradeContext context = new UpgradeContext(kvStoreProvider, legacyKVStoreProvider, null, null, null);
List<UpgradeTask> tasksToRun = new ArrayList<>();
for(UpgradeTask task: tasks) {
if (upgradeStore.isUpgradeTaskCompleted(task.getTaskUUID())) {
continue;
}
tasksToRun.add(task);
}
if (!tasksToRun.isEmpty()) {
for (UpgradeTask task : tasksToRun) {
Upgrade.upgradeExternal(task, context, upgradeStore, kvStoreVersion);
}
}
return context;
}
private static class TestUpgradeFailORSuccessTask extends UpgradeTask implements LegacyUpgradeTask {
private boolean toFail = false;
private boolean isTaskRun = false;
private Version maxVersion;
public TestUpgradeFailORSuccessTask(String name, Version maxVersion) {
super(name, ImmutableList.of());
this.maxVersion = maxVersion;
}
@Override
public Version getMaxVersion() {
return maxVersion;
}
@Override
public String getTaskUUID() {
return "TestUpgradeFailORSuccessTask_ID";
}
@Override
public void upgrade(UpgradeContext context) throws Exception {
isTaskRun = true;
if (toFail) {
throw new RuntimeException("taskFailure");
}
}
}
private static class TestUpgradeTask extends UpgradeTask implements LegacyUpgradeTask {
private boolean toFail = false;
private boolean isTaskRun = false;
private Version maxVersion;
public TestUpgradeTask(String name, Version maxVersion) {
super(name, ImmutableList.of());
this.maxVersion = maxVersion;
}
@Override
public Version getMaxVersion() {
return maxVersion;
}
@Override
public String getTaskUUID() {
return "TestUpgradeTask_ID";
}
@Override
public void upgrade(UpgradeContext context) throws Exception {
isTaskRun = true;
if (toFail) {
throw new RuntimeException("taskFailure");
}
}
}
/**
* Verify that we don't add a task whose version is higher than the current version,
* as it would create a loop where user would have to upgrade but would never be able
* to update the version to a greater version than the task in the kvstore.
*/
@Test
public void testMaxTaskVersion() {
DACConfig dacConfig = DACConfig.newConfig();
Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false);
final Optional<Version> tasksGreatestMaxVersion = upgrade.getUpgradeTasks().stream()
.filter((v) -> v instanceof LegacyUpgradeTask)
.map((v) -> ((LegacyUpgradeTask)v).getMaxVersion() )
.max(UPGRADE_VERSION_ORDERING);
// Making sure that current version is newer that all upgrade tasks
assertThat(UPGRADE_VERSION_ORDERING.compare(tasksGreatestMaxVersion.get(), VERSION) <= 0)
.as(String.format("One task has a newer version (%s) than the current server version (%s)", tasksGreatestMaxVersion.get(), VERSION))
.isTrue();
}
/**
* Verify that tasks are discovered properly and are correctly ordered
*/
@Test
public void testTasksOrder() {
DACConfig dacConfig = DACConfig.newConfig();
Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false);
List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks();
// Get MapR profile variable from Maven surfire plugin
boolean isMapr = Boolean.valueOf(System.getProperty("dremio.mapr.profile"));
// Dremio build contains S3 plugin, UpdateS3CredentialType is included in the list of
// upgrade tasks. The Dremio MapR distribution does not include S3 plugin, therefore UpdateS3CredentialType
// should not be included in the list of upgrade tasks. UpdateDatasetSplitIdTask has a child,
// UpdateS3CredentialType, which should not be included as an upgrade task in the MapR distribution.
// We want to first determine whether UpdateDatasetSplitIdTask and UpdateS3CredentialType are in the list
// of tasks, then test accordingly.
boolean containsS3Task = false;
int s3TaskIndex = 0;
boolean containsDatasetSplitTask = false;
int datasetSplitTaskIndex = 0;
for (int i = 0; i < tasks.size(); i++) {
String taskName = tasks.get(i).getClass().getName();
if ("com.dremio.dac.cmd.upgrade.UpdateS3CredentialType".equals(taskName)) {
containsS3Task = true;
s3TaskIndex = i;
} else if ("com.dremio.dac.cmd.upgrade.UpdateDatasetSplitIdTask".equals(taskName)) {
containsDatasetSplitTask = true;
datasetSplitTaskIndex = i;
}
}
if (isMapr) {
assertThat(containsS3Task).isFalse();
} else {
// Following conditions must be satisfied to ensure correct upgrade tasks ordering.
// 1. All three tasks are in the list of tasks
assertThat(containsDatasetSplitTask).isTrue();
assertThat(containsS3Task).isTrue();
// 2. Both child tasks are successive of UpdateDatasetSplitIdTask
assertThat(s3TaskIndex).isGreaterThan(datasetSplitTaskIndex);
// Remove UpdateS3CredentialType from the list, so vanilla and MapR distribution can be
// tested with the same upgrade task list
tasks.remove(s3TaskIndex);
}
// WHEN creating new UpgradeTask - please add it to the list
// in order to get taskUUID you can run
// testNoDuplicateUUID() test - it will generate one
// tasks will not include TestUpgradeFailORSuccessTask and TestUpgradeTask
// because they don't have default ctor
assertThat(tasks).hasSize(11);
assertThat(tasks.get(0)).isInstanceOf(ReIndexAllStores.class);
assertThat(tasks.get(1)).isInstanceOf(UpdateDatasetSplitIdTask.class);
assertThat(tasks.get(2)).isInstanceOf(DeleteHistoryOfRenamedDatasets.class);
assertThat(tasks.get(3)).isInstanceOf(DeleteHive121BasedInputSplits.class);
assertThat(tasks.get(4)).isInstanceOf(MinimizeJobResultsMetadata.class);
assertThat(tasks.get(5)).isInstanceOf(UpdateExternalReflectionHash.class);
assertThat(tasks.get(6)).isInstanceOf(DeleteSysMaterializationsMetadata.class);
assertThat(tasks.get(7)).isInstanceOf(SetTableauDefaults.class);
assertThat(tasks.get(8)).isInstanceOf(SetExportType.class);
assertThat(tasks.get(9)).isInstanceOf(TopPriorityTask.class);
assertThat(tasks.get(10)).isInstanceOf(LowPriorityTask.class);
}
@Test
public void testTasksWithoutUUID() throws Exception {
DACConfig dacConfig = DACConfig.newConfig();
Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false);
List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks();
tasks.forEach(task -> assertNotNull(
String.format(
"Need to add UUID to task: '%s'. For example: %s", task.getTaskName(), UUID.randomUUID().toString()),
task.getTaskUUID()));
}
@Test
public void testNoDuplicateUUID() {
DACConfig dacConfig = DACConfig.newConfig();
Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false);
List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks();
Set<String> uuidToCount = new HashSet<>();
assertThat(tasks).allSatisfy(task -> assertThat(uuidToCount.add(task.getTaskUUID())).isTrue());
}
@Test
public void testDependenciesResolver() throws Exception {
DACConfig dacConfig = DACConfig.newConfig();
Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false);
List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks();
// Get MapR profile variable from Maven surfire plugin
boolean isMapr = Boolean.valueOf(System.getProperty("dremio.mapr.profile"));
// Dremio build contains S3 plugin, UpdateS3CredentialType is included in the list of
// upgrade tasks. The Dremio MapR distribution does not include S3 plugin, therefore UpdateS3CredentialType
// should not be included in the list of upgrade tasks. UpdateDatasetSplitIdTask has a child,
// UpdateS3CredentialType, which should not be included as an upgrade task in the MapR distribution.
// We want to first determine whether UpdateDatasetSplitIdTask and UpdateS3CredentialType are in the list
// of tasks, then test accordingly.
boolean containsS3Task = false;
int s3TaskIndex = 0;
boolean containsDatasetSplitTask = false;
int datasetSplitTaskIndex = 0;
for (int i = 0; i < tasks.size(); i++) {
String taskName = tasks.get(i).getClass().getName();
if ("com.dremio.dac.cmd.upgrade.UpdateS3CredentialType".equals(taskName)) {
containsS3Task = true;
s3TaskIndex = i;
} else if ("com.dremio.dac.cmd.upgrade.UpdateDatasetSplitIdTask".equals(taskName)) {
containsDatasetSplitTask = true;
datasetSplitTaskIndex = i;
}
}
if (isMapr) {
assertThat(containsS3Task).isFalse();
} else {
// Following conditions must be satisfied to ensure correct upgrade tasks ordering.
// 1. All three tasks are in the list of tasks
assertThat(containsDatasetSplitTask).isTrue();
assertThat(containsS3Task).isTrue();
// 2. Both child tasks are successive of UpdateDatasetSplitIdTask
assertThat(s3TaskIndex).isGreaterThan(datasetSplitTaskIndex);
// Remove UpdateS3CredentialType from the list, so vanilla and MapR distribution can be
// tested with the same upgrade task list
tasks.remove(s3TaskIndex);
}
Collections.shuffle(tasks);
UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver(tasks);
List<UpgradeTask> resolvedTasks = upgradeTaskDependencyResolver.topologicalTasksSort();
// WHEN creating new UpgradeTask - please add it to the list
// in order to get taskUUID you can run
// testNoDuplicateUUID() test - it will generate one
// tasks will not include TestUpgradeFailORSuccessTask and TestUpgradeTask
// because they don't have default ctor
assertThat(resolvedTasks).hasSize(11);
assertThat(resolvedTasks.get(0)).isInstanceOf(ReIndexAllStores.class);
assertThat(resolvedTasks.get(1)).isInstanceOf(UpdateDatasetSplitIdTask.class);
assertThat(resolvedTasks.get(2)).isInstanceOf(DeleteHistoryOfRenamedDatasets.class);
assertThat(resolvedTasks.get(3)).isInstanceOf(DeleteHive121BasedInputSplits.class);
assertThat(resolvedTasks.get(4)).isInstanceOf(MinimizeJobResultsMetadata.class);
assertThat(resolvedTasks.get(5)).isInstanceOf(UpdateExternalReflectionHash.class);
assertThat(resolvedTasks.get(6)).isInstanceOf(DeleteSysMaterializationsMetadata.class);
assertThat(resolvedTasks.get(7)).isInstanceOf(SetTableauDefaults.class);
assertThat(resolvedTasks.get(8)).isInstanceOf(SetExportType.class);
assertThat(resolvedTasks.get(9)).isInstanceOf(TopPriorityTask.class);
assertThat(resolvedTasks.get(10)).isInstanceOf(LowPriorityTask.class);
}
/**
* Tests illegal upgrade from OSS to EE
*/
@Test
public void testIllegalUpgrade() throws Exception {
final ByteString prevEdition = ByteString.copyFrom("OSS".getBytes());
final ConfigurationEntry configurationEntry = new ConfigurationEntry();
configurationEntry.setValue(prevEdition);
final LegacyKVStoreProvider kvStoreProvider =
LegacyKVStoreProviderAdapter.inMemory(CLASSPATH_SCAN_RESULT);
kvStoreProvider.start();
final ConfigurationStore configurationStore = new ConfigurationStore(kvStoreProvider);
configurationStore.put(SupportService.DREMIO_EDITION, configurationEntry);
assertThatThrownBy(() -> new Upgrade(DACConfig.newConfig(), CLASSPATH_SCAN_RESULT, false).validateUpgrade(kvStoreProvider, "EE"))
.isInstanceOf(Exception.class)
.hasMessageContaining("Illegal upgrade from OSS to EE");
}
/**
* Test legal upgrade if prior dremio edition is not specified or editions match
*/
@Test
public void testLegalUpgrade() throws Exception {
final ByteString prevEdition = ByteString.copyFrom("OSS".getBytes());
final ConfigurationEntry configurationEntry = new ConfigurationEntry();
configurationEntry.setValue(prevEdition);
final LegacyKVStoreProvider kvStoreProvider =
LegacyKVStoreProviderAdapter.inMemory(CLASSPATH_SCAN_RESULT);
kvStoreProvider.start();
final ConfigurationStore configurationStore = new ConfigurationStore(kvStoreProvider);
new Upgrade(DACConfig.newConfig(), CLASSPATH_SCAN_RESULT, false).validateUpgrade(kvStoreProvider, "OSS");
configurationStore.put(SupportService.DREMIO_EDITION, configurationEntry);
new Upgrade(DACConfig.newConfig(), CLASSPATH_SCAN_RESULT, false).validateUpgrade(kvStoreProvider, "OSS");
}
}
|
package xdean.share.junit.param;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
@RunWith(Theories.class)
public class ThoryDemo {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(ThoryDemo.class);
System.out.println(result.getRunCount());
System.out.println(result.getFailureCount());
}
@DataPoints
public static final int[] PARAM = { 1, 2, 3 };
static int[] ADD = { 1, 2, 3, 4, 5 };
static int[] SQURE = { 0, 1, 4, 9, 16 };
@Theory
public void testAdd(int i) {
assertEquals(ADD[i], i + 1);
}
@Theory
public void testSqure(int i) {
assertEquals(SQURE[i], i * i);
}
@Test
public void testOther() {
assertEquals(ADD.length, SQURE.length);
}
}
|
package org.ssldev.api.fields;
import org.ssldev.api.consumption.SslBuffer;
public class AdatField39 extends Field <AdatField39 >{
public AdatField39() {
super("Field39",39);
}
@Override
public void consume(SslBuffer buf) {
int len = buf.size();
if(len != 1) throw new IllegalStateException("assumed always length of 1. instead length == " +len);
data = buf.poll();
}
}
|
/**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.maven.util;
import org.apache.maven.settings.Profile;
import org.apache.maven.settings.Repository;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.building.DefaultSettingsBuilderFactory;
import org.apache.maven.settings.building.DefaultSettingsBuildingRequest;
import org.apache.maven.settings.building.SettingsBuilder;
import org.apache.maven.settings.building.SettingsBuildingException;
import org.apache.maven.settings.crypto.DefaultSettingsDecrypter;
import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest;
import org.apache.maven.settings.crypto.SettingsDecrypter;
import org.apache.maven.settings.crypto.SettingsDecryptionResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.aether.repository.*;
import org.sonatype.aether.util.repository.ConservativeAuthenticationSelector;
import org.sonatype.aether.util.repository.DefaultAuthenticationSelector;
import org.sonatype.aether.util.repository.DefaultMirrorSelector;
import org.sonatype.aether.util.repository.DefaultProxySelector;
import java.io.File;
import java.lang.reflect.Field;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class MavenUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(MavenUtils.class);
private static final SettingsBuilder settingsBuilder = new DefaultSettingsBuilderFactory().newInstance();
private static final String USER_SETTINGS_FILE = System.getProperty("user.home") + "/.m2/settings.xml";
private static final String GLOBAL_MAVEN_SETTINGS_FILE = System.getProperty("maven.home") + "/conf/settings.xml";
private static final String GLOBAL_M2_SETTINGS_FILE = System.getenv("M2_HOME") + "/conf/settings.xml";
private static final String USER_SETTINGS_SECURITY_FILE = System.getProperty("user.home") + "/.m2/settings-security.xml";
public static synchronized Settings getSettings() {
Settings settings = null;
DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
File userSettingsFile = safeGetFile(USER_SETTINGS_FILE);
File globalMavenSettingsFile = safeGetFile(GLOBAL_MAVEN_SETTINGS_FILE);
if (globalMavenSettingsFile == null) {
globalMavenSettingsFile = safeGetFile(GLOBAL_M2_SETTINGS_FILE);
}
if (userSettingsFile != null) {
request.setUserSettingsFile(userSettingsFile);
}
if (globalMavenSettingsFile != null) {
request.setGlobalSettingsFile(globalMavenSettingsFile);
}
request.setSystemProperties(System.getProperties());
try {
settings = settingsBuilder.build(request).getEffectiveSettings();
} catch (SettingsBuildingException e) {
LOGGER.warn("Could not process settings.xml: ", e);
}
try {
SettingsDecrypter settingsDecrypter = createSettingsDecrypter();
SettingsDecryptionResult result =
settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(settings));
settings.setServers(result.getServers());
settings.setProxies(result.getProxies());
} catch (Exception ex) {
LOGGER.warn("Failed to decrypt maven settings.", ex);
}
return settings;
}
public static List<Repository> getRepositories() {
List<Repository> repositories = new LinkedList<Repository>();
Settings settings = getSettings();
Set<String> profileNames = new LinkedHashSet<String>();
profileNames.addAll(settings.getActiveProfiles());
for (Profile p : settings.getProfiles()) {
if (p.getActivation() != null && p.getActivation().isActiveByDefault()) {
profileNames.add(p.getId());
}
}
for (String profileName : profileNames) {
Object obj = settings.getProfilesAsMap().get(profileName);
if (Profile.class.isAssignableFrom(obj.getClass())) {
Profile p = (Profile) obj;
for (Repository repository : p.getRepositories()) {
repositories.add(repository);
}
}
}
return repositories;
}
/**
* Returns a list of {@link RemoteRepository} as configured in the maven settings.xml
*
* @return
*/
public static List<RemoteRepository> getRemoteRepositories() {
List<RemoteRepository> repositories = new LinkedList<RemoteRepository>();
for (Repository repository : getRepositories()) {
RemoteRepository remote = new RemoteRepository();
remote.setId(repository.getId());
remote.setUrl(repository.getUrl());
remote.setContentType("default");
if (repository.getSnapshots().isEnabled()) {
RepositoryPolicy repositoryPolicy = new RepositoryPolicy();
if (repository.getSnapshots() != null) {
remote.setPolicy(true, convertMavenRepositoryPolicy(repository.getSnapshots()));
}
}
if (repository.getReleases() != null) {
remote.setPolicy(false, convertMavenRepositoryPolicy(repository.getReleases()));
}
Server server = getSettings().getServer(repository.getId());
if (server != null) {
// Need to decode username/password because it may contain encoded characters (http://www.w3schools.com/tags/ref_urlencode.asp)
// A common encoding is to provide a username as an email address like user%40domain.org
String decodedUsername = decode(server.getUsername());
Authentication authentication = new Authentication(decodedUsername, server.getPassword(), server.getPrivateKey(), server.getPassphrase());
remote.setAuthentication(authentication);
}
repositories.add(remote);
}
return repositories;
}
/**
* Returns the default {@link ProxySelector} as configured in the maven settings.xml
*
* @return
*/
public static ProxySelector getProxySelector() {
DefaultProxySelector selector = new DefaultProxySelector();
Settings settings = getSettings();
for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) {
Authentication auth = new Authentication(proxy.getUsername(), proxy.getPassword());
org.sonatype.aether.repository.Proxy p = new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth);
selector.add(p, proxy.getNonProxyHosts());
}
return selector;
}
/**
* Returns the default {@link ProxySelector} as configured in the maven settings.xml
*
* @return
*/
public static ProxySelector getProxySelector(String protocol, String host, int port, String nonProxyHosts, String username, String password) {
DefaultProxySelector selector = new DefaultProxySelector();
Settings settings = getSettings();
if (protocol != null && !protocol.isEmpty() && host != null && !host.isEmpty() && port > 0) {
Authentication auth = new Authentication(username, password);
org.sonatype.aether.repository.Proxy p = new Proxy(protocol, host, port, auth);
selector.add(p, nonProxyHosts);
}
for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) {
Authentication auth = new Authentication(proxy.getUsername(), proxy.getPassword());
org.sonatype.aether.repository.Proxy p = new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth);
selector.add(p, proxy.getNonProxyHosts());
}
return selector;
}
/**
* Returns the default {@link MirrorSelector} as configured in the maven settings.xml
*
* @return
*/
public static MirrorSelector getMirrorSelector() {
DefaultMirrorSelector selector = new DefaultMirrorSelector();
Settings settings = getSettings();
for (org.apache.maven.settings.Mirror mirror : settings.getMirrors()) {
selector.add(String.valueOf(mirror.getId()), mirror.getUrl(), mirror.getLayout(), false,
mirror.getMirrorOf(), mirror.getMirrorOfLayouts());
}
return selector;
}
/**
* Returns the default {@link Authentication} as configured in the maven settings.xml
*
* @return
*/
public static AuthenticationSelector getAuthSelector() {
DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector();
Settings settings = getSettings();
for (Server server : settings.getServers()) {
// Need to decode username/password because it may contain encoded characters (http://www.w3schools.com/tags/ref_urlencode.asp)
// A common encoding is to provide a username as an email address like user%40domain.org
String decodedUsername = decode(server.getUsername());
Authentication auth = new Authentication(decodedUsername, server.getPassword(), server.getPrivateKey(), server.getPassphrase());
selector.add(server.getId(), auth);
}
return new ConservativeAuthenticationSelector(selector);
}
/**
* Decodes the specified (portion of a) URL. <strong>Note:</strong> This decoder assumes that ISO-8859-1 is used to
* convert URL-encoded octets to characters.
*
* @param url The URL to decode, may be <code>null</code>.
* @return The decoded URL or <code>null</code> if the input was <code>null</code>.
*/
private static String decode(String url) {
if (url == null) {
return null;
}
StringBuilder decoded = new StringBuilder();
int pos = 0;
while (pos < url.length()) {
char ch = url.charAt(pos);
if (ch == '%') {
if (pos + 2 < url.length()) {
String hexStr = url.substring(pos + 1, pos + 3);
char hexChar = (char) Integer.parseInt(hexStr, 16);
decoded.append(hexChar);
pos += 3;
} else {
throw new IllegalStateException("'%' escape must be followed by two hex digits");
}
} else {
decoded.append(ch);
pos++;
}
}
return decoded.toString();
}
private static SettingsDecrypter createSettingsDecrypter() {
MavenSecDispatcher secDispatcher = new MavenSecDispatcher();
DefaultSettingsDecrypter decrypter = new DefaultSettingsDecrypter();
try {
Field field = decrypter.getClass().getDeclaredField("securityDispatcher");
field.setAccessible(true);
field.set(decrypter, secDispatcher);
} catch (Exception e) {
throw new IllegalStateException(e);
}
return decrypter;
}
private static RepositoryPolicy convertMavenRepositoryPolicy(org.apache.maven.settings.RepositoryPolicy repositoryPolicy) {
RepositoryPolicy policy = new RepositoryPolicy();
if (repositoryPolicy != null && repositoryPolicy.getChecksumPolicy() != null) {
policy.setChecksumPolicy(repositoryPolicy.getChecksumPolicy());
}
policy.setEnabled(repositoryPolicy.isEnabled());
policy.setUpdatePolicy(repositoryPolicy.getUpdatePolicy());
return policy;
}
/**
* Checks if path corresponds to an existing {@link File} and returns it.
*
* @param filePath The path to the file.
* @return The file or null, if not found, not readable or not a file (e.g. directory).
*/
private static File safeGetFile(final String filePath) {
if (filePath != null) {
File file = new File(filePath);
if (file.exists() && file.canRead() && file.isFile()) {
return file;
}
}
return null;
}
}
|
package com.my.blog.website.controller.admin;
import com.github.pagehelper.PageInfo;
import com.my.blog.website.cache.StringCache;
import com.my.blog.website.constant.WebConst;
import com.my.blog.website.controller.BaseController;
import com.my.blog.website.dto.LogActions;
import com.my.blog.website.dto.Types;
import com.my.blog.website.exception.TipException;
import com.my.blog.website.model.Bo.RestResponseBo;
import com.my.blog.website.model.Vo.ContentVo;
import com.my.blog.website.model.Vo.ContentVoExample;
import com.my.blog.website.model.Vo.UserVo;
import com.my.blog.website.service.IContentService;
import com.my.blog.website.service.ILogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import xyz.cheungz.httphelper.utils.SerializationUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* Created by 13 on 2021/2/21.
*/
@Controller()
@RequestMapping("admin/page")
public class PageController extends BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(PageController.class);
@Resource
private IContentService contentsService;
@Resource
private ILogService logService;
@Resource
private StringCache redisStringCache;
@GetMapping(value = "")
public String index(HttpServletRequest request) {
ContentVoExample contentVoExample = new ContentVoExample();
contentVoExample.setOrderByClause("created desc");
contentVoExample.createCriteria().andTypeEqualTo(Types.PAGE.getType());
PageInfo<ContentVo> contentsPaginator = contentsService.getArticlesWithpage(contentVoExample, 1, WebConst.MAX_POSTS);
request.setAttribute("articles", contentsPaginator);
return "admin/page_list";
}
@GetMapping(value = "new")
public String newPage(HttpServletRequest request) {
return "admin/page_edit";
}
@GetMapping(value = "/{cid}")
public String editPage(@PathVariable String cid, HttpServletRequest request) {
ContentVo contents = contentsService.getContents(cid);
request.setAttribute("contents", contents);
return "admin/page_edit";
}
@PostMapping(value = "publish")
@ResponseBody
@Transactional(rollbackFor = TipException.class)
public RestResponseBo publishPage(@RequestParam String title, @RequestParam String content,
@RequestParam String status, @RequestParam String slug,
@RequestParam(required = false) Integer allowComment, @RequestParam(required = false) Integer allowPing, HttpServletRequest request) {
UserVo users = this.user(request);
ContentVo contents = new ContentVo();
contents.setTitle(title);
contents.setContent(content);
contents.setStatus(status);
contents.setSlug(slug);
contents.setType(Types.PAGE.getType());
if (null != allowComment) {
contents.setAllowComment(allowComment == 1);
}
if (null != allowPing) {
contents.setAllowPing(allowPing == 1);
}
contents.setAuthorId(users.getUid());
try {
contentsService.publish(contents);
} catch (Exception e) {
String msg = "页面发布失败";
if (e instanceof TipException) {
msg = e.getMessage();
} else {
LOGGER.error(msg, e);
}
return RestResponseBo.fail(msg);
}
return RestResponseBo.ok();
}
@PostMapping(value = "modify")
@ResponseBody
@Transactional(rollbackFor = TipException.class)
public RestResponseBo modifyArticle(@RequestParam Integer cid, @RequestParam String title,
@RequestParam String content,
@RequestParam String status, @RequestParam String slug,
@RequestParam(required = false) Integer allowComment, @RequestParam(required = false) Integer allowPing, HttpServletRequest request) {
UserVo users = this.user(request);
ContentVo contents = new ContentVo();
contents.setCid(cid);
contents.setTitle(title);
contents.setContent(content);
contents.setStatus(status);
contents.setSlug(slug);
contents.setType(Types.PAGE.getType());
if (null != allowComment) {
contents.setAllowComment(allowComment == 1);
}
if (null != allowPing) {
contents.setAllowPing(allowPing == 1);
}
contents.setAuthorId(users.getUid());
try {
int i = contentsService.updateArticle(contents);
if (i == 1){
redisStringCache.updateCache(String.valueOf(contents.getCid()), SerializationUtil.obj2String(contents));
}
} catch (Exception e) {
String msg = "页面编辑失败";
if (e instanceof TipException) {
msg = e.getMessage();
} else {
LOGGER.error(msg, e);
}
return RestResponseBo.fail(msg);
}
return RestResponseBo.ok();
}
@RequestMapping(value = "delete")
@ResponseBody
@Transactional(rollbackFor = TipException.class)
public RestResponseBo delete(@RequestParam int cid, HttpServletRequest request) {
try {
contentsService.deleteByCid(cid);
logService.insertLog(LogActions.DEL_PAGE.getAction(), cid + "", request.getRemoteAddr(), this.getUid(request));
} catch (Exception e) {
String msg = "页面删除失败";
if (e instanceof TipException) {
msg = e.getMessage();
} else {
LOGGER.error(msg, e);
}
return RestResponseBo.fail(msg);
}
return RestResponseBo.ok();
}
}
|
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.authy.v1.service.entity.factor;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.MoreObjects;
import com.twilio.base.Resource;
import com.twilio.converter.DateConverter;
import com.twilio.converter.Promoter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import org.joda.time.DateTime;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Map;
import java.util.Objects;
/**
* PLEASE NOTE that this class contains preview products that are subject to
* change. Use them with caution. If you currently do not have developer preview
* access, please contact help@twilio.com.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Challenge extends Resource {
private static final long serialVersionUID = 149233025221094L;
public enum ChallengeStatuses {
PENDING("pending"),
EXPIRED("expired"),
APPROVED("approved"),
DENIED("denied");
private final String value;
private ChallengeStatuses(final String value) {
this.value = value;
}
public String toString() {
return value;
}
/**
* Generate a ChallengeStatuses from a string.
* @param value string value
* @return generated ChallengeStatuses
*/
@JsonCreator
public static ChallengeStatuses forValue(final String value) {
return Promoter.enumFromString(value, ChallengeStatuses.values());
}
}
public enum ChallengeReasons {
NONE("none"),
NOT_NEEDED("not_needed"),
NOT_REQUESTED("not_requested");
private final String value;
private ChallengeReasons(final String value) {
this.value = value;
}
public String toString() {
return value;
}
/**
* Generate a ChallengeReasons from a string.
* @param value string value
* @return generated ChallengeReasons
*/
@JsonCreator
public static ChallengeReasons forValue(final String value) {
return Promoter.enumFromString(value, ChallengeReasons.values());
}
}
public enum FactorTypes {
APP_PUSH("app-push"),
SMS("sms"),
TOTP("totp");
private final String value;
private FactorTypes(final String value) {
this.value = value;
}
public String toString() {
return value;
}
/**
* Generate a FactorTypes from a string.
* @param value string value
* @return generated FactorTypes
*/
@JsonCreator
public static FactorTypes forValue(final String value) {
return Promoter.enumFromString(value, FactorTypes.values());
}
}
public enum FactorStrengths {
UNKNOWN("unknown"),
VERY_LOW("very_low"),
LOW("low"),
MEDIUM("medium"),
HIGH("high"),
VERY_HIGH("very_high");
private final String value;
private FactorStrengths(final String value) {
this.value = value;
}
public String toString() {
return value;
}
/**
* Generate a FactorStrengths from a string.
* @param value string value
* @return generated FactorStrengths
*/
@JsonCreator
public static FactorStrengths forValue(final String value) {
return Promoter.enumFromString(value, FactorStrengths.values());
}
}
/**
* Create a ChallengeCreator to execute create.
*
* @param pathServiceSid Service Sid.
* @param pathIdentity Unique identity of the Entity
* @param pathFactorSid Factor Sid.
* @return ChallengeCreator capable of executing the create
*/
public static ChallengeCreator creator(final String pathServiceSid,
final String pathIdentity,
final String pathFactorSid) {
return new ChallengeCreator(pathServiceSid, pathIdentity, pathFactorSid);
}
/**
* Create a ChallengeDeleter to execute delete.
*
* @param pathServiceSid Service Sid.
* @param pathIdentity Unique identity of the Entity
* @param pathFactorSid Factor Sid.
* @param pathSid A string that uniquely identifies this Challenge.
* @return ChallengeDeleter capable of executing the delete
*/
public static ChallengeDeleter deleter(final String pathServiceSid,
final String pathIdentity,
final String pathFactorSid,
final String pathSid) {
return new ChallengeDeleter(pathServiceSid, pathIdentity, pathFactorSid, pathSid);
}
/**
* Create a ChallengeFetcher to execute fetch.
*
* @param pathServiceSid Service Sid.
* @param pathIdentity Unique identity of the Entity
* @param pathFactorSid Factor Sid.
* @param pathSid A string that uniquely identifies this Challenge, or `latest`.
* @return ChallengeFetcher capable of executing the fetch
*/
public static ChallengeFetcher fetcher(final String pathServiceSid,
final String pathIdentity,
final String pathFactorSid,
final String pathSid) {
return new ChallengeFetcher(pathServiceSid, pathIdentity, pathFactorSid, pathSid);
}
/**
* Create a ChallengeUpdater to execute update.
*
* @param pathServiceSid Service Sid.
* @param pathIdentity Unique identity of the Entity
* @param pathFactorSid Factor Sid.
* @param pathSid A string that uniquely identifies this Challenge, or `latest`.
* @return ChallengeUpdater capable of executing the update
*/
public static ChallengeUpdater updater(final String pathServiceSid,
final String pathIdentity,
final String pathFactorSid,
final String pathSid) {
return new ChallengeUpdater(pathServiceSid, pathIdentity, pathFactorSid, pathSid);
}
/**
* Converts a JSON String into a Challenge object using the provided
* ObjectMapper.
*
* @param json Raw JSON String
* @param objectMapper Jackson ObjectMapper
* @return Challenge object represented by the provided JSON
*/
public static Challenge fromJson(final String json, final ObjectMapper objectMapper) {
// Convert all checked exceptions to Runtime
try {
return objectMapper.readValue(json, Challenge.class);
} catch (final JsonMappingException | JsonParseException e) {
throw new ApiException(e.getMessage(), e);
} catch (final IOException e) {
throw new ApiConnectionException(e.getMessage(), e);
}
}
/**
* Converts a JSON InputStream into a Challenge object using the provided
* ObjectMapper.
*
* @param json Raw JSON InputStream
* @param objectMapper Jackson ObjectMapper
* @return Challenge object represented by the provided JSON
*/
public static Challenge fromJson(final InputStream json, final ObjectMapper objectMapper) {
// Convert all checked exceptions to Runtime
try {
return objectMapper.readValue(json, Challenge.class);
} catch (final JsonMappingException | JsonParseException e) {
throw new ApiException(e.getMessage(), e);
} catch (final IOException e) {
throw new ApiConnectionException(e.getMessage(), e);
}
}
private final String sid;
private final String accountSid;
private final String serviceSid;
private final String entitySid;
private final String identity;
private final String factorSid;
private final DateTime dateCreated;
private final DateTime dateUpdated;
private final DateTime dateResponded;
private final DateTime expirationDate;
private final Challenge.ChallengeStatuses status;
private final Challenge.ChallengeReasons respondedReason;
private final String details;
private final String hiddenDetails;
private final Challenge.FactorTypes factorType;
private final Challenge.FactorStrengths factorStrength;
private final URI url;
@JsonCreator
private Challenge(@JsonProperty("sid")
final String sid,
@JsonProperty("account_sid")
final String accountSid,
@JsonProperty("service_sid")
final String serviceSid,
@JsonProperty("entity_sid")
final String entitySid,
@JsonProperty("identity")
final String identity,
@JsonProperty("factor_sid")
final String factorSid,
@JsonProperty("date_created")
final String dateCreated,
@JsonProperty("date_updated")
final String dateUpdated,
@JsonProperty("date_responded")
final String dateResponded,
@JsonProperty("expiration_date")
final String expirationDate,
@JsonProperty("status")
final Challenge.ChallengeStatuses status,
@JsonProperty("responded_reason")
final Challenge.ChallengeReasons respondedReason,
@JsonProperty("details")
final String details,
@JsonProperty("hidden_details")
final String hiddenDetails,
@JsonProperty("factor_type")
final Challenge.FactorTypes factorType,
@JsonProperty("factor_strength")
final Challenge.FactorStrengths factorStrength,
@JsonProperty("url")
final URI url) {
this.sid = sid;
this.accountSid = accountSid;
this.serviceSid = serviceSid;
this.entitySid = entitySid;
this.identity = identity;
this.factorSid = factorSid;
this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated);
this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated);
this.dateResponded = DateConverter.iso8601DateTimeFromString(dateResponded);
this.expirationDate = DateConverter.iso8601DateTimeFromString(expirationDate);
this.status = status;
this.respondedReason = respondedReason;
this.details = details;
this.hiddenDetails = hiddenDetails;
this.factorType = factorType;
this.factorStrength = factorStrength;
this.url = url;
}
/**
* Returns The A string that uniquely identifies this Challenge..
*
* @return A string that uniquely identifies this Challenge.
*/
public final String getSid() {
return this.sid;
}
/**
* Returns The Account Sid..
*
* @return Account Sid.
*/
public final String getAccountSid() {
return this.accountSid;
}
/**
* Returns The Service Sid..
*
* @return Service Sid.
*/
public final String getServiceSid() {
return this.serviceSid;
}
/**
* Returns The Entity Sid..
*
* @return Entity Sid.
*/
public final String getEntitySid() {
return this.entitySid;
}
/**
* Returns The Unique identity of the Entity.
*
* @return Unique identity of the Entity
*/
public final String getIdentity() {
return this.identity;
}
/**
* Returns The Factor Sid..
*
* @return Factor Sid.
*/
public final String getFactorSid() {
return this.factorSid;
}
/**
* Returns The The date this Challenge was created.
*
* @return The date this Challenge was created
*/
public final DateTime getDateCreated() {
return this.dateCreated;
}
/**
* Returns The The date this Challenge was updated.
*
* @return The date this Challenge was updated
*/
public final DateTime getDateUpdated() {
return this.dateUpdated;
}
/**
* Returns The The date this Challenge was responded.
*
* @return The date this Challenge was responded
*/
public final DateTime getDateResponded() {
return this.dateResponded;
}
/**
* Returns The The date this Challenge is expired.
*
* @return The date this Challenge is expired
*/
public final DateTime getExpirationDate() {
return this.expirationDate;
}
/**
* Returns The The Status of this Challenge.
*
* @return The Status of this Challenge
*/
public final Challenge.ChallengeStatuses getStatus() {
return this.status;
}
/**
* Returns The The Reason of this Challenge `status`.
*
* @return The Reason of this Challenge `status`
*/
public final Challenge.ChallengeReasons getRespondedReason() {
return this.respondedReason;
}
/**
* Returns The Public details provided to contextualize the Challenge.
*
* @return Public details provided to contextualize the Challenge
*/
public final String getDetails() {
return this.details;
}
/**
* Returns The Hidden details provided to contextualize the Challenge.
*
* @return Hidden details provided to contextualize the Challenge
*/
public final String getHiddenDetails() {
return this.hiddenDetails;
}
/**
* Returns The The Factor Type of this Challenge.
*
* @return The Factor Type of this Challenge
*/
public final Challenge.FactorTypes getFactorType() {
return this.factorType;
}
/**
* Returns The The Factor Strength of this Challenge.
*
* @return The Factor Strength of this Challenge
*/
public final Challenge.FactorStrengths getFactorStrength() {
return this.factorStrength;
}
/**
* Returns The The URL of this resource..
*
* @return The URL of this resource.
*/
public final URI getUrl() {
return this.url;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Challenge other = (Challenge) o;
return Objects.equals(sid, other.sid) &&
Objects.equals(accountSid, other.accountSid) &&
Objects.equals(serviceSid, other.serviceSid) &&
Objects.equals(entitySid, other.entitySid) &&
Objects.equals(identity, other.identity) &&
Objects.equals(factorSid, other.factorSid) &&
Objects.equals(dateCreated, other.dateCreated) &&
Objects.equals(dateUpdated, other.dateUpdated) &&
Objects.equals(dateResponded, other.dateResponded) &&
Objects.equals(expirationDate, other.expirationDate) &&
Objects.equals(status, other.status) &&
Objects.equals(respondedReason, other.respondedReason) &&
Objects.equals(details, other.details) &&
Objects.equals(hiddenDetails, other.hiddenDetails) &&
Objects.equals(factorType, other.factorType) &&
Objects.equals(factorStrength, other.factorStrength) &&
Objects.equals(url, other.url);
}
@Override
public int hashCode() {
return Objects.hash(sid,
accountSid,
serviceSid,
entitySid,
identity,
factorSid,
dateCreated,
dateUpdated,
dateResponded,
expirationDate,
status,
respondedReason,
details,
hiddenDetails,
factorType,
factorStrength,
url);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("sid", sid)
.add("accountSid", accountSid)
.add("serviceSid", serviceSid)
.add("entitySid", entitySid)
.add("identity", identity)
.add("factorSid", factorSid)
.add("dateCreated", dateCreated)
.add("dateUpdated", dateUpdated)
.add("dateResponded", dateResponded)
.add("expirationDate", expirationDate)
.add("status", status)
.add("respondedReason", respondedReason)
.add("details", details)
.add("hiddenDetails", hiddenDetails)
.add("factorType", factorType)
.add("factorStrength", factorStrength)
.add("url", url)
.toString();
}
}
|
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree.
*/
package org.fcrepo.auth.common;
import static org.slf4j.LoggerFactory.getLogger;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.Principal;
import java.util.HashSet;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
/**
* This abstract class implements the Filter interface to add principals
* to the session so that Shiro can evaluate the principals.
*
* The getPrincipals method is left as the responsibility of the classes
* that will be extending this abstract class.
*
* @author Mohamed Abdul Rasheed
* @see PrincipalProvider
*/
abstract class AbstractPrincipalProvider implements PrincipalProvider {
private static final Logger log = getLogger(AbstractPrincipalProvider.class);
private static final String REALM_NAME = "org.fcrepo.auth.webac.WebACAuthorizingRealm";
@Override
public void init(final FilterConfig filterConfig) {
// this method intentionally left empty
}
@SuppressWarnings("unchecked")
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest hsRequest = (HttpServletRequest) request;
final Subject currentUser = SecurityUtils.getSubject();
PrincipalCollection principals = currentUser.getPrincipals();
final Set<Principal> newPrincipals = getPrincipals(hsRequest);
if (newPrincipals.size() > 0) {
final Set<Principal> currentPrincipals;
if (principals == null || principals.asList().isEmpty()) {
log.debug("Shiro Principal object is not found!");
currentPrincipals = newPrincipals;
} else {
currentPrincipals = new HashSet<>(principals.asSet());
log.debug("Number of Principals already in session object: {}", currentPrincipals.size());
currentPrincipals.addAll(newPrincipals);
}
log.debug("Number of Principals after processing the current request: {}", currentPrincipals.size());
principals = new SimplePrincipalCollection(currentPrincipals, REALM_NAME);
currentUser.runAs(principals);
} else {
log.debug("New Principals not found in the request!");
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
// this method intentionally left empty
}
}
|
package org.openstack4j.model.senlin;
import org.openstack4j.model.ResourceEntity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* This interface describes the getter-methods (and thus components) of a Cluster.
* All getters map to the possible return values of
* <code> GET /v1/clusters/{cluster_id}</code>
*
* @see http://developer.openstack.org/api-ref-clustering-v1.html
*
* @author lion
*
*/
public interface Cluster extends ResourceEntity {
/**
* Returns the created at time of the cluster
*
* @return the created at time of the cluster
*/
Date getCreatedAt();
/**
* Returns the data of the cluster
*
* @return the data of the cluster
*/
Map<String, Object> getData();
/**
* Returns the desired capacity of the cluster
*
* @return the desired capacity of the cluster
*/
Integer getDesiredCapacity();
/**
* Returns the domain of the cluster
*
* @return the domain of the cluster
*/
String getDomain();
/**
* Returns the init at time of the cluster
*
* @return the init at time of the cluster
*/
Date getInitAt();
/**
* Returns the max size of the cluster
*
* @return the max size time of the cluster
*/
Integer getMaxSize();
/**
* Returns the metadata of the cluster
*
* @return the metadata of the cluster
*/
Map<String, Object> getMetadata();
/**
* Returns the min size of the cluster
*
* @return the min size of the cluster
*/
Integer getMinSize();
/**
* Returns the nodes of the cluster
*
* @return the nodes of the cluster
*/
List<String> getNodes();
/**
* Returns the policies of the cluster
*
* @return the policies of the cluster
*/
List<String> getPolicies();
/**
* Returns the profile id of the cluster
*
* @return the profile id of the cluster
*/
String getProfileID();
/**
* Returns the profile name of the cluster
*
* @return the profile name of the cluster
*/
String getProfileName();
/**
* Returns the project of the cluster
*
* @return the project of the cluster
*/
String getProject();
/**
* Returns the status of the cluster
*
* @return the status of the cluster
*/
ClusterStatus getStatus();
/**
* Returns the status reason of the cluster
*
* @return the status reason of the cluster
*/
String getStatusReason();
/**
* Returns the timeout value of the cluster
*
* @return the timeout value of the cluster
*/
Integer getTimeout();
/**
* Returns the updated at time of the cluster
*
* @return the updated at time of the cluster
*/
Date getUpdatedAt();
/**
* Returns the user of the cluster
*
* @return the user of the cluster
*/
String getUser();
}
|
package home.smart.fly.animations.ui.activity;
import android.content.Context;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import home.smart.fly.animations.R;
import java8.util.Optional;
public class OptionalActivity extends AppCompatActivity implements View.OnClickListener {
private Context mContext;
private static final String TAG = "OptionalActivity";
private List<Student> mStudents = Arrays.asList(
new Student("mike", 11),
new Student("mike1", 111),
new Student("mike2", 112),
new Student("mike3", 131),
new Student("mike4", 151),
new Student("mike5", 161),
new Student("mike6", 181),
new Student("mike7", 181),
new Student("mike8", 181)
);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_optional);
mContext = this;
findViewById(R.id.nullValue).setOnClickListener(this);
findViewById(R.id.notNullValue).setOnClickListener(this);
findViewById(R.id.elseUse).setOnClickListener(this);
findViewById(R.id.stream).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.nullValue:
// Optional.ofNullable 允许接收 null ,
// ifPresentOrElse 当ofNullable 返回非空时,执行第一个 action ,否则执行第二个 action
Student mStudent = null;
Optional.ofNullable(mStudent).ifPresentOrElse(student -> Toast.makeText(mContext,
student.name + " " + student.age, Toast.LENGTH_SHORT).show(),
() -> Toast.makeText(mContext, "it is null", Toast.LENGTH_SHORT).show());
break;
case R.id.notNullValue:
// Optional.of 不允许接收 null,遇到 null 会直接 throw NullPointerException
// ifPresent of 返回为非空时,执行 ifPresent 中的 action ,否则什么都不做
mStudent = new Student("mike", 18);
Optional.of(mStudent).ifPresent(student -> Toast.makeText(mContext,
student.name + " " + student.age, Toast.LENGTH_SHORT).show());
break;
case R.id.elseUse:
elseUse();
break;
case R.id.stream:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
streamPlay();
}
break;
default:
break;
}
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void streamPlay() {
List<String> names = mStudents
.stream()
.map(student -> student.name)
.collect(Collectors.toList());
List<Integer> ages = mStudents
.stream()
.map(student -> student.age)
.collect(Collectors.toList());
Optional.ofNullable(names)
.ifPresent(strings -> strings.forEach(s -> Log.e(TAG, "accept: s==" + s)));
Optional.ofNullable(ages)
.ifPresent(integers -> integers.forEach(integer -> Log.e(TAG, "streamPlay: integer==" + integer)));
}
private void elseUse() {
Student student = new Student("lucy", 18);
// 创建一个 为 Null 的 Optional
Optional optional = Optional.empty();
if (optional.isEmpty()) {
System.out.println("optional is empty");
}
Optional<Student> studentOptional = Optional.ofNullable(student);
// isPresent() 可以判断当前 Optional 是否为 Null
if (studentOptional.isPresent()) {
System.out.println("student is present");
}
}
private class Student {
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
}
|
/**
* Copyright 2009-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.apache.ibatis.reflection.property;
import java.util.Locale;
import org.apache.ibatis.reflection.ReflectionException;
/**
* 属性名相关的工具类方法
* @author Clinton Begin
*/
public final class PropertyNamer {
private PropertyNamer() {
// Prevent Instantiation of Static Class
}
/**
* 提供方法名, 获得对应的属性名
*
* @param name 方法名
* @return 属性名
*/
public static String methodToProperty(String name) {
if (name.startsWith("is")) {
name = name.substring(2);
} else if (name.startsWith("get") || name.startsWith("set")) {
name = name.substring(3);
} else {
throw new ReflectionException("Error parsing property name '" + name + "'. Didn't start with 'is', 'get' or 'set'.");
}
if (name.length() == 1 || (name.length() > 1 && !Character.isUpperCase(name.charAt(1)))) {
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
}
return name;
}
/**
* 判断是否为 is, get, set 方法
* @param name
* @return
*/
public static boolean isProperty(String name) {
return isGetter(name) || isSetter(name);
}
public static boolean isGetter(String name) {
return (name.startsWith("get") && name.length() > 3) || (name.startsWith("is") && name.length() > 2);
}
public static boolean isSetter(String name) {
return name.startsWith("set") && name.length() > 3;
}
}
|
/*
* Copyright 2016-2021 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.backup;
import javax.annotation.Generated;
import com.amazonaws.services.backup.model.*;
import com.amazonaws.client.AwsAsyncClientParams;
import com.amazonaws.annotation.ThreadSafe;
import java.util.concurrent.ExecutorService;
/**
* Client for accessing AWS Backup asynchronously. Each asynchronous method will return a Java Future object
* representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive
* notification when an asynchronous operation completes.
* <p>
* <fullname>AWS Backup</fullname>
* <p>
* AWS Backup is a unified backup service designed to protect AWS services and their associated data. AWS Backup
* simplifies the creation, migration, restoration, and deletion of backups, while also providing reporting and
* auditing.
* </p>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AWSBackupAsyncClient extends AWSBackupClient implements AWSBackupAsync {
private static final int DEFAULT_THREAD_POOL_SIZE = 50;
private final java.util.concurrent.ExecutorService executorService;
public static AWSBackupAsyncClientBuilder asyncBuilder() {
return AWSBackupAsyncClientBuilder.standard();
}
/**
* Constructs a new asynchronous client to invoke service methods on AWS Backup using the specified parameters.
*
* @param asyncClientParams
* Object providing client parameters.
*/
AWSBackupAsyncClient(AwsAsyncClientParams asyncClientParams) {
this(asyncClientParams, false);
}
/**
* Constructs a new asynchronous client to invoke service methods on AWS Backup using the specified parameters.
*
* @param asyncClientParams
* Object providing client parameters.
* @param endpointDiscoveryEnabled
* true will enable endpoint discovery if the service supports it.
*/
AWSBackupAsyncClient(AwsAsyncClientParams asyncClientParams, boolean endpointDiscoveryEnabled) {
super(asyncClientParams, endpointDiscoveryEnabled);
this.executorService = asyncClientParams.getExecutor();
}
/**
* Returns the executor service used by this client to execute async requests.
*
* @return The executor service used by this client to execute async requests.
*/
public ExecutorService getExecutorService() {
return executorService;
}
@Override
public java.util.concurrent.Future<CreateBackupPlanResult> createBackupPlanAsync(CreateBackupPlanRequest request) {
return createBackupPlanAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateBackupPlanResult> createBackupPlanAsync(final CreateBackupPlanRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateBackupPlanRequest, CreateBackupPlanResult> asyncHandler) {
final CreateBackupPlanRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateBackupPlanResult>() {
@Override
public CreateBackupPlanResult call() throws Exception {
CreateBackupPlanResult result = null;
try {
result = executeCreateBackupPlan(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateBackupSelectionResult> createBackupSelectionAsync(CreateBackupSelectionRequest request) {
return createBackupSelectionAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateBackupSelectionResult> createBackupSelectionAsync(final CreateBackupSelectionRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateBackupSelectionRequest, CreateBackupSelectionResult> asyncHandler) {
final CreateBackupSelectionRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateBackupSelectionResult>() {
@Override
public CreateBackupSelectionResult call() throws Exception {
CreateBackupSelectionResult result = null;
try {
result = executeCreateBackupSelection(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateBackupVaultResult> createBackupVaultAsync(CreateBackupVaultRequest request) {
return createBackupVaultAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateBackupVaultResult> createBackupVaultAsync(final CreateBackupVaultRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateBackupVaultRequest, CreateBackupVaultResult> asyncHandler) {
final CreateBackupVaultRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateBackupVaultResult>() {
@Override
public CreateBackupVaultResult call() throws Exception {
CreateBackupVaultResult result = null;
try {
result = executeCreateBackupVault(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteBackupPlanResult> deleteBackupPlanAsync(DeleteBackupPlanRequest request) {
return deleteBackupPlanAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteBackupPlanResult> deleteBackupPlanAsync(final DeleteBackupPlanRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteBackupPlanRequest, DeleteBackupPlanResult> asyncHandler) {
final DeleteBackupPlanRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteBackupPlanResult>() {
@Override
public DeleteBackupPlanResult call() throws Exception {
DeleteBackupPlanResult result = null;
try {
result = executeDeleteBackupPlan(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteBackupSelectionResult> deleteBackupSelectionAsync(DeleteBackupSelectionRequest request) {
return deleteBackupSelectionAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteBackupSelectionResult> deleteBackupSelectionAsync(final DeleteBackupSelectionRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteBackupSelectionRequest, DeleteBackupSelectionResult> asyncHandler) {
final DeleteBackupSelectionRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteBackupSelectionResult>() {
@Override
public DeleteBackupSelectionResult call() throws Exception {
DeleteBackupSelectionResult result = null;
try {
result = executeDeleteBackupSelection(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteBackupVaultResult> deleteBackupVaultAsync(DeleteBackupVaultRequest request) {
return deleteBackupVaultAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteBackupVaultResult> deleteBackupVaultAsync(final DeleteBackupVaultRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteBackupVaultRequest, DeleteBackupVaultResult> asyncHandler) {
final DeleteBackupVaultRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteBackupVaultResult>() {
@Override
public DeleteBackupVaultResult call() throws Exception {
DeleteBackupVaultResult result = null;
try {
result = executeDeleteBackupVault(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteBackupVaultAccessPolicyResult> deleteBackupVaultAccessPolicyAsync(DeleteBackupVaultAccessPolicyRequest request) {
return deleteBackupVaultAccessPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteBackupVaultAccessPolicyResult> deleteBackupVaultAccessPolicyAsync(
final DeleteBackupVaultAccessPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteBackupVaultAccessPolicyRequest, DeleteBackupVaultAccessPolicyResult> asyncHandler) {
final DeleteBackupVaultAccessPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteBackupVaultAccessPolicyResult>() {
@Override
public DeleteBackupVaultAccessPolicyResult call() throws Exception {
DeleteBackupVaultAccessPolicyResult result = null;
try {
result = executeDeleteBackupVaultAccessPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteBackupVaultNotificationsResult> deleteBackupVaultNotificationsAsync(DeleteBackupVaultNotificationsRequest request) {
return deleteBackupVaultNotificationsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteBackupVaultNotificationsResult> deleteBackupVaultNotificationsAsync(
final DeleteBackupVaultNotificationsRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteBackupVaultNotificationsRequest, DeleteBackupVaultNotificationsResult> asyncHandler) {
final DeleteBackupVaultNotificationsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteBackupVaultNotificationsResult>() {
@Override
public DeleteBackupVaultNotificationsResult call() throws Exception {
DeleteBackupVaultNotificationsResult result = null;
try {
result = executeDeleteBackupVaultNotifications(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteRecoveryPointResult> deleteRecoveryPointAsync(DeleteRecoveryPointRequest request) {
return deleteRecoveryPointAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteRecoveryPointResult> deleteRecoveryPointAsync(final DeleteRecoveryPointRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteRecoveryPointRequest, DeleteRecoveryPointResult> asyncHandler) {
final DeleteRecoveryPointRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteRecoveryPointResult>() {
@Override
public DeleteRecoveryPointResult call() throws Exception {
DeleteRecoveryPointResult result = null;
try {
result = executeDeleteRecoveryPoint(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeBackupJobResult> describeBackupJobAsync(DescribeBackupJobRequest request) {
return describeBackupJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeBackupJobResult> describeBackupJobAsync(final DescribeBackupJobRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeBackupJobRequest, DescribeBackupJobResult> asyncHandler) {
final DescribeBackupJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeBackupJobResult>() {
@Override
public DescribeBackupJobResult call() throws Exception {
DescribeBackupJobResult result = null;
try {
result = executeDescribeBackupJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeBackupVaultResult> describeBackupVaultAsync(DescribeBackupVaultRequest request) {
return describeBackupVaultAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeBackupVaultResult> describeBackupVaultAsync(final DescribeBackupVaultRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeBackupVaultRequest, DescribeBackupVaultResult> asyncHandler) {
final DescribeBackupVaultRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeBackupVaultResult>() {
@Override
public DescribeBackupVaultResult call() throws Exception {
DescribeBackupVaultResult result = null;
try {
result = executeDescribeBackupVault(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeCopyJobResult> describeCopyJobAsync(DescribeCopyJobRequest request) {
return describeCopyJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeCopyJobResult> describeCopyJobAsync(final DescribeCopyJobRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeCopyJobRequest, DescribeCopyJobResult> asyncHandler) {
final DescribeCopyJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeCopyJobResult>() {
@Override
public DescribeCopyJobResult call() throws Exception {
DescribeCopyJobResult result = null;
try {
result = executeDescribeCopyJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeGlobalSettingsResult> describeGlobalSettingsAsync(DescribeGlobalSettingsRequest request) {
return describeGlobalSettingsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeGlobalSettingsResult> describeGlobalSettingsAsync(final DescribeGlobalSettingsRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeGlobalSettingsRequest, DescribeGlobalSettingsResult> asyncHandler) {
final DescribeGlobalSettingsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeGlobalSettingsResult>() {
@Override
public DescribeGlobalSettingsResult call() throws Exception {
DescribeGlobalSettingsResult result = null;
try {
result = executeDescribeGlobalSettings(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeProtectedResourceResult> describeProtectedResourceAsync(DescribeProtectedResourceRequest request) {
return describeProtectedResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeProtectedResourceResult> describeProtectedResourceAsync(final DescribeProtectedResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeProtectedResourceRequest, DescribeProtectedResourceResult> asyncHandler) {
final DescribeProtectedResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeProtectedResourceResult>() {
@Override
public DescribeProtectedResourceResult call() throws Exception {
DescribeProtectedResourceResult result = null;
try {
result = executeDescribeProtectedResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeRecoveryPointResult> describeRecoveryPointAsync(DescribeRecoveryPointRequest request) {
return describeRecoveryPointAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeRecoveryPointResult> describeRecoveryPointAsync(final DescribeRecoveryPointRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeRecoveryPointRequest, DescribeRecoveryPointResult> asyncHandler) {
final DescribeRecoveryPointRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeRecoveryPointResult>() {
@Override
public DescribeRecoveryPointResult call() throws Exception {
DescribeRecoveryPointResult result = null;
try {
result = executeDescribeRecoveryPoint(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeRegionSettingsResult> describeRegionSettingsAsync(DescribeRegionSettingsRequest request) {
return describeRegionSettingsAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeRegionSettingsResult> describeRegionSettingsAsync(final DescribeRegionSettingsRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeRegionSettingsRequest, DescribeRegionSettingsResult> asyncHandler) {
final DescribeRegionSettingsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeRegionSettingsResult>() {
@Override
public DescribeRegionSettingsResult call() throws Exception {
DescribeRegionSettingsResult result = null;
try {
result = executeDescribeRegionSettings(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeRestoreJobResult> describeRestoreJobAsync(DescribeRestoreJobRequest request) {
return describeRestoreJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeRestoreJobResult> describeRestoreJobAsync(final DescribeRestoreJobRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeRestoreJobRequest, DescribeRestoreJobResult> asyncHandler) {
final DescribeRestoreJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeRestoreJobResult>() {
@Override
public DescribeRestoreJobResult call() throws Exception {
DescribeRestoreJobResult result = null;
try {
result = executeDescribeRestoreJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ExportBackupPlanTemplateResult> exportBackupPlanTemplateAsync(ExportBackupPlanTemplateRequest request) {
return exportBackupPlanTemplateAsync(request, null);
}
@Override
public java.util.concurrent.Future<ExportBackupPlanTemplateResult> exportBackupPlanTemplateAsync(final ExportBackupPlanTemplateRequest request,
final com.amazonaws.handlers.AsyncHandler<ExportBackupPlanTemplateRequest, ExportBackupPlanTemplateResult> asyncHandler) {
final ExportBackupPlanTemplateRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ExportBackupPlanTemplateResult>() {
@Override
public ExportBackupPlanTemplateResult call() throws Exception {
ExportBackupPlanTemplateResult result = null;
try {
result = executeExportBackupPlanTemplate(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetBackupPlanResult> getBackupPlanAsync(GetBackupPlanRequest request) {
return getBackupPlanAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetBackupPlanResult> getBackupPlanAsync(final GetBackupPlanRequest request,
final com.amazonaws.handlers.AsyncHandler<GetBackupPlanRequest, GetBackupPlanResult> asyncHandler) {
final GetBackupPlanRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetBackupPlanResult>() {
@Override
public GetBackupPlanResult call() throws Exception {
GetBackupPlanResult result = null;
try {
result = executeGetBackupPlan(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetBackupPlanFromJSONResult> getBackupPlanFromJSONAsync(GetBackupPlanFromJSONRequest request) {
return getBackupPlanFromJSONAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetBackupPlanFromJSONResult> getBackupPlanFromJSONAsync(final GetBackupPlanFromJSONRequest request,
final com.amazonaws.handlers.AsyncHandler<GetBackupPlanFromJSONRequest, GetBackupPlanFromJSONResult> asyncHandler) {
final GetBackupPlanFromJSONRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetBackupPlanFromJSONResult>() {
@Override
public GetBackupPlanFromJSONResult call() throws Exception {
GetBackupPlanFromJSONResult result = null;
try {
result = executeGetBackupPlanFromJSON(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetBackupPlanFromTemplateResult> getBackupPlanFromTemplateAsync(GetBackupPlanFromTemplateRequest request) {
return getBackupPlanFromTemplateAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetBackupPlanFromTemplateResult> getBackupPlanFromTemplateAsync(final GetBackupPlanFromTemplateRequest request,
final com.amazonaws.handlers.AsyncHandler<GetBackupPlanFromTemplateRequest, GetBackupPlanFromTemplateResult> asyncHandler) {
final GetBackupPlanFromTemplateRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetBackupPlanFromTemplateResult>() {
@Override
public GetBackupPlanFromTemplateResult call() throws Exception {
GetBackupPlanFromTemplateResult result = null;
try {
result = executeGetBackupPlanFromTemplate(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetBackupSelectionResult> getBackupSelectionAsync(GetBackupSelectionRequest request) {
return getBackupSelectionAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetBackupSelectionResult> getBackupSelectionAsync(final GetBackupSelectionRequest request,
final com.amazonaws.handlers.AsyncHandler<GetBackupSelectionRequest, GetBackupSelectionResult> asyncHandler) {
final GetBackupSelectionRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetBackupSelectionResult>() {
@Override
public GetBackupSelectionResult call() throws Exception {
GetBackupSelectionResult result = null;
try {
result = executeGetBackupSelection(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetBackupVaultAccessPolicyResult> getBackupVaultAccessPolicyAsync(GetBackupVaultAccessPolicyRequest request) {
return getBackupVaultAccessPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetBackupVaultAccessPolicyResult> getBackupVaultAccessPolicyAsync(final GetBackupVaultAccessPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<GetBackupVaultAccessPolicyRequest, GetBackupVaultAccessPolicyResult> asyncHandler) {
final GetBackupVaultAccessPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetBackupVaultAccessPolicyResult>() {
@Override
public GetBackupVaultAccessPolicyResult call() throws Exception {
GetBackupVaultAccessPolicyResult result = null;
try {
result = executeGetBackupVaultAccessPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetBackupVaultNotificationsResult> getBackupVaultNotificationsAsync(GetBackupVaultNotificationsRequest request) {
return getBackupVaultNotificationsAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetBackupVaultNotificationsResult> getBackupVaultNotificationsAsync(final GetBackupVaultNotificationsRequest request,
final com.amazonaws.handlers.AsyncHandler<GetBackupVaultNotificationsRequest, GetBackupVaultNotificationsResult> asyncHandler) {
final GetBackupVaultNotificationsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetBackupVaultNotificationsResult>() {
@Override
public GetBackupVaultNotificationsResult call() throws Exception {
GetBackupVaultNotificationsResult result = null;
try {
result = executeGetBackupVaultNotifications(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetRecoveryPointRestoreMetadataResult> getRecoveryPointRestoreMetadataAsync(
GetRecoveryPointRestoreMetadataRequest request) {
return getRecoveryPointRestoreMetadataAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetRecoveryPointRestoreMetadataResult> getRecoveryPointRestoreMetadataAsync(
final GetRecoveryPointRestoreMetadataRequest request,
final com.amazonaws.handlers.AsyncHandler<GetRecoveryPointRestoreMetadataRequest, GetRecoveryPointRestoreMetadataResult> asyncHandler) {
final GetRecoveryPointRestoreMetadataRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetRecoveryPointRestoreMetadataResult>() {
@Override
public GetRecoveryPointRestoreMetadataResult call() throws Exception {
GetRecoveryPointRestoreMetadataResult result = null;
try {
result = executeGetRecoveryPointRestoreMetadata(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetSupportedResourceTypesResult> getSupportedResourceTypesAsync(GetSupportedResourceTypesRequest request) {
return getSupportedResourceTypesAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetSupportedResourceTypesResult> getSupportedResourceTypesAsync(final GetSupportedResourceTypesRequest request,
final com.amazonaws.handlers.AsyncHandler<GetSupportedResourceTypesRequest, GetSupportedResourceTypesResult> asyncHandler) {
final GetSupportedResourceTypesRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetSupportedResourceTypesResult>() {
@Override
public GetSupportedResourceTypesResult call() throws Exception {
GetSupportedResourceTypesResult result = null;
try {
result = executeGetSupportedResourceTypes(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListBackupJobsResult> listBackupJobsAsync(ListBackupJobsRequest request) {
return listBackupJobsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListBackupJobsResult> listBackupJobsAsync(final ListBackupJobsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListBackupJobsRequest, ListBackupJobsResult> asyncHandler) {
final ListBackupJobsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListBackupJobsResult>() {
@Override
public ListBackupJobsResult call() throws Exception {
ListBackupJobsResult result = null;
try {
result = executeListBackupJobs(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListBackupPlanTemplatesResult> listBackupPlanTemplatesAsync(ListBackupPlanTemplatesRequest request) {
return listBackupPlanTemplatesAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListBackupPlanTemplatesResult> listBackupPlanTemplatesAsync(final ListBackupPlanTemplatesRequest request,
final com.amazonaws.handlers.AsyncHandler<ListBackupPlanTemplatesRequest, ListBackupPlanTemplatesResult> asyncHandler) {
final ListBackupPlanTemplatesRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListBackupPlanTemplatesResult>() {
@Override
public ListBackupPlanTemplatesResult call() throws Exception {
ListBackupPlanTemplatesResult result = null;
try {
result = executeListBackupPlanTemplates(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListBackupPlanVersionsResult> listBackupPlanVersionsAsync(ListBackupPlanVersionsRequest request) {
return listBackupPlanVersionsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListBackupPlanVersionsResult> listBackupPlanVersionsAsync(final ListBackupPlanVersionsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListBackupPlanVersionsRequest, ListBackupPlanVersionsResult> asyncHandler) {
final ListBackupPlanVersionsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListBackupPlanVersionsResult>() {
@Override
public ListBackupPlanVersionsResult call() throws Exception {
ListBackupPlanVersionsResult result = null;
try {
result = executeListBackupPlanVersions(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListBackupPlansResult> listBackupPlansAsync(ListBackupPlansRequest request) {
return listBackupPlansAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListBackupPlansResult> listBackupPlansAsync(final ListBackupPlansRequest request,
final com.amazonaws.handlers.AsyncHandler<ListBackupPlansRequest, ListBackupPlansResult> asyncHandler) {
final ListBackupPlansRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListBackupPlansResult>() {
@Override
public ListBackupPlansResult call() throws Exception {
ListBackupPlansResult result = null;
try {
result = executeListBackupPlans(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListBackupSelectionsResult> listBackupSelectionsAsync(ListBackupSelectionsRequest request) {
return listBackupSelectionsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListBackupSelectionsResult> listBackupSelectionsAsync(final ListBackupSelectionsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListBackupSelectionsRequest, ListBackupSelectionsResult> asyncHandler) {
final ListBackupSelectionsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListBackupSelectionsResult>() {
@Override
public ListBackupSelectionsResult call() throws Exception {
ListBackupSelectionsResult result = null;
try {
result = executeListBackupSelections(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListBackupVaultsResult> listBackupVaultsAsync(ListBackupVaultsRequest request) {
return listBackupVaultsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListBackupVaultsResult> listBackupVaultsAsync(final ListBackupVaultsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListBackupVaultsRequest, ListBackupVaultsResult> asyncHandler) {
final ListBackupVaultsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListBackupVaultsResult>() {
@Override
public ListBackupVaultsResult call() throws Exception {
ListBackupVaultsResult result = null;
try {
result = executeListBackupVaults(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListCopyJobsResult> listCopyJobsAsync(ListCopyJobsRequest request) {
return listCopyJobsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListCopyJobsResult> listCopyJobsAsync(final ListCopyJobsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListCopyJobsRequest, ListCopyJobsResult> asyncHandler) {
final ListCopyJobsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListCopyJobsResult>() {
@Override
public ListCopyJobsResult call() throws Exception {
ListCopyJobsResult result = null;
try {
result = executeListCopyJobs(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListProtectedResourcesResult> listProtectedResourcesAsync(ListProtectedResourcesRequest request) {
return listProtectedResourcesAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListProtectedResourcesResult> listProtectedResourcesAsync(final ListProtectedResourcesRequest request,
final com.amazonaws.handlers.AsyncHandler<ListProtectedResourcesRequest, ListProtectedResourcesResult> asyncHandler) {
final ListProtectedResourcesRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListProtectedResourcesResult>() {
@Override
public ListProtectedResourcesResult call() throws Exception {
ListProtectedResourcesResult result = null;
try {
result = executeListProtectedResources(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListRecoveryPointsByBackupVaultResult> listRecoveryPointsByBackupVaultAsync(
ListRecoveryPointsByBackupVaultRequest request) {
return listRecoveryPointsByBackupVaultAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListRecoveryPointsByBackupVaultResult> listRecoveryPointsByBackupVaultAsync(
final ListRecoveryPointsByBackupVaultRequest request,
final com.amazonaws.handlers.AsyncHandler<ListRecoveryPointsByBackupVaultRequest, ListRecoveryPointsByBackupVaultResult> asyncHandler) {
final ListRecoveryPointsByBackupVaultRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListRecoveryPointsByBackupVaultResult>() {
@Override
public ListRecoveryPointsByBackupVaultResult call() throws Exception {
ListRecoveryPointsByBackupVaultResult result = null;
try {
result = executeListRecoveryPointsByBackupVault(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListRecoveryPointsByResourceResult> listRecoveryPointsByResourceAsync(ListRecoveryPointsByResourceRequest request) {
return listRecoveryPointsByResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListRecoveryPointsByResourceResult> listRecoveryPointsByResourceAsync(final ListRecoveryPointsByResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<ListRecoveryPointsByResourceRequest, ListRecoveryPointsByResourceResult> asyncHandler) {
final ListRecoveryPointsByResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListRecoveryPointsByResourceResult>() {
@Override
public ListRecoveryPointsByResourceResult call() throws Exception {
ListRecoveryPointsByResourceResult result = null;
try {
result = executeListRecoveryPointsByResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListRestoreJobsResult> listRestoreJobsAsync(ListRestoreJobsRequest request) {
return listRestoreJobsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListRestoreJobsResult> listRestoreJobsAsync(final ListRestoreJobsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListRestoreJobsRequest, ListRestoreJobsResult> asyncHandler) {
final ListRestoreJobsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListRestoreJobsResult>() {
@Override
public ListRestoreJobsResult call() throws Exception {
ListRestoreJobsResult result = null;
try {
result = executeListRestoreJobs(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListTagsResult> listTagsAsync(ListTagsRequest request) {
return listTagsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListTagsResult> listTagsAsync(final ListTagsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListTagsRequest, ListTagsResult> asyncHandler) {
final ListTagsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListTagsResult>() {
@Override
public ListTagsResult call() throws Exception {
ListTagsResult result = null;
try {
result = executeListTags(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<PutBackupVaultAccessPolicyResult> putBackupVaultAccessPolicyAsync(PutBackupVaultAccessPolicyRequest request) {
return putBackupVaultAccessPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<PutBackupVaultAccessPolicyResult> putBackupVaultAccessPolicyAsync(final PutBackupVaultAccessPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<PutBackupVaultAccessPolicyRequest, PutBackupVaultAccessPolicyResult> asyncHandler) {
final PutBackupVaultAccessPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<PutBackupVaultAccessPolicyResult>() {
@Override
public PutBackupVaultAccessPolicyResult call() throws Exception {
PutBackupVaultAccessPolicyResult result = null;
try {
result = executePutBackupVaultAccessPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<PutBackupVaultNotificationsResult> putBackupVaultNotificationsAsync(PutBackupVaultNotificationsRequest request) {
return putBackupVaultNotificationsAsync(request, null);
}
@Override
public java.util.concurrent.Future<PutBackupVaultNotificationsResult> putBackupVaultNotificationsAsync(final PutBackupVaultNotificationsRequest request,
final com.amazonaws.handlers.AsyncHandler<PutBackupVaultNotificationsRequest, PutBackupVaultNotificationsResult> asyncHandler) {
final PutBackupVaultNotificationsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<PutBackupVaultNotificationsResult>() {
@Override
public PutBackupVaultNotificationsResult call() throws Exception {
PutBackupVaultNotificationsResult result = null;
try {
result = executePutBackupVaultNotifications(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<StartBackupJobResult> startBackupJobAsync(StartBackupJobRequest request) {
return startBackupJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<StartBackupJobResult> startBackupJobAsync(final StartBackupJobRequest request,
final com.amazonaws.handlers.AsyncHandler<StartBackupJobRequest, StartBackupJobResult> asyncHandler) {
final StartBackupJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<StartBackupJobResult>() {
@Override
public StartBackupJobResult call() throws Exception {
StartBackupJobResult result = null;
try {
result = executeStartBackupJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<StartCopyJobResult> startCopyJobAsync(StartCopyJobRequest request) {
return startCopyJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<StartCopyJobResult> startCopyJobAsync(final StartCopyJobRequest request,
final com.amazonaws.handlers.AsyncHandler<StartCopyJobRequest, StartCopyJobResult> asyncHandler) {
final StartCopyJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<StartCopyJobResult>() {
@Override
public StartCopyJobResult call() throws Exception {
StartCopyJobResult result = null;
try {
result = executeStartCopyJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<StartRestoreJobResult> startRestoreJobAsync(StartRestoreJobRequest request) {
return startRestoreJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<StartRestoreJobResult> startRestoreJobAsync(final StartRestoreJobRequest request,
final com.amazonaws.handlers.AsyncHandler<StartRestoreJobRequest, StartRestoreJobResult> asyncHandler) {
final StartRestoreJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<StartRestoreJobResult>() {
@Override
public StartRestoreJobResult call() throws Exception {
StartRestoreJobResult result = null;
try {
result = executeStartRestoreJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<StopBackupJobResult> stopBackupJobAsync(StopBackupJobRequest request) {
return stopBackupJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<StopBackupJobResult> stopBackupJobAsync(final StopBackupJobRequest request,
final com.amazonaws.handlers.AsyncHandler<StopBackupJobRequest, StopBackupJobResult> asyncHandler) {
final StopBackupJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<StopBackupJobResult>() {
@Override
public StopBackupJobResult call() throws Exception {
StopBackupJobResult result = null;
try {
result = executeStopBackupJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) {
return tagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(final TagResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) {
final TagResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<TagResourceResult>() {
@Override
public TagResourceResult call() throws Exception {
TagResourceResult result = null;
try {
result = executeTagResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) {
return untagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(final UntagResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) {
final UntagResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UntagResourceResult>() {
@Override
public UntagResourceResult call() throws Exception {
UntagResourceResult result = null;
try {
result = executeUntagResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UpdateBackupPlanResult> updateBackupPlanAsync(UpdateBackupPlanRequest request) {
return updateBackupPlanAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateBackupPlanResult> updateBackupPlanAsync(final UpdateBackupPlanRequest request,
final com.amazonaws.handlers.AsyncHandler<UpdateBackupPlanRequest, UpdateBackupPlanResult> asyncHandler) {
final UpdateBackupPlanRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UpdateBackupPlanResult>() {
@Override
public UpdateBackupPlanResult call() throws Exception {
UpdateBackupPlanResult result = null;
try {
result = executeUpdateBackupPlan(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UpdateGlobalSettingsResult> updateGlobalSettingsAsync(UpdateGlobalSettingsRequest request) {
return updateGlobalSettingsAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateGlobalSettingsResult> updateGlobalSettingsAsync(final UpdateGlobalSettingsRequest request,
final com.amazonaws.handlers.AsyncHandler<UpdateGlobalSettingsRequest, UpdateGlobalSettingsResult> asyncHandler) {
final UpdateGlobalSettingsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UpdateGlobalSettingsResult>() {
@Override
public UpdateGlobalSettingsResult call() throws Exception {
UpdateGlobalSettingsResult result = null;
try {
result = executeUpdateGlobalSettings(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UpdateRecoveryPointLifecycleResult> updateRecoveryPointLifecycleAsync(UpdateRecoveryPointLifecycleRequest request) {
return updateRecoveryPointLifecycleAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateRecoveryPointLifecycleResult> updateRecoveryPointLifecycleAsync(final UpdateRecoveryPointLifecycleRequest request,
final com.amazonaws.handlers.AsyncHandler<UpdateRecoveryPointLifecycleRequest, UpdateRecoveryPointLifecycleResult> asyncHandler) {
final UpdateRecoveryPointLifecycleRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UpdateRecoveryPointLifecycleResult>() {
@Override
public UpdateRecoveryPointLifecycleResult call() throws Exception {
UpdateRecoveryPointLifecycleResult result = null;
try {
result = executeUpdateRecoveryPointLifecycle(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UpdateRegionSettingsResult> updateRegionSettingsAsync(UpdateRegionSettingsRequest request) {
return updateRegionSettingsAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateRegionSettingsResult> updateRegionSettingsAsync(final UpdateRegionSettingsRequest request,
final com.amazonaws.handlers.AsyncHandler<UpdateRegionSettingsRequest, UpdateRegionSettingsResult> asyncHandler) {
final UpdateRegionSettingsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UpdateRegionSettingsResult>() {
@Override
public UpdateRegionSettingsResult call() throws Exception {
UpdateRegionSettingsResult result = null;
try {
result = executeUpdateRegionSettings(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
/**
* Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
* asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
* call {@code getExecutorService().shutdown()} followed by {@code getExecutorService().awaitTermination()} prior to
* calling this method.
*/
@Override
public void shutdown() {
super.shutdown();
executorService.shutdownNow();
}
}
|
package com.gathermall.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gathermall.common.utils.PageUtils;
import com.gathermall.product.entity.Attr;
import com.gathermall.product.vo.AttrGroupRelationVo;
import com.gathermall.product.vo.AttrRespVo;
import com.gathermall.product.vo.AttrVo;
import java.util.List;
import java.util.Map;
public interface AttrService extends IService<Attr> {
PageUtils queryPage(Map<String, Object> params, String attrType);
void saveAttr(AttrVo attrVo);
AttrRespVo getAttrInfo(Long attrId);
void updateAttr(AttrVo attrVo);
List<Attr> getRelationAttr(Long attrGroupId);
void deleteRelation(AttrGroupRelationVo[] vos);
PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId);
PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type);
/**
* 在指定的所有属性集合里面,挑出检索属性
* @param attrIds
* @return
*/
List<Long> selectSearchAttrIds(List<Long> attrIds);
}
|
package electrodomesticos;
import java.util.HashMap;
import java.util.Map;
public class Electrodomestico {
protected double PRECIOBASE = 100.0;
protected String COLOR = "blanco";
protected char CONSUMO_ENERGETICO = 'F';
protected double PESO = 5.0;
public Electrodomestico(double PRECIOBASE, double PESO) {
this.PRECIOBASE = PRECIOBASE;
this.PESO = PESO;
}
public Electrodomestico(double PRECIOBASE, String COLOR, char CONSUMO_ENERGETICO, double PESO) {
this.PRECIOBASE = PRECIOBASE;
this.COLOR = COLOR;
this.CONSUMO_ENERGETICO = CONSUMO_ENERGETICO;
this.PESO = PESO;
}
private boolean comprobarConsumoEnergetico(char letra) {
letra = Character.toUpperCase(letra);
switch (letra) {
case 'A', 'B', 'C', 'D', 'E', 'F' -> {
return true;
}
default -> {
this.CONSUMO_ENERGETICO = 'F';
return false;
}
}
}
private boolean comprobarColor(String color) {
switch (color.toLowerCase()) {
case "blanco", "negro", "rojo", "azul", "gris" -> {
return true;
}
default -> {
this.COLOR = "BLANCO";
return false;
}
}
}
public double precioFinal() {
Map<Character, Double> precio = new HashMap<Character, Double>();
precio.put('A', 100.0);
precio.put('B', 80.0);
precio.put('C', 60.0);
precio.put('D', 50.0);
precio.put('E', 30.0);
precio.put('F', 10.0);
PRECIOBASE += precio.get(CONSUMO_ENERGETICO);
if (PESO >= 0 && PESO <= 19) {
PRECIOBASE += 10;
} else if (PESO >= 20 && PESO <= 49) {
PRECIOBASE += 50;
} else if (PESO >= 50 && PESO <= 79) {
PRECIOBASE += 80;
} else if (PESO >= 80) {
PRECIOBASE += 100;
}
return PRECIOBASE;
}
public double getPRECIOBASE() {
return PRECIOBASE;
}
public String getCOLOR() {
return COLOR;
}
public char getCONSUMO_ENERGETICO() {
return CONSUMO_ENERGETICO;
}
public double getPESO() {
return PESO;
}
}
|
/*
* 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.aliyuncs.lmztest.transform.v20100101;
import com.aliyuncs.lmztest.model.v20100101.LfDemoResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class LfDemoResponseUnmarshaller {
public static LfDemoResponse unmarshall(LfDemoResponse lfDemoResponse, UnmarshallerContext _ctx) {
return lfDemoResponse;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.