text
stringlengths 7
1.01M
|
|---|
package ai.sangmado.urbanboot.urban.iptable.management.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Slf4j
@RestController
@ApiIgnore("忽略Ping和健康检查文档")
public class PingController {
private static final String DATE_FORMAT_ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss[.SSS'Z']";
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT_ISO8601_PATTERN);
@GetMapping(path = "/", produces = {"text/plain"})
public String root() {
return "Hello";
}
@GetMapping(path = "/ping", produces = {"text/plain"})
public String ping() {
return LocalDateTime.now(ZoneOffset.UTC).format(dateTimeFormatter);
}
@GetMapping(path = "/health", produces = {"text/plain"})
public String health() {
return "OK";
}
}
|
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.observer.generic;
import com.iluwatar.observer.WeatherType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* GHobbits
*
*/
public class GHobbits implements Race {
private static final Logger LOGGER = LoggerFactory.getLogger(GHobbits.class);
@Override
public void update(GWeather weather, WeatherType weatherType) {
switch (weatherType) {
case COLD:
LOGGER.info("The hobbits are shivering in the cold weather.");
break;
case RAINY:
LOGGER.info("The hobbits look for cover from the rain.");
break;
case SUNNY:
LOGGER.info("The happy hobbits bade in the warm sun.");
break;
case WINDY:
LOGGER.info("The hobbits hold their hats tightly in the windy weather.");
break;
default:
break;
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2022 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.windows;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
/**
* The base .NET class managing System.Windows.Localization, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Localization" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Localization</a>
*/
public class Localization extends NetObject {
/**
* Fully assembly qualified name: PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
*/
public static final String assemblyFullName = "PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
/**
* Assembly name: PresentationFramework
*/
public static final String assemblyShortName = "PresentationFramework";
/**
* Qualified class name: System.Windows.Localization
*/
public static final String className = "System.Windows.Localization";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public Localization(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link Localization}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link Localization} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static Localization cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new Localization(from.getJCOInstance());
}
// Constructors section
public Localization() throws Throwable {
}
// Methods section
public static java.lang.String GetAttributes(NetObject element) throws Throwable, system.ArgumentNullException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentException, system.ArgumentOutOfRangeException, system.NotSupportedException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (java.lang.String)classType.Invoke("GetAttributes", element == null ? null : element.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static java.lang.String GetComments(NetObject element) throws Throwable, system.ArgumentNullException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentException, system.ArgumentOutOfRangeException, system.NotSupportedException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
return (java.lang.String)classType.Invoke("GetComments", element == null ? null : element.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static void SetAttributes(NetObject element, java.lang.String attributes) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.NotImplementedException, system.ArgumentException, system.ObjectDisposedException, system.InvalidOperationException, system.FormatException, system.OutOfMemoryException, system.globalization.CultureNotFoundException, system.NotSupportedException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
classType.Invoke("SetAttributes", element == null ? null : element.getJCOInstance(), attributes);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public static void SetComments(NetObject element, java.lang.String comments) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.FormatException, system.resources.MissingManifestResourceException, system.NotImplementedException, system.ArgumentException, system.ObjectDisposedException, system.InvalidOperationException, system.NotSupportedException {
if (classType == null)
throw new UnsupportedOperationException("classType is null.");
try {
classType.Invoke("SetComments", element == null ? null : element.getJCOInstance(), comments);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Properties section
// Instance Events section
}
|
package com.alfa.cell.push.sdk;
import com.alfa.cell.push.sdk.models.Delivery;
import com.alfa.cell.push.sdk.models.Register;
import com.alfa.cell.push.sdk.models.User;
import com.alfa.cell.push.sdk.models.delivery.DeliveryResult;
import com.alfa.cell.push.sdk.models.register.RegisterResult;
import com.alfa.cell.push.sdk.models.user.UserResult;
import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
class NetworkClient {
private static final String BASE_URL = "https://rest.alfa-cell.com/";
private static final String API_PUSH_DELIVERY = BASE_URL + "message/pushDelivered";
private static final String API_REGISTER_TOKEN = BASE_URL + "device/token";
private static final String API_REGISTER_USER = BASE_URL + "device/user";
private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
private PushDeliveredInterface mPushDeliveredInterface;
private RegisterDeviceInterface mRequestTicketInterface;
private String mAppCode;
private String mUserId;
private String mDeviceId;
void init(String appCode, String deviceId) {
mAppCode = appCode;
mDeviceId = deviceId;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
builder.addNetworkInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY));
}
Retrofit mRetrofitBuilder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(builder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting()
.create()))
.build();
mRequestTicketInterface = mRetrofitBuilder.create(RegisterDeviceInterface.class);
mPushDeliveredInterface = mRetrofitBuilder.create(PushDeliveredInterface.class);
}
void registerToken(String token, String packageName, MobilyPushService.RegisterListener listener) {
if (mDeviceId == null || mDeviceId.isEmpty()) {
throw new RuntimeException("First must invoke initialization.");
}
mCompositeDisposable.add(mRequestTicketInterface.registerToken(new Register(token, mDeviceId, packageName, mAppCode))
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(registerResult -> {
mUserId = registerResult.getData().getId();
if (listener != null) {
listener.onRegistered(registerResult);
}
}, error -> {
if (listener != null) {
listener.onError(error);
}
}));
}
void registerUser(User user, MobilyPushService.UserRegisterListener listener) {
if (mDeviceId == null || mDeviceId.isEmpty()) {
throw new RuntimeException("First must invoke initialization.");
}
user.setAppCode(mAppCode);
user.setDeviceId(mDeviceId);
if (mUserId != null && !mUserId.isEmpty()) {
user.setId(mUserId);
}
mCompositeDisposable.add(mRequestTicketInterface.registerUser(user)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(registerResult -> {
if (listener != null) {
listener.onRegistered(registerResult);
}
}, error -> {
if (listener != null) {
listener.onError(error);
}
}));
}
void pushDelivered(String pushID, MobilyPushService.PushDataListener listener) {
if (mDeviceId == null || mDeviceId.isEmpty()) {
throw new RuntimeException("First must invoke initialization.");
}
mCompositeDisposable.add(mPushDeliveredInterface.delivery(new Delivery(pushID, mDeviceId, mAppCode))
.subscribeOn(Schedulers.newThread())
.observeOn(Schedulers.computation())
.subscribe(registerResult -> {
if (listener != null) {
listener.onDelivered(registerResult);
}
}, error -> {
if (listener != null) {
listener.onError(error);
}
}));
}
interface RegisterDeviceInterface {
@Headers("Content-Type: application/json")
@POST(NetworkClient.API_REGISTER_TOKEN)
Observable<RegisterResult> registerToken(@Body Register register);
@Headers("Content-Type: application/json")
@POST(NetworkClient.API_REGISTER_USER)
Observable<UserResult> registerUser(@Body User user);
}
interface PushDeliveredInterface {
@Headers("Content-Type: application/json")
@POST(NetworkClient.API_PUSH_DELIVERY)
Observable<DeliveryResult> delivery(@Body Delivery delivery);
}
}
|
package async.net.impl;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.Closeable;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import async.net.callback.ExceptionCallback;
public class IOUtilTest {
@SuppressWarnings("unchecked")
private ExceptionCallback<IOException> eCallback = mock(ExceptionCallback.class);
private Closeable closeable = mock(Closeable.class);
@Before
public void setUp() throws Exception {
}
@Test
public void testClose() throws IOException {
IOUtil.close(closeable, eCallback);
verify(closeable).close();
}
@Test
public void testClose_IOException() throws IOException {
IOException e = new IOException();
doThrow(e).when(closeable).close();
IOUtil.close(closeable, eCallback);
verify(closeable).close();
verify(eCallback).exception(e);
}
@Test
public void testClose_Null() throws IOException {
IOUtil.close(null, eCallback);
}
}
|
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.websocket.jakarta.tests.server.sockets;
import jakarta.websocket.Endpoint;
import jakarta.websocket.EndpointConfig;
import jakarta.websocket.MessageHandler;
import jakarta.websocket.Session;
public class IdleTimeoutOnOpenEndpoint extends Endpoint implements MessageHandler.Whole<String>
{
private Session session;
@Override
public void onOpen(Session session, EndpointConfig config)
{
this.session = session;
session.addMessageHandler(this);
session.setMaxIdleTimeout(500);
}
@Override
public void onMessage(String message)
{
// echo message back (this is an indication of timeout failure)
session.getAsyncRemote().sendText(message);
}
}
|
/*
* Copyright 2016 Chris Millar
*
* 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.millr.slick.impl.services;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.millr.slick.services.MediaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Media Service Implementation.
*
* This service will get a list of media nodes.
*/
@Service
@Component
public class MediaServiceImpl implements MediaService {
private static final Logger LOGGER = LoggerFactory.getLogger(PostServiceImpl.class);
private static final String MEDIA_QUERY = "SELECT * FROM [nt:file] AS s "
+ "WHERE "
+ "ISCHILDNODE(s,'/content/slick/publish/media') "
+ "ORDER BY [%s] DESC";
public NodeIterator getMedia(Session session) {
return getMedia(session, null, null);
}
public NodeIterator getMedia(Session session, Long offset, Long limit) {
String currentQuery = String.format(MEDIA_QUERY,"jcr:created");
LOGGER.info("CURRENT QUERY: " + currentQuery);
NodeIterator nodes = null;
if (session != null) {
try {
QueryManager queryManager = session.getWorkspace().getQueryManager();
Query query = queryManager.createQuery(currentQuery, Query.JCR_SQL2);
if (offset != null) {
query.setOffset(offset);
}
if (limit != null) {
query.setLimit(limit);
}
QueryResult result = query.execute();
nodes = result.getNodes();
} catch (RepositoryException e) {
LOGGER.error("Could not search repository", e);
}
}
return nodes;
}
public long getMediaPageCount(Session session, Long pageSize) {
long posts = getTotalMediaCount(session);
return (long)Math.ceil((double)posts / pageSize);
}
public long getTotalMediaCount(Session session) {
return getMedia(session).getSize();
}
}
|
package Shakti.HibernateApp;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import Shakti.HibernateApp.daos.StuffDao;
import Shakti.HibernateApp.entities.Stuff;
import Shakti.HibernateApp.repositories.AuthorityRepo;
import Shakti.HibernateApp.services.UserDetailsSrvc;
import junit.framework.TestCase;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AppTest extends TestCase {
private static final Logger log = LoggerFactory.getLogger(AppTest.class);
@Autowired
private StuffDao stuffDao;
@Autowired UserDetailsSrvc loginService;
@Autowired AuthorityRepo roleRepo;
@Test
public void createStuff() {
Integer i=7;
Stuff s = stuffDao.createStuff(i);
log.debug("S id: "+s.getId());
assertThat(s.getN()).isEqualTo(i);
}
@Test
public void clearTable() {
stuffDao.createStuff(null);
List<Stuff> lzt = stuffDao.getAllUsers();
assertThat(lzt.size()).isGreaterThan(0);
stuffDao.truncate();
lzt = stuffDao.getAllUsers();
assertThat(lzt.size()).isEqualTo(0);
}
/*
@Test
public void loginFail() {
boolean err = false;
try {
loginService.login("beets", "123");
}catch (AuthenticationException ex) {
err = true;
}
assertTrue(err);
}
@Test
public void loginSuccess() {
String user = "max";
String pass = "plank";
User oldUser = loginService.findUser(user);
if (oldUser != null) {
loginService.deleteUser(oldUser.getId());
}
Optional<Role> role = roleRepo.findById("USER");
assertTrue(role.isPresent());
List<Role> lzt = new ArrayList<Role>();
lzt.add(role.get());
int id = -1;
try {
id = loginService.createNewUser(user, pass, lzt);
} catch (NamingException ex) {
ex.printStackTrace();
}
assertThat(id).isGreaterThan(0);
boolean err = false;
try {
loginService.login(user, pass);
}catch (AuthenticationException ex) {
err = true;
}
assertFalse(err);
}
*/
}
|
package ch.tyratox.security.eemail.design;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import ch.tyratox.security.eemail.EEMail_About;
public class EEMail_AboutLabel extends JLabel{
/**
*
*/
private static final long serialVersionUID = 7499150070631081033L;
public EEMail_AboutLabel(){
setOpaque(true);
setBackground(Colors.menuBarAboutBackgroundColor);
setBorder(null);
setForeground(Colors.designForeground);
setFont(Fonts.lato(getClass()));
setHorizontalAlignment(SwingConstants.CENTER);
setText("About");
addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
setBackground(Colors.menuBarAboutBackgroundColor);
}
@Override
public void mousePressed(MouseEvent e) {
setBackground(Colors.menuBarAboutBackgroundColor_hover);
}
@Override
public void mouseExited(MouseEvent e) {
setBackground(Colors.menuBarAboutBackgroundColor);
}
@Override
public void mouseEntered(MouseEvent e) {
setBackground(Colors.menuBarAboutBackgroundColor_hover);
}
@Override
public void mouseClicked(MouseEvent e) {
setBackground(Colors.menuBarAboutBackgroundColor_hover);
EEMail_About es = new EEMail_About();
es.setVisible(true);
}
});
}
}
|
/*
Copyright (c) 2022, Hervé Girod
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 copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Alternatively if you have any questions about this project, you can visit
the project website at the project page on https://github.com/hervegirod/fxsvgimage
*/
package org.girod.javafx.svgimage.tosvg.converters;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Labeled;
import org.girod.javafx.svgimage.tosvg.xml.XMLNode;
/**
* A converter which convert Controls.
*
* @since 1.0
*/
public class ControlConverter extends RegionConverter {
private Control control = null;
public ControlConverter(ConverterDelegate delegate, Control control, XMLNode xmlParent) {
super(delegate, control, xmlParent);
this.control = control;
}
/**
* Convert the Control.
*
* @return the xml node
*/
@Override
public XMLNode convert() {
return super.convert();
}
/**
* Return the additional child Node on this Node.
* Will return null, except for a {@link javafx.scene.control.Labeled}, where it will return {@link javafx.scene.control.Labeled#getGraphic()}.
*
* @return the additional child Node on this Node
*/
@Override
public Node getAdditionalNode() {
if (control instanceof Labeled) {
return ((Labeled) control).getGraphic();
} else {
return null;
}
}
}
|
/*
* Copyright 2015-2020 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.iotsitewise.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Contains a summary of an asset model.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotsitewise-2019-12-02/AssetModelSummary" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AssetModelSummary implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The ID of the asset model (used with AWS IoT SiteWise APIs).
* </p>
*/
private String id;
/**
* <p>
* The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the asset
* model, which has the following format.
* </p>
* <p>
* <code>arn:${Partition}:iotsitewise:${Region}:${Account}:asset-model/${AssetModelId}</code>
* </p>
*/
private String arn;
/**
* <p>
* The name of the asset model.
* </p>
*/
private String name;
/**
* <p>
* The asset model description.
* </p>
*/
private String description;
/**
* <p>
* The date the asset model was created, in Unix epoch time.
* </p>
*/
private java.util.Date creationDate;
/**
* <p>
* The date the asset model was last updated, in Unix epoch time.
* </p>
*/
private java.util.Date lastUpdateDate;
/**
* <p>
* The current status of the asset model.
* </p>
*/
private AssetModelStatus status;
/**
* <p>
* The ID of the asset model (used with AWS IoT SiteWise APIs).
* </p>
*
* @param id
* The ID of the asset model (used with AWS IoT SiteWise APIs).
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The ID of the asset model (used with AWS IoT SiteWise APIs).
* </p>
*
* @return The ID of the asset model (used with AWS IoT SiteWise APIs).
*/
public String getId() {
return this.id;
}
/**
* <p>
* The ID of the asset model (used with AWS IoT SiteWise APIs).
* </p>
*
* @param id
* The ID of the asset model (used with AWS IoT SiteWise APIs).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AssetModelSummary withId(String id) {
setId(id);
return this;
}
/**
* <p>
* The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the asset
* model, which has the following format.
* </p>
* <p>
* <code>arn:${Partition}:iotsitewise:${Region}:${Account}:asset-model/${AssetModelId}</code>
* </p>
*
* @param arn
* The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the
* asset model, which has the following format.</p>
* <p>
* <code>arn:${Partition}:iotsitewise:${Region}:${Account}:asset-model/${AssetModelId}</code>
*/
public void setArn(String arn) {
this.arn = arn;
}
/**
* <p>
* The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the asset
* model, which has the following format.
* </p>
* <p>
* <code>arn:${Partition}:iotsitewise:${Region}:${Account}:asset-model/${AssetModelId}</code>
* </p>
*
* @return The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the
* asset model, which has the following format.</p>
* <p>
* <code>arn:${Partition}:iotsitewise:${Region}:${Account}:asset-model/${AssetModelId}</code>
*/
public String getArn() {
return this.arn;
}
/**
* <p>
* The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the asset
* model, which has the following format.
* </p>
* <p>
* <code>arn:${Partition}:iotsitewise:${Region}:${Account}:asset-model/${AssetModelId}</code>
* </p>
*
* @param arn
* The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the
* asset model, which has the following format.</p>
* <p>
* <code>arn:${Partition}:iotsitewise:${Region}:${Account}:asset-model/${AssetModelId}</code>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AssetModelSummary withArn(String arn) {
setArn(arn);
return this;
}
/**
* <p>
* The name of the asset model.
* </p>
*
* @param name
* The name of the asset model.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the asset model.
* </p>
*
* @return The name of the asset model.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the asset model.
* </p>
*
* @param name
* The name of the asset model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AssetModelSummary withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The asset model description.
* </p>
*
* @param description
* The asset model description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The asset model description.
* </p>
*
* @return The asset model description.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The asset model description.
* </p>
*
* @param description
* The asset model description.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AssetModelSummary withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The date the asset model was created, in Unix epoch time.
* </p>
*
* @param creationDate
* The date the asset model was created, in Unix epoch time.
*/
public void setCreationDate(java.util.Date creationDate) {
this.creationDate = creationDate;
}
/**
* <p>
* The date the asset model was created, in Unix epoch time.
* </p>
*
* @return The date the asset model was created, in Unix epoch time.
*/
public java.util.Date getCreationDate() {
return this.creationDate;
}
/**
* <p>
* The date the asset model was created, in Unix epoch time.
* </p>
*
* @param creationDate
* The date the asset model was created, in Unix epoch time.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AssetModelSummary withCreationDate(java.util.Date creationDate) {
setCreationDate(creationDate);
return this;
}
/**
* <p>
* The date the asset model was last updated, in Unix epoch time.
* </p>
*
* @param lastUpdateDate
* The date the asset model was last updated, in Unix epoch time.
*/
public void setLastUpdateDate(java.util.Date lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
/**
* <p>
* The date the asset model was last updated, in Unix epoch time.
* </p>
*
* @return The date the asset model was last updated, in Unix epoch time.
*/
public java.util.Date getLastUpdateDate() {
return this.lastUpdateDate;
}
/**
* <p>
* The date the asset model was last updated, in Unix epoch time.
* </p>
*
* @param lastUpdateDate
* The date the asset model was last updated, in Unix epoch time.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AssetModelSummary withLastUpdateDate(java.util.Date lastUpdateDate) {
setLastUpdateDate(lastUpdateDate);
return this;
}
/**
* <p>
* The current status of the asset model.
* </p>
*
* @param status
* The current status of the asset model.
*/
public void setStatus(AssetModelStatus status) {
this.status = status;
}
/**
* <p>
* The current status of the asset model.
* </p>
*
* @return The current status of the asset model.
*/
public AssetModelStatus getStatus() {
return this.status;
}
/**
* <p>
* The current status of the asset model.
* </p>
*
* @param status
* The current status of the asset model.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public AssetModelSummary withStatus(AssetModelStatus status) {
setStatus(status);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getId() != null)
sb.append("Id: ").append(getId()).append(",");
if (getArn() != null)
sb.append("Arn: ").append(getArn()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getCreationDate() != null)
sb.append("CreationDate: ").append(getCreationDate()).append(",");
if (getLastUpdateDate() != null)
sb.append("LastUpdateDate: ").append(getLastUpdateDate()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AssetModelSummary == false)
return false;
AssetModelSummary other = (AssetModelSummary) obj;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null && other.getId().equals(this.getId()) == false)
return false;
if (other.getArn() == null ^ this.getArn() == null)
return false;
if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getCreationDate() == null ^ this.getCreationDate() == null)
return false;
if (other.getCreationDate() != null && other.getCreationDate().equals(this.getCreationDate()) == false)
return false;
if (other.getLastUpdateDate() == null ^ this.getLastUpdateDate() == null)
return false;
if (other.getLastUpdateDate() != null && other.getLastUpdateDate().equals(this.getLastUpdateDate()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getCreationDate() == null) ? 0 : getCreationDate().hashCode());
hashCode = prime * hashCode + ((getLastUpdateDate() == null) ? 0 : getLastUpdateDate().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public AssetModelSummary clone() {
try {
return (AssetModelSummary) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.iotsitewise.model.transform.AssetModelSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
package com.in28minutes.rest.webservices.restfulwebservices.todo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TodoJpaRepository extends JpaRepository<Todo, Long>{
List<Todo> findByUsername(String username);
}
|
package org.deeplearning4j.models.embeddings.loader;
import org.nd4j.shade.jackson.databind.DeserializationFeature;
import org.nd4j.shade.jackson.databind.MapperFeature;
import org.nd4j.shade.jackson.databind.ObjectMapper;
import org.nd4j.shade.jackson.databind.SerializationFeature;
import lombok.Data;
import org.apache.commons.codec.binary.Base64;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
*
* This is simple bean/POJO for Word2Vec persistence handling.
* It holds whole w2v model configuration info, except of TokenizerFactory and SentenceIterator, since they are not intended for serialization, and specified at run-time.
*
* @author raver119@gmail.com
*/
@Data
public class VectorsConfiguration implements Serializable {
// word2vec params
private int minWordFrequency = 5;
private double learningRate = 0.025;
private double minLearningRate = 0.0001;
private int layersSize = 200;
private boolean useAdaGrad = false;
private int batchSize = 512;
private int iterations = 1;
private int epochs = 1;
private int window = 5;
private long seed;
private double negative = 0.0d;
private boolean useHierarchicSoftmax = true;
private double sampling = 0.0d;
private int learningRateDecayWords;
private int[] variableWindows;
private boolean hugeModelExpected = false;
private boolean useUnknown = false;
private int scavengerActivationThreshold = 2000000;
private int scavengerRetentionDelay = 3;
private String elementsLearningAlgorithm;
private String sequenceLearningAlgorithm;
private String modelUtils;
private String tokenizerFactory;
private String tokenPreProcessor;
private String UNK = "UNK";
private String STOP = "STOP";
private List<String> stopList = new ArrayList<>();
// overall model info
private int vocabSize;
// paravec-specific option
private boolean trainElementsVectors = true;
private boolean allowParallelTokenization = false;
private boolean preciseWeightInit = false;
private static ObjectMapper mapper;
private static final Object lock = new Object();
private static ObjectMapper mapper() {
if (mapper == null) {
synchronized (lock) {
if (mapper == null) {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
return mapper;
}
}
}
return mapper;
}
public String toJson() {
ObjectMapper mapper = mapper();
try {
/*
we need JSON as single line to save it at first line of the CSV model file
That's ugly method, but its way more memory-friendly then loading whole 10GB json file just to create another 10GB memory array.
*/
return mapper.writeValueAsString(this);
} catch (org.nd4j.shade.jackson.core.JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public String toEncodedJson() {
Base64 base64 = new Base64(Integer.MAX_VALUE);
try {
return base64.encodeAsString(this.toJson().getBytes("UTF-8"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static VectorsConfiguration fromJson(String json) {
ObjectMapper mapper = mapper();
try {
VectorsConfiguration ret = mapper.readValue(json, VectorsConfiguration.class);
return ret;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
/*
*******************************************************************************
* Copyright (C) 2007, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.dev.test.util;
import java.util.Iterator;
import com.ibm.icu.dev.test.TestFmwk;
import com.ibm.icu.impl.TextTrieMap;
public class TextTrieMapTest extends TestFmwk {
private static final Integer SUN = new Integer(1);
private static final Integer MON = new Integer(2);
private static final Integer TUE = new Integer(3);
private static final Integer WED = new Integer(4);
private static final Integer THU = new Integer(5);
private static final Integer FRI = new Integer(6);
private static final Integer SAT = new Integer(7);
private static final Integer FOO = new Integer(-1);
private static final Integer BAR = new Integer(-2);
private static final Object[][] TESTDATA = {
{"Sunday", SUN},
{"Monday", MON},
{"Tuesday", TUE},
{"Wednesday", WED},
{"Thursday", THU},
{"Friday", FRI},
{"Saturday", SAT},
{"Sun", SUN},
{"Mon", MON},
{"Tue", TUE},
{"Wed", WED},
{"Thu", THU},
{"Fri", FRI},
{"Sat", SAT},
{"S", SUN},
{"M", MON},
{"T", TUE},
{"W", WED},
{"T", THU},
{"F", FRI},
{"S", SAT}
};
private static final Object[][] TESTCASES = {
{"Sunday", SUN, SUN},
{"sunday", null, SUN},
{"Mo", MON, MON},
{"mo", null, MON},
{"Thursday Friday", THU, THU},
{"T", new Object[]{TUE, THU}, new Object[]{TUE, THU}},
{"TEST", new Object[]{TUE, THU}, new Object[]{TUE, THU}},
{"SUN", new Object[]{SUN, SAT}, SUN},
{"super", null, SUN},
{"NO", null, null}
};
public static void main(String[] args) throws Exception {
TextTrieMapTest test = new TextTrieMapTest();
test.run(args);
}
public void TestCaseSensitive() {
Iterator itr = null;
TextTrieMap map = new TextTrieMap(false);
for (int i = 0; i < TESTDATA.length; i++) {
map.put((String)TESTDATA[i][0], TESTDATA[i][1]);
}
logln("Test for get(String)");
for (int i = 0; i < TESTCASES.length; i++) {
itr = map.get((String)TESTCASES[i][0]);
checkResult(itr, TESTCASES[i][1]);
}
logln("Test for get(String, int)");
StringBuffer textBuf = new StringBuffer();
for (int i = 0; i < TESTCASES.length; i++) {
textBuf.setLength(0);
for (int j = 0; j < i; j++) {
textBuf.append('X');
}
textBuf.append(TESTCASES[i][0]);
itr = map.get(textBuf.toString(), i);
checkResult(itr, TESTCASES[i][1]);
}
// Add duplicated entry
map.put("Sunday", FOO);
// Add duplicated entry with different casing
map.put("sunday", BAR);
// Make sure the all entries are returned
itr = map.get("Sunday");
checkResult(itr, new Object[]{FOO, SUN});
}
public void TestCaseInsensitive() {
Iterator itr = null;
TextTrieMap map = new TextTrieMap(true);
for (int i = 0; i < TESTDATA.length; i++) {
map.put((String)TESTDATA[i][0], TESTDATA[i][1]);
}
logln("Test for get(String)");
for (int i = 0; i < TESTCASES.length; i++) {
itr = map.get((String)TESTCASES[i][0]);
checkResult(itr, TESTCASES[i][2]);
}
logln("Test for get(String, int)");
StringBuffer textBuf = new StringBuffer();
for (int i = 0; i < TESTCASES.length; i++) {
textBuf.setLength(0);
for (int j = 0; j < i; j++) {
textBuf.append('X');
}
textBuf.append(TESTCASES[i][0]);
itr = map.get(textBuf.toString(), i);
checkResult(itr, TESTCASES[i][2]);
}
// Add duplicated entry
map.put("Sunday", FOO);
// Add duplicated entry with different casing
map.put("sunday", BAR);
// Make sure the all entries are returned
itr = map.get("Sunday");
checkResult(itr, new Object[]{SUN, FOO, BAR});
}
private boolean eql(Object o1, Object o2) {
if (o1 == null || o2 == null) {
if (o1 == null && o2 == null) {
return true;
}
return false;
}
return o1.equals(o2);
}
private void checkResult(Iterator itr, Object expected) {
if (itr == null) {
if (expected != null) {
errln("FAIL: Empty results - Expected: " + expected);
}
return;
}
if (expected == null && itr != null) {
errln("FAIL: Empty result is expected");
return;
}
Object[] exp;
if (expected instanceof Object[]) {
exp = (Object[])expected;
} else {
exp = new Object[]{expected};
}
boolean[] found = new boolean[exp.length];
while (itr.hasNext()) {
Object val = itr.next();
for (int i = 0; i < exp.length; i++) {
if (eql(exp[i], val)) {
found[i] = true;
}
}
}
for (int i = 0; i < exp.length; i++) {
if (found[i] == false) {
errln("FAIL: The search result does not contain " + exp[i]);
}
}
}
}
|
package com.snackhole.simplesorcery.sorcery.spells;
import net.minecraft.entity.player.EntityPlayerMP;
public class dispel implements ISpell {
@Override
public void cast(int level, EntityPlayerMP player, boolean entityDetected, int entityID) {
player.clearActivePotions();
}
}
|
/*
* Licensed to ObjectStyle LLC under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ObjectStyle LLC 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.bootique.jersey.client;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation;
/**
* A DI annotation for a set of JAXRS client features.
*/
@Target({ ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface JerseyClientFeatures {
}
|
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: RealType.java,v 1.2.4.1 2005/09/05 11:28:45 pvedula Exp $
*/
package com.sun.org.apache.xalan.internal.xsltc.compiler.util;
import com.sun.org.apache.bcel.internal.generic.BranchHandle;
import com.sun.org.apache.bcel.internal.generic.CHECKCAST;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.DLOAD;
import com.sun.org.apache.bcel.internal.generic.DSTORE;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import com.sun.org.apache.bcel.internal.generic.IFEQ;
import com.sun.org.apache.bcel.internal.generic.IFNE;
import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL;
import com.sun.org.apache.bcel.internal.generic.INVOKESTATIC;
import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
import com.sun.org.apache.bcel.internal.generic.Instruction;
import com.sun.org.apache.bcel.internal.generic.InstructionConstants;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.LocalVariableGen;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Constants;
import com.sun.org.apache.xalan.internal.xsltc.compiler.FlowList;
/**
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
*/
public final class RealType extends NumberType {
protected RealType() {}
public String toString() {
return "real";
}
public boolean identicalTo(Type other) {
return this == other;
}
public String toSignature() {
return "D";
}
public com.sun.org.apache.bcel.internal.generic.Type toJCType() {
return com.sun.org.apache.bcel.internal.generic.Type.DOUBLE;
}
/**
* @see com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#distanceTo
*/
public int distanceTo(Type type) {
if (type == this) {
return 0;
}
else if (type == Type.Int) {
return 1;
}
else {
return Integer.MAX_VALUE;
}
}
/**
* Translates a real into an object of internal type <code>type</code>. The
* translation to int is undefined since reals are never converted to ints.
*
* @see com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
*/
public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
Type type) {
if (type == Type.String) {
translateTo(classGen, methodGen, (StringType) type);
}
else if (type == Type.Boolean) {
translateTo(classGen, methodGen, (BooleanType) type);
}
else if (type == Type.Reference) {
translateTo(classGen, methodGen, (ReferenceType) type);
}
else if (type == Type.Int) {
translateTo(classGen, methodGen, (IntType) type);
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR,
toString(), type.toString());
classGen.getParser().reportError(Constants.FATAL, err);
}
}
/**
* Expects a real on the stack and pushes its string value by calling
* <code>Double.toString(double d)</code>.
*
* @see com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
*/
public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
StringType type) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
il.append(new INVOKESTATIC(cpg.addMethodref(BASIS_LIBRARY_CLASS,
"realToString",
"(D)" + STRING_SIG)));
}
/**
* Expects a real on the stack and pushes a 0 if that number is 0.0 and
* a 1 otherwise.
*
* @see com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
*/
public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
BooleanType type) {
final InstructionList il = methodGen.getInstructionList();
FlowList falsel = translateToDesynthesized(classGen, methodGen, type);
il.append(ICONST_1);
final BranchHandle truec = il.append(new GOTO(null));
falsel.backPatch(il.append(ICONST_0));
truec.setTarget(il.append(NOP));
}
/**
* Expects a real on the stack and pushes a truncated integer value
*
* @see com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
*/
public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
IntType type) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
il.append(new INVOKESTATIC(cpg.addMethodref(BASIS_LIBRARY_CLASS,
"realToInt","(D)I")));
}
/**
* Translates a real into a non-synthesized boolean. It does not push a
* 0 or a 1 but instead returns branchhandle list to be appended to the
* false list. A NaN must be converted to "false".
*
* @see com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateToDesynthesized
*/
public FlowList translateToDesynthesized(ClassGenerator classGen,
MethodGenerator methodGen,
BooleanType type) {
LocalVariableGen local;
final FlowList flowlist = new FlowList();
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
// Store real into a local variable
il.append(DUP2);
local = methodGen.addLocalVariable("real_to_boolean_tmp",
com.sun.org.apache.bcel.internal.generic.Type.DOUBLE,
null, null);
local.setStart(il.append(new DSTORE(local.getIndex())));
// Compare it to 0.0
il.append(DCONST_0);
il.append(DCMPG);
flowlist.add(il.append(new IFEQ(null)));
//!!! call isNaN
// Compare it to itself to see if NaN
il.append(new DLOAD(local.getIndex()));
local.setEnd(il.append(new DLOAD(local.getIndex())));
il.append(DCMPG);
flowlist.add(il.append(new IFNE(null))); // NaN != NaN
return flowlist;
}
/**
* Expects a double on the stack and pushes a boxed double. Boxed
* double are represented by an instance of <code>java.lang.Double</code>.
*
* @see com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
*/
public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
ReferenceType type) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
il.append(new NEW(cpg.addClass(DOUBLE_CLASS)));
il.append(DUP_X2);
il.append(DUP_X2);
il.append(POP);
il.append(new INVOKESPECIAL(cpg.addMethodref(DOUBLE_CLASS,
"<init>", "(D)V")));
}
/**
* Translates a real into the Java type denoted by <code>clazz</code>.
* Expects a real on the stack and pushes a number of the appropriate
* type after coercion.
*/
public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
final Class clazz) {
final InstructionList il = methodGen.getInstructionList();
if (clazz == Character.TYPE) {
il.append(D2I);
il.append(I2C);
}
else if (clazz == Byte.TYPE) {
il.append(D2I);
il.append(I2B);
}
else if (clazz == Short.TYPE) {
il.append(D2I);
il.append(I2S);
}
else if (clazz == Integer.TYPE) {
il.append(D2I);
}
else if (clazz == Long.TYPE) {
il.append(D2L);
}
else if (clazz == Float.TYPE) {
il.append(D2F);
}
else if (clazz == Double.TYPE) {
il.append(NOP);
}
// Is Double <: clazz? I.e. clazz in { Double, Number, Object }
else if (clazz.isAssignableFrom(java.lang.Double.class)) {
translateTo(classGen, methodGen, Type.Reference);
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR,
toString(), clazz.getName());
classGen.getParser().reportError(Constants.FATAL, err);
}
}
/**
* Translates an external (primitive) Java type into a real. Expects a java
* object on the stack and pushes a real (i.e., a double).
*/
public void translateFrom(ClassGenerator classGen, MethodGenerator methodGen,
Class clazz) {
InstructionList il = methodGen.getInstructionList();
if (clazz == Character.TYPE || clazz == Byte.TYPE ||
clazz == Short.TYPE || clazz == Integer.TYPE) {
il.append(I2D);
}
else if (clazz == Long.TYPE) {
il.append(L2D);
}
else if (clazz == Float.TYPE) {
il.append(F2D);
}
else if (clazz == Double.TYPE) {
il.append(NOP);
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR,
toString(), clazz.getName());
classGen.getParser().reportError(Constants.FATAL, err);
}
}
/**
* Translates an object of this type to its boxed representation.
*/
public void translateBox(ClassGenerator classGen,
MethodGenerator methodGen) {
translateTo(classGen, methodGen, Type.Reference);
}
/**
* Translates an object of this type to its unboxed representation.
*/
public void translateUnBox(ClassGenerator classGen,
MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
il.append(new CHECKCAST(cpg.addClass(DOUBLE_CLASS)));
il.append(new INVOKEVIRTUAL(cpg.addMethodref(DOUBLE_CLASS,
DOUBLE_VALUE,
DOUBLE_VALUE_SIG)));
}
public Instruction ADD() {
return InstructionConstants.DADD;
}
public Instruction SUB() {
return InstructionConstants.DSUB;
}
public Instruction MUL() {
return InstructionConstants.DMUL;
}
public Instruction DIV() {
return InstructionConstants.DDIV;
}
public Instruction REM() {
return InstructionConstants.DREM;
}
public Instruction NEG() {
return InstructionConstants.DNEG;
}
public Instruction LOAD(int slot) {
return new DLOAD(slot);
}
public Instruction STORE(int slot) {
return new DSTORE(slot);
}
public Instruction POP() {
return POP2;
}
public Instruction CMP(boolean less) {
return less ? InstructionConstants.DCMPG : InstructionConstants.DCMPL;
}
public Instruction DUP() {
return DUP2;
}
}
|
package jet.opengl.demos.intel.avsm;
/**
* Created by mazhen'gui on 2017/10/9.
*/
final class FrameStats {
float VolumetricShadowTime;
float SolidGeometryTime;
float ParticlesTime;
float TotalTime;
void reset(){
VolumetricShadowTime = 0;
SolidGeometryTime = 0;
ParticlesTime = 0;
TotalTime = 0;
}
void set(FrameStats ohs){
VolumetricShadowTime = ohs.VolumetricShadowTime;
SolidGeometryTime = ohs.SolidGeometryTime;
ParticlesTime = ohs.ParticlesTime;
TotalTime = ohs.TotalTime;
}
}
|
/*
* 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.geode.cache.lucene.internal.filesystem;
import static org.junit.Assert.assertEquals;
import java.util.UUID;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.CopyHelper;
import org.apache.geode.test.junit.categories.LuceneTest;
@Category({LuceneTest.class})
public class ChunkKeyJUnitTest {
@Test
public void testSerialization() {
ChunkKey key = new ChunkKey(UUID.randomUUID(), 5);
ChunkKey copy = CopyHelper.deepCopy(key);
assertEquals(key, copy);
assertEquals(key.hashCode(), copy.hashCode());
assertEquals(key.getFileId(), copy.getFileId());
assertEquals(key.getChunkId(), copy.getChunkId());
}
}
|
/* file: Input.java */
/*******************************************************************************
* Copyright 2014-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
* @ingroup sorting
* @{
*/
package com.intel.daal.algorithms.sorting;
import com.intel.daal.utils.*;
import com.intel.daal.data_management.data.Factory;
import com.intel.daal.data_management.data.NumericTable;
import com.intel.daal.services.DaalContext;
/**
* <a name="DAAL-CLASS-ALGORITHMS__SORTING__INPUT"></a>
* @brief %Input objects for the sorting
*/
public class Input extends com.intel.daal.algorithms.Input {
/** @private */
static {
LibUtils.loadLibrary();
}
public Input(DaalContext context, long cInput) {
super(context, cInput);
}
/**
* Sets the input object for the sorting
* @param id Identifier of the %input object
* @param val Value of the input object
*/
public void set(InputId id, NumericTable val) {
if (id == InputId.data) {
cSetInput(cObject, id.getValue(), val.getCObject());
}
else {
throw new IllegalArgumentException("id unsupported");
}
}
/**
* Returns the input object of the sorting
* @param id Identifier of the %input object
* @return %Input object that corresponds to the given identifier
*/
public NumericTable get(InputId id) {
if (id == InputId.data) {
return (NumericTable)Factory.instance().createObject(getContext(), cGetInput(cObject, id.getValue()));
}
else {
throw new IllegalArgumentException("id unsupported");
}
}
private native void cSetInput(long cInput, int id, long ntAddr);
private native long cGetInput(long cInput, int id);
}
/** @} */
|
package com.discovery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryApplication.class, args);
}
}
|
/*
* 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.ambari.server.checks;
import java.util.HashMap;
import java.util.Map;
import org.apache.ambari.server.controller.PrereqCheckRequest;
import org.apache.ambari.server.orm.entities.RepositoryVersionEntity;
import org.apache.ambari.server.stack.upgrade.UpgradeType;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.RepositoryType;
import org.apache.ambari.server.state.Service;
import org.apache.ambari.server.state.StackId;
import org.apache.ambari.server.state.repository.ClusterVersionSummary;
import org.apache.ambari.server.state.repository.VersionDefinitionXml;
import org.apache.ambari.server.state.stack.PrereqCheckStatus;
import org.apache.ambari.server.state.stack.PrerequisiteCheck;
import org.easymock.EasyMock;
import org.easymock.EasyMockSupport;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.inject.Provider;
/**
* Tests {@link HiveNotRollingWarning}.
*/
@RunWith(MockitoJUnitRunner.class)
public class HiveNotRollingWarningTest extends EasyMockSupport {
private final String m_clusterName = "c1";
private final Clusters m_clusters = niceMock(Clusters.class);
@Mock
private ClusterVersionSummary m_clusterVersionSummary;
@Mock
private VersionDefinitionXml m_vdfXml;
@Mock
private RepositoryVersionEntity m_repositoryVersion;
final Map<String, Service> m_services = new HashMap<>();
@Before
public void setup() throws Exception {
m_services.clear();
Mockito.when(m_repositoryVersion.getType()).thenReturn(RepositoryType.STANDARD);
Mockito.when(m_repositoryVersion.getRepositoryXml()).thenReturn(m_vdfXml);
Mockito.when(m_vdfXml.getClusterSummary(Mockito.any(Cluster.class))).thenReturn(m_clusterVersionSummary);
Mockito.when(m_clusterVersionSummary.getAvailableServiceNames()).thenReturn(m_services.keySet());
}
/**
* @throws Exception
*/
@Test
public void testIsApplicable() throws Exception {
final HiveNotRollingWarning hiveWarningCheck = new HiveNotRollingWarning();
hiveWarningCheck.clustersProvider = new Provider<Clusters>() {
@Override
public Clusters get() {
return m_clusters;
}
};
final Cluster cluster = niceMock(Cluster.class);
final Service hive = niceMock(Service.class);
m_services.put("HIVE", hive);
EasyMock.expect(cluster.getClusterId()).andReturn(1L).anyTimes();
EasyMock.expect(cluster.getCurrentStackVersion()).andReturn(new StackId("HDP", "2.3")).anyTimes();
EasyMock.expect(cluster.getServices()).andReturn(m_services).anyTimes();
EasyMock.expect(m_clusters.getCluster(m_clusterName)).andReturn(cluster).atLeastOnce();
PrereqCheckRequest request = niceMock(PrereqCheckRequest.class);
EasyMock.expect(request.getClusterName()).andReturn(m_clusterName).anyTimes();
EasyMock.expect(request.getUpgradeType()).andReturn(UpgradeType.ROLLING).anyTimes();
EasyMock.expect(request.getTargetRepositoryVersion()).andReturn(m_repositoryVersion).atLeastOnce();
replayAll();
Assert.assertTrue(hiveWarningCheck.isApplicable(request));
verifyAll();
}
/**
* @throws Exception
*/
@Test
public void testPerform() throws Exception {
final HiveNotRollingWarning hiveWarningCheck = new HiveNotRollingWarning();
PrereqCheckRequest request = new PrereqCheckRequest(m_clusterName);
PrerequisiteCheck check = new PrerequisiteCheck(null, null);
hiveWarningCheck.perform(check, request);
Assert.assertEquals(PrereqCheckStatus.WARNING, check.getStatus());
}
}
|
package com.bitdubai.fermat_ccp_plugin.layer.request.crypto_payment.developer.bitdubai.version_1.database;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabase;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTable;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTableRecord;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperObjectFactory;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_ccp_plugin.layer.request.crypto_payment.developer.bitdubai.version_1.exceptions.CantInitializeCryptoPaymentRequestDatabaseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* The Class <code>com.bitdubai.fermat_ccp_plugin.layer.request.crypto_payment.developer.bitdubai.version_1.database.CryptoPaymentRequestDeveloperDatabaseFactory</code> have
* contains the methods that the Developer Database Tools uses to show the information.
* <p/>
*
* Created by Leon Acosta - (laion.cj91@gmail.com) on 01/10/15.
*
* @version 1.0
* @since Java JDK 1.7
*/
public class CryptoPaymentRequestDeveloperDatabaseFactory {
private final PluginDatabaseSystem pluginDatabaseSystem;
private final UUID pluginId;
Database database;
public CryptoPaymentRequestDeveloperDatabaseFactory(final PluginDatabaseSystem pluginDatabaseSystem,
final UUID pluginId ) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
this.pluginId = pluginId ;
}
public void initializeDatabase() throws CantInitializeCryptoPaymentRequestDatabaseException {
try {
database = this.pluginDatabaseSystem.openDatabase(
pluginId,
pluginId.toString()
);
} catch (CantOpenDatabaseException cantOpenDatabaseException) {
throw new CantInitializeCryptoPaymentRequestDatabaseException(cantOpenDatabaseException);
} catch (DatabaseNotFoundException e) {
CryptoPaymentRequestDatabaseFactory cryptoPaymentRequestDatabaseFactory = new CryptoPaymentRequestDatabaseFactory(pluginDatabaseSystem);
try {
database = cryptoPaymentRequestDatabaseFactory.createDatabase(pluginId, pluginId.toString());
} catch (CantCreateDatabaseException cantCreateDatabaseException) {
throw new CantInitializeCryptoPaymentRequestDatabaseException(cantCreateDatabaseException);
}
}
}
public List<DeveloperDatabase> getDatabaseList(final DeveloperObjectFactory developerObjectFactory) {
List<DeveloperDatabase> databases = new ArrayList<>();
databases.add(developerObjectFactory.getNewDeveloperDatabase("Crypto Payment", this.pluginId.toString()));
return databases;
}
public List<DeveloperDatabaseTable> getDatabaseTableList(final DeveloperObjectFactory developerObjectFactory) {
List<DeveloperDatabaseTable> tables = new ArrayList<>();
/**
* Table Crypto Address Request columns.
*/
List<String> cryptoAddressRequestColumns = new ArrayList<>();
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_REQUEST_ID_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_WALLET_PUBLIC_KEY_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_IDENTITY_PUBLIC_KEY_COLUMN_NAME);
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_IDENTITY_TYPE_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_ACTOR_PUBLIC_KEY_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_ACTOR_TYPE_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_DESCRIPTION_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_CRYPTO_ADDRESS_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_CRYPTO_CURRENCY_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_AMOUNT_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_START_TIME_STAMP_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_END_TIME_STAMP_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_TYPE_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_STATE_COLUMN_NAME );
cryptoAddressRequestColumns.add(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_NETWORK_TYPE_COLUMN_NAME );
/**
* Table Crypto Address Request addition.
*/
DeveloperDatabaseTable cryptoAddressRequestTable = developerObjectFactory.getNewDeveloperDatabaseTable(CryptoPaymentRequestDatabaseConstants.CRYPTO_PAYMENT_REQUEST_TABLE_NAME, cryptoAddressRequestColumns);
tables.add(cryptoAddressRequestTable);
return tables;
}
public List<DeveloperDatabaseTableRecord> getDatabaseTableContent(final DeveloperObjectFactory developerObjectFactory,
final DeveloperDatabaseTable developerDatabaseTable) {
try {
initializeDatabase();
DatabaseTable selectedTable = database.getTable(developerDatabaseTable.getName());
selectedTable.loadToMemory();
List<DatabaseTableRecord> records = selectedTable.getRecords();
List<String> developerRow = new ArrayList<>();
List<DeveloperDatabaseTableRecord> returnedRecords = new ArrayList<>();
for (DatabaseTableRecord row : records) {
for (DatabaseRecord field : row.getValues())
developerRow.add(field.getValue());
returnedRecords.add(developerObjectFactory.getNewDeveloperDatabaseTableRecord(developerRow));
}
return returnedRecords;
} catch (CantLoadTableToMemoryException | CantInitializeCryptoPaymentRequestDatabaseException cantLoadTableToMemory) {
return new ArrayList<>();
}
}
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2021 aoju.org OSHI and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *
********************************************************************************/
package org.aoju.bus.health.builtin.hardware;
import org.aoju.bus.core.annotation.ThreadSafe;
import java.util.Collections;
import java.util.List;
/**
* A hardware abstraction layer. Provides access to hardware items such as
* processors, memory, battery, and disks.
*
* @author Kimi Liu
* @version 6.3.2
* @since JDK 1.8+
*/
@ThreadSafe
public interface HardwareAbstractionLayer {
/**
* Instantiates a {@link ComputerSystem} object. This represents
* the physical hardware, including components such as BIOS/Firmware and a
* motherboard, logic board, etc.
*
* @return a {@link ComputerSystem} object.
*/
ComputerSystem getComputerSystem();
/**
* Instantiates a {@link CentralProcessor} object. This represents
* one or more Logical CPUs.
*
* @return A {@link CentralProcessor} object.
*/
CentralProcessor getProcessor();
/**
* Instantiates a {@link GlobalMemory} object.
*
* @return A memory object.
*/
GlobalMemory getMemory();
/**
* Instantiates a list of {@link PowerSource} objects,
* representing batteries, etc.
*
* @return A list of PowerSource objects or an empty list if none are present.
*/
List<PowerSource> getPowerSources();
/**
* Instantiates a list of {@link HWDiskStore} objects,
* representing physical hard disks or other similar storage devices.
*
* @return A list of HWDiskStore objects or an empty list if none are present.
*/
List<HWDiskStore> getDiskStores();
/**
* Instantiates a list of {@link LogicalVolumeGroup} objects, representing a
* storage pool or group of devices, partitions, volumes, or other
* implementation specific means of file storage.
* <p>
* If not yet implemented or if logical volume groups do not exist, returns an
* empty list.
* <p>
* Currently implemented for Linux (LVM2), macOS (Core Storage), and Windows
* (Storage Spaces).
*
* @return A list of {@link LogicalVolumeGroup} objects or an empty list if none
* are present.
*/
default List<LogicalVolumeGroup> getLogicalVolumeGroups() {
return Collections.emptyList();
}
/**
* Gets a list of non-local {@link NetworkIF} objects, representing a network
* interface. The list excludes local interfaces.
*
* @return A list of {@link NetworkIF} objects representing the interfaces
*/
List<NetworkIF> getNetworkIFs();
/**
* Gets a list {@link NetworkIF} objects, representing a network interface.
*
* @param includeLocalInterfaces whether to include local interfaces (loopback or no hardware
* address) in the result
* @return A list of {@link NetworkIF} objects representing the interfaces
*/
List<NetworkIF> getNetworkIFs(boolean includeLocalInterfaces);
/**
* Instantiates a list of {@link Display} objects, representing
* monitors or other video output devices.
*
* @return A list of Display objects or an empty list if none are present.
*/
List<Display> getDisplays();
/**
* Instantiates a {@link Sensors} object, representing CPU
* temperature and fan speed.
*
* @return A Sensors object
*/
Sensors getSensors();
/**
* Instantiates a list of {@link UsbDevice} objects, representing
* devices connected via a usb port (including internal devices).
* <p>
* If the value of {@code tree} is true, the top level devices returned from
* this method are the USB Controllers; connected hubs and devices in its device
* tree share that controller's bandwidth. If the value of {@code tree} is
* false, USB devices (not controllers) are listed in a single flat list.
*
* @param tree If {@code true}, returns devices connected to the existing device,
* accessible via {@link UsbDevice#getConnectedDevices()}. If
* {@code false} returns devices as a flat list with no connected
* device information.
* @return A list of UsbDevice objects representing (optionally) the USB
* Controllers and devices connected to them, or an empty list if none
* are present
*/
List<UsbDevice> getUsbDevices(boolean tree);
/**
* Instantiates a list of {@link SoundCard} objects, representing
* the Sound cards.
*
* @return A list of SoundCard objects or an empty list if none are present.
*/
List<SoundCard> getSoundCards();
/**
* Instantiates a list of {@link GraphicsCard} objects,
* representing the Graphics cards.
*
* @return A list of objects or an empty list if none are present.
*/
List<GraphicsCard> getGraphicsCards();
}
|
package kim.aries.gulimall.order.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 支付信息表
*
* @author aries
* @email aries_test@qq.com
* @date 2021-04-04 20:17:39
*/
@Data
@TableName("oms_payment_info")
public class OmsPaymentInfoEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 订单号(对外业务号)
*/
private String orderSn;
/**
* 订单id
*/
private Long orderId;
/**
* 支付宝交易流水号
*/
private String alipayTradeNo;
/**
* 支付总金额
*/
private BigDecimal totalAmount;
/**
* 交易内容
*/
private String subject;
/**
* 支付状态
*/
private String paymentStatus;
/**
* 创建时间
*/
private Date createTime;
/**
* 确认时间
*/
private Date confirmTime;
/**
* 回调内容
*/
private String callbackContent;
/**
* 回调时间
*/
private Date callbackTime;
}
|
package net.minecraft.enchantment;
import java.util.ArrayList;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.StatCollector;
public abstract class Enchantment
{
public static final Enchantment[] enchantmentsList = new Enchantment[256];
/** The list of enchantments applicable by the anvil from a book */
public static final Enchantment[] enchantmentsBookList;
/** Converts environmental damage to armour damage */
public static final Enchantment protection = new EnchantmentProtection(0, 10, 0);
/** Protection against fire */
public static final Enchantment fireProtection = new EnchantmentProtection(1, 5, 1);
/** Less fall damage */
public static final Enchantment featherFalling = new EnchantmentProtection(2, 5, 2);
/** Protection against explosions */
public static final Enchantment blastProtection = new EnchantmentProtection(3, 2, 3);
/** Protection against projectile entities (e.g. arrows) */
public static final Enchantment projectileProtection = new EnchantmentProtection(4, 5, 4);
/**
* Decreases the rate of air loss underwater; increases time between damage while suffocating
*/
public static final Enchantment respiration = new EnchantmentOxygen(5, 2);
/** Increases underwater mining rate */
public static final Enchantment aquaAffinity = new EnchantmentWaterWorker(6, 2);
public static final Enchantment thorns = new EnchantmentThorns(7, 1);
/** Extra damage to mobs */
public static final Enchantment sharpness = new EnchantmentDamage(16, 10, 0);
/** Extra damage to zombies, zombie pigmen and skeletons */
public static final Enchantment smite = new EnchantmentDamage(17, 5, 1);
/** Extra damage to spiders, cave spiders and silverfish */
public static final Enchantment baneOfArthropods = new EnchantmentDamage(18, 5, 2);
/** Knocks mob and players backwards upon hit */
public static final Enchantment knockback = new EnchantmentKnockback(19, 5);
/** Lights mobs on fire */
public static final Enchantment fireAspect = new EnchantmentFireAspect(20, 2);
/** Mobs have a chance to drop more loot */
public static final Enchantment looting = new EnchantmentLootBonus(21, 2, EnumEnchantmentType.weapon);
/** Faster resource gathering while in use */
public static final Enchantment efficiency = new EnchantmentDigging(32, 10);
/**
* Blocks mined will drop themselves, even if it should drop something else (e.g. stone will drop stone, not
* cobblestone)
*/
public static final Enchantment silkTouch = new EnchantmentUntouching(33, 1);
/**
* Sometimes, the tool's durability will not be spent when the tool is used
*/
public static final Enchantment unbreaking = new EnchantmentDurability(34, 5);
/** Can multiply the drop rate of items from blocks */
public static final Enchantment fortune = new EnchantmentLootBonus(35, 2, EnumEnchantmentType.digger);
/** Power enchantment for bows, add's extra damage to arrows. */
public static final Enchantment power = new EnchantmentArrowDamage(48, 10);
/**
* Knockback enchantments for bows, the arrows will knockback the target when hit.
*/
public static final Enchantment punch = new EnchantmentArrowKnockback(49, 2);
/**
* Flame enchantment for bows. Arrows fired by the bow will be on fire. Any target hit will also set on fire.
*/
public static final Enchantment flame = new EnchantmentArrowFire(50, 2);
/**
* Infinity enchantment for bows. The bow will not consume arrows anymore, but will still required at least one
* arrow on inventory use the bow.
*/
public static final Enchantment infinity = new EnchantmentArrowInfinite(51, 1);
public static final Enchantment field_151370_z = new EnchantmentLootBonus(61, 2, EnumEnchantmentType.fishing_rod);
public static final Enchantment field_151369_A = new EnchantmentFishingSpeed(62, 2, EnumEnchantmentType.fishing_rod);
public final int effectId;
private final int weight;
/** The EnumEnchantmentType given to this Enchantment. */
public EnumEnchantmentType type;
/** Used in localisation and stats. */
protected String name;
private static final String __OBFID = "CL_00000105";
protected Enchantment(int par1, int par2, EnumEnchantmentType par3EnumEnchantmentType)
{
this.effectId = par1;
this.weight = par2;
this.type = par3EnumEnchantmentType;
if (enchantmentsList[par1] != null)
{
throw new IllegalArgumentException("Duplicate enchantment id!");
}
else
{
enchantmentsList[par1] = this;
}
}
public int getWeight()
{
return this.weight;
}
/**
* Returns the minimum level that the enchantment can have.
*/
public int getMinLevel()
{
return 1;
}
/**
* Returns the maximum level that the enchantment can have.
*/
public int getMaxLevel()
{
return 1;
}
/**
* Returns the minimal value of enchantability needed on the enchantment level passed.
*/
public int getMinEnchantability(int par1)
{
return 1 + par1 * 10;
}
/**
* Returns the maximum value of enchantability nedded on the enchantment level passed.
*/
public int getMaxEnchantability(int par1)
{
return this.getMinEnchantability(par1) + 5;
}
/**
* Calculates de damage protection of the enchantment based on level and damage source passed.
*/
public int calcModifierDamage(int par1, DamageSource par2DamageSource)
{
return 0;
}
/**
* Calculates de (magic) damage done by the enchantment on a living entity based on level and entity passed.
*/
public float calcModifierLiving(int par1, EntityLivingBase par2EntityLivingBase)
{
return 0.0F;
}
/**
* Determines if the enchantment passed can be applyied together with this enchantment.
*/
public boolean canApplyTogether(Enchantment par1Enchantment)
{
return this != par1Enchantment;
}
/**
* Sets the enchantment name
*/
public Enchantment setName(String par1Str)
{
this.name = par1Str;
return this;
}
/**
* Return the name of key in translation table of this enchantment.
*/
public String getName()
{
return "enchantment." + this.name;
}
/**
* Returns the correct traslated name of the enchantment and the level in roman numbers.
*/
public String getTranslatedName(int par1)
{
String var2 = StatCollector.translateToLocal(this.getName());
return var2 + " " + StatCollector.translateToLocal("enchantment.level." + par1);
}
public boolean canApply(ItemStack par1ItemStack)
{
return this.type.canEnchantItem(par1ItemStack.getItem());
}
public void func_151368_a(EntityLivingBase p_151368_1_, Entity p_151368_2_, int p_151368_3_) {}
public void func_151367_b(EntityLivingBase p_151367_1_, Entity p_151367_2_, int p_151367_3_) {}
static
{
ArrayList var0 = new ArrayList();
Enchantment[] var1 = enchantmentsList;
int var2 = var1.length;
for (int var3 = 0; var3 < var2; ++var3)
{
Enchantment var4 = var1[var3];
if (var4 != null)
{
var0.add(var4);
}
}
enchantmentsBookList = (Enchantment[])var0.toArray(new Enchantment[0]);
}
}
|
/**
* Created by IntelliJ IDEA
*
* @author robin
* @create 2019/1/30 01:53
*/
package com.SegmentTree;
/**
* Created by robin on 2019/1/30.
*/
public class SegmentTree<E> {
public E[] tree;
public E[] data;
private Merger<E> merger;
public SegmentTree(E[] arr, Merger<E> merger){
this.merger = merger;
data = (E[]) new Object[arr.length];
for (int i = 0; i < arr.length; i++) {
data[i] = arr[i];
}
tree = (E[]) new Object[4 * arr.length];
buildSegmentTree(0, 0, data.length - 1);
}
private void buildSegmentTree(int treeIndex, int l, int r) {
if(l == r){
tree[treeIndex] = data[l];
return;
}
int leftTreeIndex = leftChild(treeIndex);
int rightTreeIndex = rightChild(treeIndex);
int mid = l + (r - l) / 2;
buildSegmentTree(leftTreeIndex, l, mid);
buildSegmentTree(rightTreeIndex, mid + 1, r);
tree[treeIndex] = merger.merge(tree[leftTreeIndex] , tree[rightTreeIndex]);
}
public int getSize(){
return data.length;
}
public E get(int index){
if(index < 0 || index >= data.length)
throw new IllegalArgumentException("Index is illegal.");
return data[index];
}
private int leftChild(int index){
return 2*index + 1;
}
private int rightChild(int index){
return 2*index + 2;
}
public E query(int queryL, int queryR){
if(queryL < 0 || queryL >= data.length || queryR < 0 || queryR >= data.length || queryL > queryR)
throw new IllegalArgumentException("Index is illegal.");
return query(0, 0, data.length-1, queryL, queryR);
}
private E query(int treeIndex, int l ,int r, int queryL, int queryR) {
if(l == queryL && r == queryR)
return tree[treeIndex];
int mid = l + (r - l) / 2;
int leftTreeIndex = leftChild(treeIndex);
int rightTreeIndex = rightChild(treeIndex);
if(queryL > mid + 1)
return query(rightTreeIndex, mid + 1, r, queryL, queryR);
else if(queryR <= mid)
return query(leftTreeIndex, l, mid, queryL, queryR);
E leftResult = query(leftTreeIndex, l, mid, queryL, mid);
E rightResult = query(rightTreeIndex, mid + 1, r, mid + 1, queryR);
return merger.merge(leftResult, rightResult);
}
public void set(int index, E e){
if(index < 0 || index >= data.length)
throw new IllegalArgumentException("Index is illegal");
data[index] = e;
set(0, 0, data.length - 1, index, e);
}
private void set(int treeIndex, int l, int r, int index, E e) {
if(l == r){
tree[treeIndex] = e;
return;
}
int mid = l + (r - l) / 2;
int leftTreeIndex = leftChild(treeIndex);
int rightTreeIndex = rightChild(treeIndex);
if(index >= mid + 1)
set(rightTreeIndex, mid + 1, r, index, e);
else
set(leftTreeIndex, l, mid, index, e);
tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("[");
for (int i = 0; i < tree.length; i++) {
if(tree[i] != null)
res.append(tree[i]);
else
res.append("null");
if(i != tree.length - 1)
res.append(", ");
}
res.append("]");
return res.toString();
}
}
|
package com.planet_ink.coffee_mud.core.collections;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
/*
Copyright 2010-2021 Bo Zimmerman
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.
*/
public class STreeMap<K,V> implements Serializable, Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>
{
private static final long serialVersionUID = -6713012858839312626L;
private volatile TreeMap<K,V> T;
public STreeMap()
{
T=new TreeMap<K,V>();
}
public STreeMap(final Comparator<K> comp)
{
T=new TreeMap<K,V>(comp);
}
public STreeMap(final Map<K,V> E)
{
T=new TreeMap<K,V>();
if(E!=null)
for(final K o : E.keySet())
put(o,E.get(o));
}
@SuppressWarnings("unchecked")
public synchronized TreeMap<K,V> toTreeMap()
{
return (TreeMap<K,V>)T.clone();
}
public synchronized Vector<String> toStringVector(final String divider)
{
final Vector<String> V=new Vector<String>(size());
for(final Object S : navigableKeySet())
{
if(S!=null)
{
final Object O = get(S);
if(O==null)
V.add(S.toString() + divider);
else
V.add(S.toString() + divider + O.toString());
}
}
return V;
}
@Override
public synchronized java.util.Map.Entry<K, V> ceilingEntry(final K key)
{
return T.ceilingEntry(key);
}
@Override
public synchronized K ceilingKey(final K key)
{
return T.ceilingKey(key);
}
@SuppressWarnings("unchecked")
@Override
public synchronized void clear()
{
T=(TreeMap<K,V>)T.clone();
T.clear();
}
@SuppressWarnings("unchecked")
public synchronized STreeMap<K,V> copyOf()
{
final STreeMap<K,V> SH=new STreeMap<K,V>();
SH.T=(TreeMap<K,V>)T.clone();
return SH;
}
@Override
public synchronized Comparator<? super K> comparator()
{
return T.comparator();
}
@Override
public synchronized boolean containsKey(final Object key)
{
return T.containsKey(key);
}
@Override
public synchronized boolean containsValue(final Object value)
{
return T.containsValue(value);
}
@Override
public synchronized NavigableSet<K> descendingKeySet()
{
return new ReadOnlyNavigableSet<K>(T.descendingKeySet());
}
@Override
public synchronized NavigableMap<K, V> descendingMap()
{
return new ReadOnlyNavigableMap<K,V>(T.descendingMap());
}
@Override
public synchronized Set<java.util.Map.Entry<K, V>> entrySet()
{
return new ReadOnlySet<java.util.Map.Entry<K, V>>(T.entrySet());
}
@Override
public synchronized java.util.Map.Entry<K, V> firstEntry()
{
return T.firstEntry();
}
@Override
public synchronized K firstKey()
{
return T.firstKey();
}
@Override
public synchronized java.util.Map.Entry<K, V> floorEntry(final K key)
{
return T.floorEntry(key);
}
@Override
public synchronized K floorKey(final K key)
{
return T.floorKey(key);
}
@Override
public synchronized V get(final Object key)
{
return T.get(key);
}
@Override
public synchronized NavigableMap<K, V> headMap(final K toKey, final boolean inclusive)
{
return new ReadOnlyNavigableMap<K,V>(T.headMap(toKey, inclusive));
}
@Override
public synchronized SortedMap<K, V> headMap(final K toKey)
{
return new ReadOnlySortedMap<K,V>(T.headMap(toKey));
}
@Override
public synchronized java.util.Map.Entry<K, V> higherEntry(final K key)
{
return T.higherEntry(key);
}
@Override
public synchronized K higherKey(final K key)
{
return T.higherKey(key);
}
@Override
public synchronized Set<K> keySet()
{
return new ReadOnlySet<K>(T.keySet());
}
@Override
public synchronized java.util.Map.Entry<K, V> lastEntry()
{
return T.lastEntry();
}
@Override
public synchronized K lastKey()
{
return T.lastKey();
}
@Override
public synchronized java.util.Map.Entry<K, V> lowerEntry(final K key)
{
return T.lowerEntry(key);
}
@Override
public synchronized K lowerKey(final K key)
{
return T.lowerKey(key);
}
@Override
public synchronized NavigableSet<K> navigableKeySet()
{
return new ReadOnlyNavigableSet<K>(T.navigableKeySet());
}
@SuppressWarnings("unchecked")
@Override
public synchronized java.util.Map.Entry<K, V> pollFirstEntry()
{
T=(TreeMap<K,V>)T.clone();
return T.pollFirstEntry();
}
@SuppressWarnings("unchecked")
@Override
public synchronized java.util.Map.Entry<K, V> pollLastEntry()
{
T=(TreeMap<K,V>)T.clone();
return T.pollLastEntry();
}
@SuppressWarnings("unchecked")
@Override
public synchronized V put(final K key, final V value)
{
T=(TreeMap<K,V>)T.clone();
return T.put(key, value);
}
@SuppressWarnings("unchecked")
@Override
public synchronized void putAll(final Map<? extends K, ? extends V> map)
{
T=(TreeMap<K,V>)T.clone();
T.putAll(map);
}
@SuppressWarnings("unchecked")
@Override
public synchronized V remove(final Object key)
{
T=(TreeMap<K,V>)T.clone();
return T.remove(key);
}
@Override
public synchronized int size()
{
return T.size();
}
@Override
public synchronized NavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey,
final boolean toInclusive)
{
return new ReadOnlyNavigableMap<K,V>(T.subMap(fromKey, fromInclusive, toKey, toInclusive));
}
@Override
public synchronized SortedMap<K, V> subMap(final K fromKey, final K toKey)
{
return new ReadOnlySortedMap<K,V>(T.subMap(fromKey, toKey));
}
@Override
public synchronized NavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive)
{
return new ReadOnlyNavigableMap<K, V>(T.tailMap(fromKey, inclusive));
}
@Override
public synchronized SortedMap<K, V> tailMap(final K fromKey)
{
return new ReadOnlySortedMap<K, V>(T.tailMap(fromKey));
}
@Override
public synchronized Collection<V> values()
{
return new ReadOnlyCollection<V>(T.values());
}
@Override
public boolean equals(final Object o)
{
return this==o;
}
@Override
public int hashCode()
{
return super.hashCode();
}
@Override
public synchronized boolean isEmpty()
{
return T.isEmpty();
}
@Override
public String toString()
{
return super.toString();
}
}
|
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package istata.interact.model;
public class StataVar {
private String name;
private String type;
private String format;
private String valueLabel;
private boolean hasNotes;
private String label;
public StataVar(String describe) {
// System.out.println(describe);
this.name = describe.replaceFirst("(^\\S*?)\\s(.*?)$", "$1");
// System.out.println(name);
describe = describe.substring(this.name.length()).trim();
int len = describe.length();
int start = 0;
int end = 7;
this.type = describe.substring(0, 7).trim();
start = end;
end = Math.min(19, len);
this.format = describe.substring(start, end).trim();
start = end;
end = Math.min(27, len);
this.valueLabel = describe.substring(start, end).trim();
start = end;
end = Math.min(30, len);
this.hasNotes = (describe.substring(start, end).trim().equals(". *"));
start = end;
this.label = describe.substring(start);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getValueLabel() {
return valueLabel;
}
public void setValueLabel(String valueLabel) {
this.valueLabel = valueLabel;
}
public boolean isHasNotes() {
return hasNotes;
}
public void setHasNotes(boolean hasNotes) {
this.hasNotes = hasNotes;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Override
public String toString() {
return name + "|\t|" + type + "|\t|" + format + "|\t|" + valueLabel
+ "|\t|" + hasNotes + "|\t|" + label;
}
}
|
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.AbstractIntegrationTest;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class AppNamespaceRepositoryTest extends AbstractIntegrationTest {
@Autowired
private AppNamespaceRepository repository;
@Test
public void testFindByNameAndIsPublicTrue() throws Exception {
AppNamespace appNamespace = repository.findByNameAndIsPublicTrue("fx.apollo.config");
assertEquals("100003171", appNamespace.getAppId());
}
@Test
public void testFindByNameAndNoPublicNamespace() throws Exception {
AppNamespace appNamespace = repository.findByNameAndIsPublicTrue("application");
assertNull(appNamespace);
}
}
|
/*
* Copyright (c) [2016-2018] [University of Minnesota]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.grouplens.samantha.server.common;
import org.grouplens.samantha.server.io.RequestContext;
interface ModelOperator {
Object operate(ModelManager modelManager, RequestContext requestContext);
}
|
package com.wut.model.scalar;
public class EmailData extends ScalarData {
private String data;
public EmailData(String string) {
this.data = string;
}
@Override
public String toRawString() {
return data;
}
@Override
public void fromRawString(String str) {
data = str;
}
}
|
package dev.voidframework.template.freemarker.method;
import com.typesafe.config.Config;
import freemarker.template.SimpleNumber;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateSequenceModel;
import java.util.Collection;
import java.util.List;
/**
* FreeMarker method: retrieve value from the configuration into the template.
*/
public class ConfigTemplateMethodModel implements TemplateMethodModelEx {
private final Config configuration;
/**
* Build a new instance.
*
* @param configuration The application configuration
*/
public ConfigTemplateMethodModel(final Config configuration) {
this.configuration = configuration;
}
@Override
public TemplateModel exec(final List args) throws TemplateModelException {
if (args.size() != 1) {
throw new TemplateModelException("Wrong arguments");
}
final Object value = this.configuration.getAnyRef(((SimpleScalar) args.get(0)).getAsString());
if (value instanceof String) {
return new SimpleScalar((String) value);
} else if (value instanceof Number) {
return new SimpleNumber((Number) value);
} else if (value instanceof Boolean) {
return (Boolean) value ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
} else if (value instanceof Collection<?>) {
return new TemplateSequenceModel() {
private final List<?> valueList = ((Collection<?>) value).stream().toList();
@Override
public TemplateModel get(final int index) {
final Object obj = valueList.get(index);
if (obj instanceof String) {
return new SimpleScalar((String) obj);
} else if (obj instanceof Number) {
return new SimpleNumber((Number) obj);
} else if (obj instanceof Boolean) {
return (Boolean) obj ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
} else {
return obj == null ? null : new SimpleScalar(obj.toString());
}
}
@Override
public int size() {
return valueList.size();
}
};
} else {
return value == null ? null : new SimpleScalar(value.toString());
}
}
}
|
//statement
byte[] a = new byte[] {1, 2, 3};
|
package io.opensphere.myplaces.controllers;
import java.awt.Component;
import java.util.Collections;
import java.util.List;
import io.opensphere.core.Toolbox;
import io.opensphere.core.control.action.ContextMenuProvider;
import io.opensphere.core.util.collections.New;
import io.opensphere.mantle.data.CategoryContextKey;
import io.opensphere.mantle.data.DataTypeInfo;
import io.opensphere.myplaces.constants.Constants;
import io.opensphere.myplaces.models.MyPlacesModel;
/**
* Provides the context menu for group modifications.
*
*/
public class CategoryContextMenuProvider implements ContextMenuProvider<CategoryContextKey>
{
/**
* The toolbox.
*/
private final Toolbox myToolbox;
/**
* The places model.
*/
private final MyPlacesModel myModel;
/**
* Constructs a new points context menu provider.
*
* @param toolbox The toolbox.
* @param model The my places model.
*/
public CategoryContextMenuProvider(Toolbox toolbox, MyPlacesModel model)
{
myToolbox = toolbox;
myModel = model;
}
@Override
public List<? extends Component> getMenuItems(String contextId, final CategoryContextKey key)
{
List<Component> menuItems;
if (Constants.MY_PLACES_LABEL.equals(key.getCategory()))
{
menuItems = New.list(2);
menuItems.add(new CreateFolderMenuItem(myToolbox, myModel.getDataGroups()));
menuItems.add(new ExportMenu(myToolbox, Collections.singletonList(myModel.getDataGroups()),
Collections.<DataTypeInfo>emptyList()));
}
else
{
menuItems = Collections.emptyList();
}
return menuItems;
}
@Override
public int getPriority()
{
return 4;
}
}
|
/*
* 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 lk.ijse.pos.controller;
import com.sun.javafx.scene.control.skin.TableViewSkinBase;
import lk.ijse.pos.business.BOFactory;
import lk.ijse.pos.business.BOTypes;
import lk.ijse.pos.business.custom.CustomerBO;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import lk.ijse.pos.dto.CustomerDTO;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import lk.ijse.pos.main.AppInitializer;
import lk.ijse.pos.util.CustomerTM;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* FXML Controller class
*
* @author ranjith-suranga
*/
public class ManageCustomerFormController implements Initializable {
@FXML
private JFXButton btnSave;
@FXML
private JFXButton btnDelete;
@FXML
private AnchorPane root;
@FXML
private JFXTextField txtCustomerId;
@FXML
private JFXTextField txtCustomerName;
@FXML
private JFXTextField txtCustomerAddress;
@FXML
private TableView<CustomerTM> tblCustomers;
private CustomerBO customerBO = BOFactory.getInstance().getBO(BOTypes.CUSTOMER);
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
tblCustomers.getColumns().get(0).setStyle("-fx-alignment:center");
tblCustomers.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("id"));
tblCustomers.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("name"));
tblCustomers.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("address"));
btnSave.setDisable(true);
btnDelete.setDisable(true);
try {
List<CustomerDTO> allCustomers = customerBO.getAllCustomers();
for (CustomerDTO customer : allCustomers) {
tblCustomers.getItems().add(new CustomerTM(customer.getId(), customer.getName(), customer.getAddress()));
}
} catch (Exception ex) {
Logger.getLogger("lk.ijse.pos.controller").log(Level.SEVERE, null,ex);
}
tblCustomers.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<CustomerTM>() {
@Override
public void changed(ObservableValue<? extends CustomerTM> observable, CustomerTM oldValue, CustomerTM selectedCustomer) {
if (selectedCustomer == null) {
// Clear Selection
return;
}
txtCustomerId.setText(selectedCustomer.getId());
txtCustomerName.setText(selectedCustomer.getName());
txtCustomerAddress.setText(selectedCustomer.getAddress());
txtCustomerId.setEditable(false);
btnSave.setDisable(false);
btnDelete.setDisable(false);
}
});
}
@FXML
private void navigateToHome(MouseEvent event) throws IOException {
AppInitializer.navigateToHome(root, (Stage) this.root.getScene().getWindow());
}
@FXML
private void btnSave_OnAction(ActionEvent event) {
if (txtCustomerId.getText().trim().isEmpty()) {
new Alert(Alert.AlertType.ERROR, "CustomerTM ID is empty", ButtonType.OK).showAndWait();
txtCustomerId.requestFocus();
return;
} else if (txtCustomerName.getText().trim().isEmpty()) {
new Alert(Alert.AlertType.ERROR, "CustomerTM Name is empty", ButtonType.OK).showAndWait();
txtCustomerName.requestFocus();
return;
} else if (txtCustomerAddress.getText().trim().isEmpty()) {
new Alert(Alert.AlertType.ERROR, "CustomerTM Address is empty", ButtonType.OK).showAndWait();
txtCustomerAddress.requestFocus();
return;
}
if (tblCustomers.getSelectionModel().isEmpty()) {
// New
ObservableList<CustomerTM> items = tblCustomers.getItems();
for (CustomerTM customerTM : items) {
if (customerTM.getId().equals(txtCustomerId.getText())) {
new Alert(Alert.AlertType.ERROR, "Duplicate CustomerTM IDs are not allowed").showAndWait();
txtCustomerId.requestFocus();
return;
}
}
CustomerDTO customerDTO = new CustomerDTO(txtCustomerId.getText(), txtCustomerName.getText(), txtCustomerAddress.getText());
try {
boolean result = customerBO.saveCustomer(customerDTO);
if (result) {
new Alert(Alert.AlertType.INFORMATION, "Customer has been saved successfully", ButtonType.OK).showAndWait();
CustomerTM customerTM = new CustomerTM(txtCustomerId.getText(), txtCustomerName.getText(), txtCustomerAddress.getText());
tblCustomers.getItems().add(customerTM);
tblCustomers.scrollTo(customerTM);
} else {
new Alert(Alert.AlertType.ERROR, "Failed to save the customer, try again", ButtonType.OK).showAndWait();
}
} catch (Exception e) {
Logger.getLogger("lk.ijse.pos.controller").log(Level.SEVERE, null,e);
}
} else {
// Update
try {
boolean result = customerBO.updateCustomer(new CustomerDTO(txtCustomerId.getText(), txtCustomerName.getText(), txtCustomerAddress.getText()));
if (result) {
new Alert(Alert.AlertType.INFORMATION, "Customer has been updated successfully").show();
CustomerTM selectedCustomer = tblCustomers.getSelectionModel().getSelectedItem();
selectedCustomer.setName(txtCustomerName.getText());
selectedCustomer.setAddress(txtCustomerAddress.getText());
tblCustomers.getProperties().put(TableViewSkinBase.RECREATE,Boolean.TRUE);
} else {
new Alert(Alert.AlertType.ERROR, "Failed to update the customer, try again").show();
}
} catch (Exception e) {
Logger.getLogger("lk.ijse.pos.controller").log(Level.SEVERE, null,e);
}
}
reset();
}
@FXML
private void btnDelete_OnAction(ActionEvent event) {
Alert confirmMsg = new Alert(Alert.AlertType.CONFIRMATION, "Are you sure to delete this customer?", ButtonType.YES, ButtonType.NO);
Optional<ButtonType> buttonType = confirmMsg.showAndWait();
if (buttonType.get() == ButtonType.YES) {
int selectedRow = tblCustomers.getSelectionModel().getSelectedIndex();
try {
boolean result = customerBO.removeCustomer(txtCustomerId.getText());
if (result) {
tblCustomers.getItems().remove(tblCustomers.getSelectionModel().getSelectedItem());
reset();
} else {
new Alert(Alert.AlertType.ERROR, "Failed to delete the customer, try again").show();
}
} catch (Exception e) {
Logger.getLogger("lk.ijse.pos.controller").log(Level.SEVERE, null,e);
}
}
}
@FXML
private void btnAddNew_OnAction(ActionEvent actionEvent) {
reset();
}
private void reset() {
txtCustomerId.clear();
txtCustomerName.clear();
txtCustomerAddress.clear();
txtCustomerId.requestFocus();
txtCustomerId.setEditable(true);
btnSave.setDisable(false);
btnDelete.setDisable(true);
tblCustomers.getSelectionModel().clearSelection();
}
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.security.transport.netty4;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.PageCacheRecycler;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.ConnectionProfile;
import org.elasticsearch.transport.TcpChannel;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportSettings;
import org.elasticsearch.xpack.security.transport.AbstractSimpleSecurityTransportTestCase;
import java.util.Collections;
public class SimpleSecurityNetty4ServerTransportTests extends AbstractSimpleSecurityTransportTestCase {
public MockTransportService nettyFromThreadPool(Settings settings, ThreadPool threadPool, final Version version,
ClusterSettings clusterSettings, boolean doHandshake) {
NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(Collections.emptyList());
NetworkService networkService = new NetworkService(Collections.emptyList());
Settings settings1 = Settings.builder()
.put(settings)
.put("xpack.security.transport.ssl.enabled", true).build();
Transport transport = new SecurityNetty4ServerTransport(settings1, version, threadPool,
networkService, PageCacheRecycler.NON_RECYCLING_INSTANCE, namedWriteableRegistry,
new NoneCircuitBreakerService(), null, createSSLService(settings1)) {
@Override
public void executeHandshake(DiscoveryNode node, TcpChannel channel, ConnectionProfile profile,
ActionListener<Version> listener) {
if (doHandshake) {
super.executeHandshake(node, channel, profile, listener);
} else {
listener.onResponse(version.minimumCompatibilityVersion());
}
}
};
MockTransportService mockTransportService =
MockTransportService.createNewService(settings, transport, version, threadPool, clusterSettings,
Collections.emptySet());
mockTransportService.start();
return mockTransportService;
}
@Override
protected MockTransportService build(Settings settings, Version version, ClusterSettings clusterSettings, boolean doHandshake) {
if (TransportSettings.PORT.exists(settings) == false) {
settings = Settings.builder().put(settings)
.put(TransportSettings.PORT.getKey(), "0")
.build();
}
MockTransportService transportService = nettyFromThreadPool(settings, threadPool, version, clusterSettings, doHandshake);
transportService.start();
return transportService;
}
}
|
package org.apache.http.impl.client.cache;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
@Immutable
class ResponseProtocolCompliance {
private static final String UNEXPECTED_100_CONTINUE = "The incoming request did not contain a 100-continue header, but the response was a Status 100, continue.";
private static final String UNEXPECTED_PARTIAL_CONTENT = "partial content was returned for a request that did not ask for it";
ResponseProtocolCompliance() {
}
private boolean backendResponseMustNotHaveBody(HttpRequest httpRequest, HttpResponse httpResponse) {
return "HEAD".equals(httpRequest.getRequestLine().getMethod()) || httpResponse.getStatusLine().getStatusCode() == 204 || httpResponse.getStatusLine().getStatusCode() == 205 || httpResponse.getStatusLine().getStatusCode() == 304;
}
private void consumeBody(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
IOUtils.consume(entity);
}
}
private void ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(HttpRequest httpRequest, HttpResponse httpResponse) {
if (httpRequest.getRequestLine().getMethod().equalsIgnoreCase("OPTIONS") && httpResponse.getStatusLine().getStatusCode() == 200 && httpResponse.getFirstHeader("Content-Length") == null) {
httpResponse.addHeader("Content-Length", "0");
}
}
private void ensure206ContainsDateHeader(HttpResponse httpResponse) {
if (httpResponse.getFirstHeader("Date") == null) {
httpResponse.addHeader("Date", DateUtils.formatDate(new Date()));
}
}
private void ensure304DoesNotContainExtraEntityHeaders(HttpResponse httpResponse) {
String[] strArr = {"Allow", "Content-Encoding", HttpHeaders.CONTENT_LANGUAGE, "Content-Length", HttpHeaders.CONTENT_MD5, "Content-Range", "Content-Type", "Last-Modified"};
if (httpResponse.getStatusLine().getStatusCode() == 304) {
for (String removeHeaders : strArr) {
httpResponse.removeHeaders(removeHeaders);
}
}
}
private void ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(HttpRequest httpRequest, HttpResponse httpResponse) throws IOException {
if (httpRequest.getFirstHeader("Range") == null && httpResponse.getStatusLine().getStatusCode() == 206) {
consumeBody(httpResponse);
throw new ClientProtocolException(UNEXPECTED_PARTIAL_CONTENT);
}
}
private void identityIsNotUsedInContentEncoding(HttpResponse httpResponse) {
Header[] headers = httpResponse.getHeaders("Content-Encoding");
if (headers != null && headers.length != 0) {
ArrayList<Header> arrayList = new ArrayList<>();
boolean z = false;
for (Header elements : headers) {
StringBuilder sb = new StringBuilder();
boolean z2 = true;
for (HeaderElement headerElement : elements.getElements()) {
if (HTTP.IDENTITY_CODING.equalsIgnoreCase(headerElement.getName())) {
z = true;
} else {
if (!z2) {
sb.append(",");
}
sb.append(headerElement.toString());
z2 = false;
}
}
String sb2 = sb.toString();
if (!"".equals(sb2)) {
arrayList.add(new BasicHeader("Content-Encoding", sb2));
}
}
if (z) {
httpResponse.removeHeaders("Content-Encoding");
for (Header addHeader : arrayList) {
httpResponse.addHeader(addHeader);
}
}
}
}
private void removeResponseTransferEncoding(HttpResponse httpResponse) {
httpResponse.removeHeaders(HttpHeaders.TE);
httpResponse.removeHeaders("Transfer-Encoding");
}
private void requestDidNotExpect100ContinueButResponseIsOne(HttpRequestWrapper httpRequestWrapper, HttpResponse httpResponse) throws IOException {
if (httpResponse.getStatusLine().getStatusCode() == 100) {
HttpRequest original = httpRequestWrapper.getOriginal();
if (!(original instanceof HttpEntityEnclosingRequest) || !((HttpEntityEnclosingRequest) original).expectContinue()) {
consumeBody(httpResponse);
throw new ClientProtocolException(UNEXPECTED_100_CONTINUE);
}
}
}
private void transferEncodingIsNotReturnedTo1_0Client(HttpRequestWrapper httpRequestWrapper, HttpResponse httpResponse) {
if (httpRequestWrapper.getOriginal().getProtocolVersion().compareToVersion(HttpVersion.HTTP_1_1) < 0) {
removeResponseTransferEncoding(httpResponse);
}
}
private void warningsWithNonMatchingWarnDatesAreRemoved(HttpResponse httpResponse) {
Header[] headers;
Date parseDate = DateUtils.parseDate(httpResponse.getFirstHeader("Date").getValue());
if (parseDate != null && (headers = httpResponse.getHeaders("Warning")) != null && headers.length != 0) {
ArrayList<Header> arrayList = new ArrayList<>();
boolean z = false;
for (Header warningValues : headers) {
for (WarningValue warningValue : WarningValue.getWarningValues(warningValues)) {
Date warnDate = warningValue.getWarnDate();
if (warnDate == null || warnDate.equals(parseDate)) {
arrayList.add(new BasicHeader("Warning", warningValue.toString()));
} else {
z = true;
}
}
}
if (z) {
httpResponse.removeHeaders("Warning");
for (Header addHeader : arrayList) {
httpResponse.addHeader(addHeader);
}
}
}
}
public void ensureProtocolCompliance(HttpRequestWrapper httpRequestWrapper, HttpResponse httpResponse) throws IOException {
if (backendResponseMustNotHaveBody(httpRequestWrapper, httpResponse)) {
consumeBody(httpResponse);
httpResponse.setEntity((HttpEntity) null);
}
requestDidNotExpect100ContinueButResponseIsOne(httpRequestWrapper, httpResponse);
transferEncodingIsNotReturnedTo1_0Client(httpRequestWrapper, httpResponse);
ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(httpRequestWrapper, httpResponse);
ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(httpRequestWrapper, httpResponse);
ensure206ContainsDateHeader(httpResponse);
ensure304DoesNotContainExtraEntityHeaders(httpResponse);
identityIsNotUsedInContentEncoding(httpResponse);
warningsWithNonMatchingWarnDatesAreRemoved(httpResponse);
}
}
|
package pro.ghosh.sudipto.personInterface;
public interface Person {
/**
* Display Method
*/
void display();
/**
* Registration Method
*/
void register();
}
|
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.healthcare.v1beta1.model;
/**
* Lists the Consents in the given Consent store.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Healthcare API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ListConsentsResponse extends com.google.api.client.json.GenericJson {
/**
* The returned consents. The maximum number of consents returned is determined by the value of
* page_size in the ListConsentsRequest.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Consent> consents;
static {
// hack to force ProGuard to consider Consent used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(Consent.class);
}
/**
* Token to retrieve the next page of results or empty if there are no more results in the list.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextPageToken;
/**
* The returned consents. The maximum number of consents returned is determined by the value of
* page_size in the ListConsentsRequest.
* @return value or {@code null} for none
*/
public java.util.List<Consent> getConsents() {
return consents;
}
/**
* The returned consents. The maximum number of consents returned is determined by the value of
* page_size in the ListConsentsRequest.
* @param consents consents or {@code null} for none
*/
public ListConsentsResponse setConsents(java.util.List<Consent> consents) {
this.consents = consents;
return this;
}
/**
* Token to retrieve the next page of results or empty if there are no more results in the list.
* @return value or {@code null} for none
*/
public java.lang.String getNextPageToken() {
return nextPageToken;
}
/**
* Token to retrieve the next page of results or empty if there are no more results in the list.
* @param nextPageToken nextPageToken or {@code null} for none
*/
public ListConsentsResponse setNextPageToken(java.lang.String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
@Override
public ListConsentsResponse set(String fieldName, Object value) {
return (ListConsentsResponse) super.set(fieldName, value);
}
@Override
public ListConsentsResponse clone() {
return (ListConsentsResponse) super.clone();
}
}
|
/*
* Copyright 2002-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
*
* 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.aop.aspectj;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aop.framework.Advised;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.Serializable;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Adrian Colyer
* @author Chris Beams
*/
public class SubtypeSensitiveMatchingTests {
private NonSerializableFoo nonSerializableBean;
private SerializableFoo serializableBean;
private Bar bar;
@BeforeEach
public void setup() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
nonSerializableBean = (NonSerializableFoo) ctx.getBean("testClassA");
serializableBean = (SerializableFoo) ctx.getBean("testClassB");
bar = (Bar) ctx.getBean("testClassC");
}
@Test
public void testBeansAreProxiedOnStaticMatch() {
boolean condition = this.serializableBean instanceof Advised;
assertThat(condition).as("bean with serializable type should be proxied").isTrue();
}
@Test
public void testBeansThatDoNotMatchBasedSolelyOnRuntimeTypeAreNotProxied() {
boolean condition = this.nonSerializableBean instanceof Advised;
assertThat(condition).as("bean with non-serializable type should not be proxied").isFalse();
}
@Test
public void testBeansThatDoNotMatchBasedOnOtherTestAreProxied() {
boolean condition = this.bar instanceof Advised;
assertThat(condition).as("bean with args check should be proxied").isTrue();
}
}
//strange looking interfaces are just to set up certain test conditions...
interface NonSerializableFoo { void foo(); }
interface SerializableFoo extends Serializable { void foo(); }
class SubtypeMatchingTestClassA implements NonSerializableFoo {
@Override
public void foo() {}
}
@SuppressWarnings("serial")
class SubtypeMatchingTestClassB implements SerializableFoo {
@Override
public void foo() {}
}
interface Bar { void bar(Object o); }
class SubtypeMatchingTestClassC implements Bar {
@Override
public void bar(Object o) {}
}
|
/*
* Copyright (C) 2012 Red Hat, Inc. (jcasey@redhat.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.commonjava.maven.ext.core.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.Exclusion;
import org.apache.maven.model.Model;
import org.apache.maven.model.Profile;
import org.commonjava.maven.atlas.ident.ref.ArtifactRef;
import org.commonjava.maven.atlas.ident.ref.InvalidRefException;
import org.commonjava.maven.atlas.ident.ref.ProjectRef;
import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef;
import org.commonjava.maven.atlas.ident.ref.SimpleArtifactRef;
import org.commonjava.maven.atlas.ident.ref.SimpleProjectRef;
import org.commonjava.maven.ext.common.ManipulationException;
import org.commonjava.maven.ext.common.model.Project;
import org.commonjava.maven.ext.core.ManipulationSession;
import org.commonjava.maven.ext.core.state.CommonState;
import org.commonjava.maven.ext.core.state.DependencyState;
import org.commonjava.maven.ext.core.state.DependencyState.DependencyPrecedence;
import org.commonjava.maven.ext.core.state.RESTState;
import org.commonjava.maven.ext.core.util.PropertiesUtils;
import org.commonjava.maven.ext.core.util.PropertyMapper;
import org.commonjava.maven.ext.core.util.WildcardMap;
import org.commonjava.maven.ext.io.ModelIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.join;
import static org.commonjava.maven.ext.core.util.IdUtils.ga;
/**
* {@link Manipulator} implementation that can alter dependency (and dependency management) sections in a project's pom file.
* Configuration is stored in a {@link DependencyState} instance, which is in turn stored in the {@link ManipulationSession}.
*/
@Named("project-dependency-manipulator")
@Singleton
public class DependencyManipulator implements Manipulator
{
private final Logger logger = LoggerFactory.getLogger( getClass() );
/**
* Used to store mappings of old property to new version for explicit overrides.
*/
private final Map<Project,Map<String, PropertyMapper>> explicitVersionPropertyUpdateMap = new LinkedHashMap<>();
/**
* Used to store mappings of old property to new version - the new version is encapsulated within the {@link PropertyMapper}
* which also contains reference to the old version and the dependency that changed this. This allows complete tracking of
* dependencies that updated properties - and therefore, the inverse, dependencies that did NOT update the property. This can
* be problematic in the case of rebuilds.
*/
private final Map<Project,Map<String, PropertyMapper>> versionPropertyUpdateMap = new LinkedHashMap<>();
private ModelIO effectiveModelBuilder;
private ManipulationSession session;
@Inject
public DependencyManipulator(ModelIO effectiveModelBuilder)
{
this.effectiveModelBuilder = effectiveModelBuilder;
}
/**
* Initialize the {@link DependencyState} state holder in the {@link ManipulationSession}. This state holder detects
* version-change configuration from the Maven user properties (-D properties from the CLI) and makes it available for
* later.
*/
@Override
public void init( final ManipulationSession session ) throws ManipulationException
{
session.setState( new DependencyState( session.getUserProperties() ) );
this.session = session;
}
/**
* Apply the alignment changes to the list of {@link Project}'s given.
*/
@Override
public Set<Project> applyChanges( final List<Project> projects )
throws ManipulationException
{
final DependencyState state = session.getState( DependencyState.class );
if ( !session.isEnabled() || !state.isEnabled() )
{
logger.debug("{}: Nothing to do!", getClass().getSimpleName());
return Collections.emptySet();
}
return internalApplyChanges( projects, loadRemoteOverrides() );
}
/**
* This will load the remote overrides. It will first try to load any overrides that might have
* been prepopulated by the REST scanner, failing that it will load from a remote POM file.
*
* @return the loaded overrides
* @throws ManipulationException if an error occurs.
*/
private Map<ArtifactRef, String> loadRemoteOverrides() throws ManipulationException
{
final DependencyState depState = session.getState( DependencyState.class );
final RESTState restState = session.getState( RESTState.class );
final List<ProjectVersionRef> gavs = depState.getRemoteBOMDepMgmt();
final Map<String, ProjectVersionRef> extraGAVs = depState.getExtraBOMs();
final Map<String, Map<ProjectRef, String>> extraBOMOverrides = depState.getExtraBOMDepMgmts();
// While in theory we are only mapping ProjectRef -> NewVersion if we store key as ProjectRef we can't then have
// org.foo:foobar -> 1.2.0.redhat-2
// org.foo:foobar -> 2.0.0.redhat-2
// Which is useful for strictAlignment scenarios (although undefined for non-strict).
Map<ArtifactRef, String> restOverrides = depState.getRemoteRESTOverrides();
Map<ArtifactRef, String> bomOverrides = new LinkedHashMap<>();
Map<ArtifactRef, String> mergedOverrides = new LinkedHashMap<>();
if ( gavs != null )
{
final ListIterator<ProjectVersionRef> iter = gavs.listIterator( gavs.size() );
// Iterate in reverse order so that the first GAV in the list overwrites the last
while ( iter.hasPrevious() )
{
final ProjectVersionRef ref = iter.previous();
Map<ArtifactRef, String> rBom = effectiveModelBuilder.getRemoteDependencyVersionOverrides( ref );
// We don't normalise the BOM list here as ::applyOverrides can handle multiple GA with different V
// for strict override. However, it is undefined if strict is not enabled.
bomOverrides.putAll( rBom );
}
}
// Load extra BOMs into seperate maps for accessing later, when applying the dependencyExclusions.
for ( Map.Entry<String, ProjectVersionRef> entry : extraGAVs.entrySet() )
{
extraBOMOverrides.put( entry.getKey(),
effectiveModelBuilder.getRemoteDependencyVersionOverridesByProject( entry.getValue() ) );
}
if ( depState.getPrecedence() == DependencyPrecedence.BOM )
{
mergedOverrides = bomOverrides;
if ( mergedOverrides.isEmpty() )
{
String msg = restState.isEnabled() ? "dependencySource for restURL" : "dependencyManagement";
logger.warn( "No dependencies found for dependencySource {}. Has {} been configured? ", depState.getPrecedence(), msg );
}
}
if ( depState.getPrecedence() == DependencyPrecedence.REST )
{
mergedOverrides = restOverrides;
if ( mergedOverrides.isEmpty() )
{
logger.warn( "No dependencies found for dependencySource {}. Has restURL been configured? ", depState.getPrecedence() );
}
}
else if ( depState.getPrecedence() == DependencyPrecedence.RESTBOM )
{
mergedOverrides = bomOverrides;
removeDuplicateArtifacts( mergedOverrides, restOverrides );
mergedOverrides.putAll( restOverrides );
}
else if ( depState.getPrecedence() == DependencyPrecedence.BOMREST )
{
mergedOverrides = restOverrides;
removeDuplicateArtifacts( mergedOverrides, bomOverrides );
mergedOverrides.putAll( bomOverrides );
}
logger.info ( "Remote precedence is {}", depState.getPrecedence() );
logger.debug ("Final remote override list is {}", mergedOverrides);
return mergedOverrides;
}
private void removeDuplicateArtifacts( Map<ArtifactRef, String> mergedOverrides, Map<ArtifactRef, String> targetOverrides )
{
Iterator<ArtifactRef> i = mergedOverrides.keySet().iterator();
while ( i.hasNext() )
{
ArtifactRef key = i.next();
ProjectRef pRef = key.asProjectRef();
for ( ArtifactRef target : targetOverrides.keySet() )
{
if ( pRef.equals( target.asProjectRef() ) )
{
logger.debug( "From source overrides artifact {} clashes with target {}", key, target );
i.remove();
break;
}
}
}
}
@Override
public int getExecutionIndex()
{
return 40;
}
private Set<Project> internalApplyChanges( final List<Project> projects, Map<ArtifactRef, String> overrides )
throws ManipulationException
{
final DependencyState state = session.getState( DependencyState.class );
final CommonState cState = session.getState( CommonState.class );
final Set<Project> result = new HashSet<>();
for ( final Project project : projects )
{
final Model model = project.getModel();
if (!overrides.isEmpty() || !state.getDependencyExclusions().isEmpty())
{
apply( project, model, overrides );
result.add( project );
}
}
// If we've changed something now update any old properties with the new values.
if (!result.isEmpty())
{
if ( cState.getStrictDependencyPluginPropertyValidation() > 0 )
{
logger.info( "Iterating to validate dependency updates..." );
for ( Project p : versionPropertyUpdateMap.keySet() )
{
validateDependenciesUpdatedProperty( cState, p, p.getResolvedManagedDependencies( session ) );
validateDependenciesUpdatedProperty( cState, p, p.getResolvedDependencies( session ) );
for ( Profile profile : p.getResolvedProfileDependencies( session ).keySet() )
{
validateDependenciesUpdatedProperty( cState, p, p.getResolvedProfileDependencies( session ).get( profile ) );
}
for ( Profile profile : p.getResolvedProfileManagedDependencies( session ).keySet() )
{
validateDependenciesUpdatedProperty( cState, p, p.getResolvedProfileManagedDependencies( session ).get( profile ) );
}
}
}
logger.info ("Iterating for standard overrides...");
for ( Project project : versionPropertyUpdateMap.keySet() )
{
logger.debug( "Checking property override within project {} ", project );
for ( final Map.Entry<String, PropertyMapper> entry : versionPropertyUpdateMap.get( project ).entrySet() )
{
PropertiesUtils.PropertyUpdate found =
PropertiesUtils.updateProperties( session, project, false,
entry.getKey(), entry.getValue().getNewVersion() );
if ( found == PropertiesUtils.PropertyUpdate.NOTFOUND )
{
// Problem in this scenario is that we know we have a property update map but we have not found a
// property to update. Its possible this property has been inherited from a parent. Override in the
// top pom for safety.
logger.info( "Unable to find a property for {} to update", entry.getKey() );
logger.info( "Adding property {} with {} ", entry.getKey(), entry.getValue().getNewVersion() );
// We know the inheritance root is at position 0 in the inherited list...
project.getInheritedList()
.get( 0 )
.getModel()
.getProperties()
.setProperty( entry.getKey(), entry.getValue().getNewVersion() );
}
}
}
logger.info ("Iterating for explicit overrides...");
for ( Project project : explicitVersionPropertyUpdateMap.keySet() )
{
logger.debug( "Checking property override within project {} ", project );
for ( final Map.Entry<String, PropertyMapper> entry : explicitVersionPropertyUpdateMap.get( project ).entrySet() )
{
PropertiesUtils.PropertyUpdate found =
PropertiesUtils.updateProperties( session, project, true,
entry.getKey(), entry.getValue().getNewVersion() );
if ( found == PropertiesUtils.PropertyUpdate.NOTFOUND )
{
// Problem in this scenario is that we know we have a property update map but we have not found a
// property to update. Its possible this property has been inherited from a parent. Override in the
// top pom for safety.
logger.info( "Unable to find a property for {} to update for explicit overrides", entry.getKey() );
logger.info( "Adding property {} with {} ", entry.getKey(), entry.getValue().getNewVersion() );
// We know the inheritance root is at position 0 in the inherited list...
project.getInheritedList()
.get( 0 )
.getModel()
.getProperties()
.setProperty( entry.getKey(), entry.getValue().getNewVersion() );
}
}
}
}
return result;
}
/**
* Applies dependency overrides to the project.
*/
private void apply( final Project project, final Model model, final Map<ArtifactRef, String> overrides )
throws ManipulationException
{
// Map of Group : Map of artifactId [ may be wildcard ] : value
final WildcardMap<String> explicitOverrides = new WildcardMap<>();
final String projectGA = ga( project );
final DependencyState dependencyState = session.getState( DependencyState.class );
final CommonState commonState = session.getState( CommonState.class );
logger.debug ("Processing project {} ", projectGA);
Map<ArtifactRef, String> moduleOverrides = new LinkedHashMap<>( overrides );
moduleOverrides = removeReactorGAs( moduleOverrides );
try
{
moduleOverrides = applyModuleVersionOverrides( projectGA,
dependencyState.getDependencyExclusions(),
moduleOverrides, explicitOverrides,
dependencyState.getExtraBOMDepMgmts() );
logger.debug( "Module overrides are:\n{}", moduleOverrides );
logger.debug( "Explicit overrides are:\n{}", explicitOverrides);
}
catch ( InvalidRefException e )
{
logger.error( "Invalid module exclusion override {} : {} ", moduleOverrides, explicitOverrides );
throw e;
}
if ( project.isInheritanceRoot() )
{
// Handle the situation where the top level parent refers to a prior build that is in the BOM.
if ( project.getModelParent() != null)
{
for ( Map.Entry<ArtifactRef, String> entry : moduleOverrides.entrySet() )
{
String oldValue = project.getModelParent().getVersion();
String newValue = entry.getValue();
if ( entry.getKey().asProjectRef().equals( SimpleProjectRef.parse( ga(project.getModelParent()) ) ))
{
if ( commonState.isStrict() )
{
if ( !PropertiesUtils.checkStrictValue( session, oldValue, newValue ) )
{
if ( commonState.isFailOnStrictViolation() )
{
throw new ManipulationException(
"Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!",
ga( project.getModelParent() ), newValue, oldValue );
}
else
{
logger.warn( "Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!",
ga( project.getModelParent() ), newValue, oldValue );
// Ignore the dependency override. As found has been set to true it won't inject
// a new property either.
continue;
}
}
}
logger.debug( " Modifying parent reference from {} to {} for {} ",
model.getParent().getVersion(), newValue, ga( project.getModelParent() ) );
model.getParent().setVersion( newValue );
break;
}
}
// Apply any explicit overrides to the top level parent. Convert it to a simulated
// dependency so we can reuse applyExplicitOverrides.
HashMap<ArtifactRef, Dependency> pDepMap = new HashMap<>( );
Dependency d = new Dependency();
d.setGroupId( project.getModelParent().getGroupId() );
d.setArtifactId( project.getModelParent().getArtifactId() );
d.setVersion( project.getModelParent().getVersion() );
pDepMap.put( SimpleArtifactRef.parse( d.getManagementKey() ), d );
applyExplicitOverrides( project, pDepMap, explicitOverrides, commonState, explicitVersionPropertyUpdateMap );
project.getModelParent().setVersion( d.getVersion() );
}
if ( session.getState( DependencyState.class ).getOverrideDependencies() )
{
// Apply overrides to project dependency management
logger.debug( "Applying overrides to managed dependencies for: {}", projectGA );
final Map<ArtifactRef, String> nonMatchingVersionOverrides =
applyOverrides( project, project.getResolvedManagedDependencies( session ),
explicitOverrides, moduleOverrides );
final Map<ArtifactRef, String> matchedOverrides = new LinkedHashMap<>( moduleOverrides );
matchedOverrides.keySet().removeAll( nonMatchingVersionOverrides.keySet() );
applyExplicitOverrides( project, project.getResolvedManagedDependencies( session ), explicitOverrides,
commonState, explicitVersionPropertyUpdateMap );
if ( commonState.isOverrideTransitive() )
{
final List<Dependency> extraDeps = new ArrayList<>();
// Add dependencies to Dependency Management which did not match any existing dependency
for ( final ArtifactRef var : overrides.keySet() )
{
if ( !nonMatchingVersionOverrides.containsKey( var ) )
{
// This one in the remote pom was already dealt with ; continue.
continue;
}
final Dependency newDependency = new Dependency();
newDependency.setGroupId( var.getGroupId() );
newDependency.setArtifactId( var.getArtifactId() );
newDependency.setType( var.getType() );
newDependency.setClassifier( var.getClassifier() );
final String artifactVersion = moduleOverrides.get( var );
newDependency.setVersion( artifactVersion );
extraDeps.add( newDependency );
logger.debug( "New entry added to <DependencyManagement/> - {} : {} ", var, artifactVersion );
}
// If the model doesn't have any Dependency Management set by default, create one for it
DependencyManagement dependencyManagement = model.getDependencyManagement();
if ( extraDeps.size() > 0 )
{
if ( dependencyManagement == null )
{
dependencyManagement = new DependencyManagement();
model.setDependencyManagement( dependencyManagement );
logger.debug( "Added <DependencyManagement/> for current project" );
}
dependencyManagement.getDependencies().addAll( 0, extraDeps );
}
}
else
{
logger.debug( "Non-matching dependencies ignored." );
}
}
else
{
logger.debug( "NOT applying overrides to managed dependencies for top-pom: {}", projectGA );
}
}
else
{
// If a child module has a depMgmt section we'll change that as well.
if ( session.getState( DependencyState.class ).getOverrideDependencies() )
{
logger.debug( "Applying overrides to managed dependencies for: {}", projectGA );
applyOverrides( project, project.getResolvedManagedDependencies( session ), explicitOverrides,
moduleOverrides );
applyExplicitOverrides( project, project.getResolvedManagedDependencies( session ), explicitOverrides,
commonState, explicitVersionPropertyUpdateMap );
}
else
{
logger.debug( "NOT applying overrides to managed dependencies for: {}", projectGA );
}
}
if ( session.getState( DependencyState.class ).getOverrideDependencies() )
{
logger.debug( "Applying overrides to concrete dependencies for: {}", projectGA );
// Apply overrides to project direct dependencies
applyOverrides( project, project.getResolvedDependencies( session ), explicitOverrides, moduleOverrides );
applyExplicitOverrides( project, project.getResolvedDependencies( session ), explicitOverrides, commonState, explicitVersionPropertyUpdateMap );
final Map<Profile, Map<ArtifactRef, Dependency>> pd = project.getResolvedProfileDependencies( session );
final Map<Profile, Map<ArtifactRef, Dependency>> pmd = project.getResolvedProfileManagedDependencies( session );
for ( Profile p : pd.keySet())
{
applyOverrides( project, pd.get( p ), explicitOverrides, moduleOverrides );
applyExplicitOverrides( project, pd.get( p ), explicitOverrides, commonState, explicitVersionPropertyUpdateMap );
}
for ( Profile p : pmd.keySet())
{
applyOverrides( project, pmd.get( p ), explicitOverrides, moduleOverrides );
applyExplicitOverrides( project, pmd.get( p ), explicitOverrides, commonState, explicitVersionPropertyUpdateMap );
}
}
else
{
logger.debug( "NOT applying overrides to concrete dependencies for: {}", projectGA );
}
}
/**
* Apply explicit overrides to a set of dependencies from a project. The explicit overrides come from
* dependencyExclusion. However they have to be separated out from standard overrides so we can easily
* ignore any property references (and overwrite them).
*
* @param project the current Project
* @param dependencies dependencies to check
* @param explicitOverrides a custom map to handle wildcard overrides
* @param state the CommonState, to retrieve Common Properties
* @param versionPropertyUpdateMap properties to update
* @throws ManipulationException if an error occurs
*/
private void applyExplicitOverrides( final Project project, final Map<ArtifactRef, Dependency> dependencies,
final WildcardMap<String> explicitOverrides, final CommonState state,
final Map<Project, Map<String, PropertyMapper>> versionPropertyUpdateMap )
throws ManipulationException
{
// Apply matching overrides to dependencies
for ( final ArtifactRef dependency : dependencies.keySet() )
{
final ProjectRef groupIdArtifactId = new SimpleProjectRef( dependency.getGroupId(), dependency.getArtifactId() );
if ( explicitOverrides.containsKey( groupIdArtifactId ) )
{
final String overrideVersion = explicitOverrides.get( groupIdArtifactId );
final String oldVersion = dependencies.get( dependency ).getVersion();
if ( isEmpty( overrideVersion ) || isEmpty( oldVersion ) )
{
if ( isEmpty( oldVersion ) )
{
logger.debug( "Unable to force align as no existing version field to update for " + groupIdArtifactId + "; ignoring" );
}
else
{
logger.warn( "Unable to force align as override version is empty for " + groupIdArtifactId
+ "; ignoring" );
}
}
else
{
for ( String target : overrideVersion.split( "," ) )
{
if ( target.startsWith( "+" ) )
{
logger.info( "Adding dependency exclusion {} to dependency {} ", target.substring( 1 ),
dependency );
Exclusion e = new Exclusion();
e.setGroupId( target.substring( 1 ).split( ":" )[0] );
e.setArtifactId( target.split( ":" )[1] );
dependencies.get( dependency ).addExclusion( e );
}
else
{
logger.info( "Explicit overrides : force aligning {} to {}.", groupIdArtifactId, target );
if ( !PropertiesUtils.cacheProperty( project, state, versionPropertyUpdateMap, oldVersion,
target, dependency, true ) )
{
if ( oldVersion.contains( "${" ) )
{
logger.warn( "Overriding version with {} when old version contained a property {} ",
target, oldVersion );
// TODO: Should this throw an exception?
}
// Not checking strict version alignment here as explicit overrides take priority.
dependencies.get( dependency ).setVersion( target );
}
}
}
}
}
}
}
/**
* Apply a set of version overrides to a list of dependencies. Return a set of the overrides which were not applied.
*
* @param project The current Project
* @param dependencies The list of dependencies
* @param explicitOverrides Any explicitOverrides to track for ignoring
* @param overrides The map of dependency version overrides
* @return The map of overrides that were not matched in the dependencies
* @throws ManipulationException if an error occurs
*/
private Map<ArtifactRef, String> applyOverrides( final Project project, final Map<ArtifactRef, Dependency> dependencies,
final WildcardMap<String> explicitOverrides, final Map<ArtifactRef, String> overrides )
throws ManipulationException
{
// Duplicate the override map so unused overrides can be easily recorded
final Map<ArtifactRef, String> unmatchedVersionOverrides = new LinkedHashMap<>( overrides );
if ( dependencies == null || dependencies.size() == 0 )
{
return unmatchedVersionOverrides;
}
final CommonState commonState = session.getState( CommonState.class );
final boolean strict = commonState.isStrict();
// Apply matching overrides to dependencies
for ( final ArtifactRef dependency : dependencies.keySet() )
{
ProjectRef depPr = new SimpleProjectRef( dependency.getGroupId(), dependency.getArtifactId() );
// We might have junit:junit:3.8.2 and junit:junit:4.1 for differing override scenarios within the
// overrides list. If strict mode alignment is enabled, using multiple overrides will work with
// different modules. It is currently undefined what will happen if non-strict mode is enabled and
// multiple versions are in the remote override list (be it from a bom or rest call). Actually, what
// will most likely happen is last-wins.
for ( final Map.Entry<ArtifactRef, String> entry : overrides.entrySet() )
{
ProjectRef groupIdArtifactId = entry.getKey().asProjectRef();
if ( depPr.equals( groupIdArtifactId ) )
{
final String oldVersion = dependencies.get( dependency ).getVersion();
final String overrideVersion = entry.getValue();
final String resolvedValue = dependency.getVersionString();
if ( isEmpty( overrideVersion ) )
{
logger.warn( "Unable to align with an empty override version for {}; ignoring", groupIdArtifactId );
}
else if ( isEmpty( oldVersion ) )
{
logger.debug( "Dependency is a managed version for {}; ignoring", groupIdArtifactId );
}
else if (oldVersion.equals( "${project.version}" ) || ( oldVersion.contains( "$" ) && project.getVersion().equals( resolvedValue ) ) )
{
logger.debug( "Dependency {} with original version {} and project version {} for {} references ${project.version} so skipping.",
dependency, oldVersion, project.getVersion(), project.getPom() );
}
// If we have an explicitOverride, this will always override the dependency changes made here.
// By avoiding the potential duplicate work it also avoids a possible property clash problem.
else if ( explicitOverrides.containsKey( depPr ) )
{
logger.debug ("Dependency {} matches known explicit override so not performing initial override pass.", depPr);
unmatchedVersionOverrides.remove( entry.getKey() );
}
// If we're doing strict matching with properties, then the original parts should match.
// i.e. assuming original resolved value is 1.2 and potential new value is 1.2.rebuild-1
// then this is fine to continue. If the original is 1.2 and potential new value is 1.3.rebuild-1
// then don't bother to attempt to cache the property as the strict check would fail.
// This extra check avoids an erroneous "Property replacement clash" error.
// Can't blindly compare resolvedValue [original] against ar as ar / overrideVersion is the new GAV. We don't
// have immediate access to the original property so the closest that is feasible is verify strict matching.
else if ( strict && oldVersion.contains( "$" ) &&
! PropertiesUtils.checkStrictValue( session, resolvedValue, overrideVersion) )
{
logger.debug ("Original fully resolved version {} of {} does not match override version {} -> {} so ignoring",
resolvedValue, dependency, entry.getKey(), overrideVersion);
if ( commonState.isFailOnStrictViolation() )
{
throw new ManipulationException(
"For {} replacing original property version {} (fully resolved: {} ) with new version {} for {} violates the strict version-alignment rule!",
depPr.toString(), dependencies.get( dependency ).getVersion(), resolvedValue, entry.getKey().getVersionString(), entry.getKey().asProjectRef().toString());
}
else
{
logger.warn( "Replacing original property version {} with new version {} for {} violates the strict version-alignment rule!",
resolvedValue, overrideVersion, dependencies.get( dependency ).getVersion() );
}
}
else
{
if ( ! PropertiesUtils.cacheProperty( project, commonState, versionPropertyUpdateMap, oldVersion, overrideVersion, entry.getKey(), false ))
{
if ( strict && ! PropertiesUtils.checkStrictValue( session, resolvedValue, overrideVersion) )
{
if ( commonState.isFailOnStrictViolation() )
{
throw new ManipulationException(
"Replacing original version {} in dependency {} with new version {} violates the strict version-alignment rule!",
oldVersion, groupIdArtifactId.toString(), overrideVersion );
}
else
{
logger.warn( "Replacing original version {} in dependency {} with new version {} violates the strict version-alignment rule!",
oldVersion, groupIdArtifactId, overrideVersion );
}
}
else
{
logger.debug( "Altered dependency {} : {} -> {}", groupIdArtifactId, oldVersion,
overrideVersion );
// This block handles a version that is a partial property with a value.
if ( oldVersion.contains( "${" ) )
{
String suffix = PropertiesUtils.getSuffix( session );
String replaceVersion;
if ( commonState.isStrictIgnoreSuffix() && oldVersion.contains( suffix ) )
{
replaceVersion = StringUtils.substringBefore( oldVersion, suffix );
replaceVersion += suffix + StringUtils.substringAfter( overrideVersion, suffix );
}
else
{
replaceVersion = oldVersion + StringUtils.removeStart( overrideVersion, resolvedValue );
}
logger.debug ( "Resolved value is {} and replacement version is {} ", resolvedValue, replaceVersion );
// In this case the previous value couldn't be cached even though it contained a property
// as it was either multiple properties or a property combined with a hardcoded value. Therefore
// just append the suffix.
dependencies.get( dependency ).setVersion( replaceVersion );
}
else
{
dependencies.get( dependency ).setVersion( overrideVersion );
}
}
}
unmatchedVersionOverrides.remove( entry.getKey() );
}
}
}
}
return unmatchedVersionOverrides;
}
/**
* Remove version overrides which refer to projects in the current reactor.
* Projects in the reactor include things like inter-module dependencies
* which should never be overridden.
* @param versionOverrides current set of ArtifactRef:newVersion overrides.
* @return A new Map with the reactor GAs removed.
*/
private Map<ArtifactRef, String> removeReactorGAs( final Map<ArtifactRef, String> versionOverrides )
{
final Map<ArtifactRef, String> reducedVersionOverrides = new LinkedHashMap<>( versionOverrides );
for ( final Project project : session.getProjects() )
{
reducedVersionOverrides.remove( new SimpleArtifactRef( project.getGroupId(), project.getArtifactId(), project.getVersion(), "pom", null ) );
}
return reducedVersionOverrides;
}
/**
* Remove module overrides which do not apply to the current module. Searches the full list of version overrides
* for any keys which contain the '@' symbol. Removes these from the version overrides list, and add them back
* without the '@' symbol only if they apply to the current module.
*
* @param projectGA the current project group : artifact
* @param originalOverrides The full list of version overrides, both global and module specific
* @param moduleOverrides are individual overrides e.g. group:artifact@groupId:artifactId :: value
* @param explicitOverrides a custom map to handle wildcard overrides
* @param extraBOMOverrides a nested map of additional overrides, keyed on a String
* @return The map of global and module specific overrides which apply to the given module
* @throws ManipulationException if an error occurs
*/
private Map<ArtifactRef, String> applyModuleVersionOverrides( final String projectGA,
final Map<String, String> moduleOverrides,
Map<ArtifactRef, String> originalOverrides,
final WildcardMap explicitOverrides,
final Map<String, Map<ProjectRef, String>> extraBOMOverrides )
throws ManipulationException
{
final Map<ArtifactRef, String> remainingOverrides = new LinkedHashMap<>( originalOverrides );
if (logger.isDebugEnabled())
{
logger.debug("Calculating module-specific version overrides. Starting with:\n {}",
join(remainingOverrides.entrySet(), "\n "));
}
// These modes correspond to two different kinds of passes over the available override properties:
// 1. Module-specific: Don't process wildcard overrides here, allow module-specific settings to take precedence.
// 2. Wildcards: Add these IF there is no corresponding module-specific override.
final boolean wildcardMode[] = { false, true };
for ( boolean aWildcardMode : wildcardMode )
{
for ( final String currentKey : new HashSet<>( moduleOverrides.keySet() ) )
{
final String currentValue = moduleOverrides.get( currentKey );
logger.debug( "Processing key {} for override with value {}", currentKey, currentValue );
if ( !currentKey.contains( "@" ) )
{
logger.debug( "Not an override. Skip." );
continue;
}
final boolean isModuleWildcard = currentKey.endsWith( "@*" );
logger.debug( "Is wildcard? {} and in module wildcard mode? {} ", isModuleWildcard, aWildcardMode );
String artifactGA = null;
boolean replace = false;
// process module-specific overrides (first)
if ( !aWildcardMode )
{
// skip wildcard overrides in this mode
if ( isModuleWildcard )
{
logger.debug( "Not currently in wildcard mode. Skip." );
continue;
}
final String[] artifactAndModule = currentKey.split( "@" );
if ( artifactAndModule.length != 2 )
{
throw new ManipulationException( "Invalid format for exclusion key " + currentKey );
}
artifactGA = artifactAndModule[0];
final ProjectRef moduleGA = SimpleProjectRef.parse( artifactAndModule[1] );
logger.debug( "For artifact override: {}, comparing parsed module: {} to current project: {}",
artifactGA, moduleGA, projectGA );
if ( moduleGA.toString().equals( projectGA ) ||
(
moduleGA.getArtifactId().equals( "*" ) &&
SimpleProjectRef.parse( projectGA ).getGroupId().equals( moduleGA.getGroupId()
)
) )
{
if ( currentValue != null && !currentValue.isEmpty() )
{
replace = true;
logger.debug( "Overriding module dependency for {} with {} : {}", moduleGA, artifactGA,
currentValue );
}
else
{
// Override prevention...
removeGA( remainingOverrides, SimpleProjectRef.parse( artifactGA ) );
logger.debug( "For module {}, ignoring dependency override for {} ", moduleGA, artifactGA);
}
}
}
// process wildcard overrides (second)
else
{
// skip module-specific overrides in this mode i.e. format of groupdId:artifactId@*=
if ( !isModuleWildcard )
{
logger.debug( "Currently in wildcard mode. Skip." );
continue;
}
artifactGA = currentKey.substring( 0, currentKey.length() - 2 );
logger.debug( "For artifact override: {}, checking if current overrides already contain a module-specific version.",
artifactGA );
if ( explicitOverrides.containsKey( SimpleProjectRef.parse( artifactGA ) ) )
{
logger.debug( "For artifact override: {}, current overrides already contain a module-specific version. Skip.",
artifactGA );
continue;
}
// I think this is only used for e.g. dependencyExclusion.groupId:artifactId@*=<explicitVersion>
if ( currentValue != null && !currentValue.isEmpty() )
{
logger.debug( "Overriding module dependency for {} with {} : {}", projectGA, artifactGA,
currentValue );
replace = true;
}
else
{
// If we have a wildcard artifact we want to replace any prior explicit overrides
// with this one i.e. this takes precedence.
removeGA( remainingOverrides, SimpleProjectRef.parse( artifactGA ) );
logger.debug( "Removing artifactGA {} from overrides", artifactGA );
}
}
if ( replace )
{
ProjectRef projectRef = SimpleProjectRef.parse( artifactGA );
String newArtifactValue;
// Expand values that reference an extra BOM
Map<ProjectRef, String> extraBOM = extraBOMOverrides.get( currentValue );
if ( extraBOM == null )
{
newArtifactValue = currentValue;
}
else
{
newArtifactValue = extraBOM.get( projectRef );
if ( newArtifactValue == null )
{
throw new ManipulationException( "Extra BOM {} does not define a version for artifact {} targeted by {}",
currentValue, artifactGA, currentKey );
}
logger.debug( "Dereferenced value {} for {} from extra BOM {}", newArtifactValue, artifactGA,
currentValue );
}
explicitOverrides.put( projectRef, newArtifactValue );
}
}
}
return remainingOverrides;
}
private void removeGA( Map<ArtifactRef, String> overrides, ProjectRef ref )
{
Iterator<ArtifactRef> it = overrides.keySet().iterator();
while ( it.hasNext() )
{
ArtifactRef a = it.next();
if ( a.asProjectRef().equals( ref ) ||
( ref.getArtifactId().equals( "*" ) && a.getGroupId().equals( ref.getGroupId() ) ) ||
( ref.getGroupId().equals( "*" ) && a.getArtifactId().equals( ref.getArtifactId() ) ) )
{
it.remove();
}
else if ( ref.getArtifactId().equals( "*" ) && ref.getGroupId().equals( "*" ) )
{
// For complete wildcard also cache the ignored module as we need the list later during
// property processing.
it.remove();
}
}
}
private void validateDependenciesUpdatedProperty( CommonState cState, Project p, Map<ArtifactRef, Dependency> dependencies )
throws ManipulationException
{
for ( ArtifactRef d : dependencies.keySet() )
{
String versionProperty = dependencies.get( d ).getVersion();
if ( versionProperty.startsWith( "${" ) )
{
PropertiesUtils.verifyPropertyMapping( cState, p, versionPropertyUpdateMap, d,
PropertiesUtils.extractPropertyName( versionProperty ) );
}
}
}
}
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.ContextKey;
import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter;
import io.opentelemetry.instrumentation.api.internal.SpanKey;
public final class AgentSpanTestingInstrumenter {
private static final ContextKey<Request> REQUEST_CONTEXT_KEY =
ContextKey.named("test-request-key");
private static final Instrumenter<Request, Void> INSTRUMENTER =
Instrumenter.<Request, Void>builder(
GlobalOpenTelemetry.get(), "test", request -> request.name)
.addContextCustomizer(
(context, request, startAttributes) -> context.with(REQUEST_CONTEXT_KEY, request))
.newInstrumenter(request -> request.kind);
public static Context startServerSpan(String name) {
return start(name, SpanKind.SERVER);
}
public static Context startClientSpan(String name) {
return start(name, SpanKind.CLIENT);
}
public static Context startSpanWithAllKeys(String name) {
Context context = start(name, SpanKind.INTERNAL);
Span span = Span.fromContext(context);
for (SpanKey spanKey : getSpanKeys()) {
context = spanKey.storeInContext(context, span);
}
return context;
}
private static Context start(String name, SpanKind kind) {
return INSTRUMENTER.start(Context.current(), new Request(name, kind));
}
public static void end(Context context, Throwable error) {
INSTRUMENTER.end(context, context.get(REQUEST_CONTEXT_KEY), null, error);
}
private static final class Request {
private final String name;
private final SpanKind kind;
public Request(String name, SpanKind kind) {
this.name = name;
this.kind = kind;
}
}
private static SpanKey[] getSpanKeys() {
return new SpanKey[] {
SpanKey.SERVER,
SpanKey.HTTP_CLIENT,
SpanKey.RPC_CLIENT,
SpanKey.DB_CLIENT,
SpanKey.ALL_CLIENTS,
SpanKey.PRODUCER,
SpanKey.CONSUMER_RECEIVE,
SpanKey.CONSUMER_PROCESS
};
}
private AgentSpanTestingInstrumenter() {}
}
|
package com.github.hiwepy.httpclient.handler.response;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import com.github.hiwepy.httpclient.utils.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
/**
*
* @className : Dom4jResponseHandler
* @description : http请求响应处理:返回org.dom4j.Document对象
* @author : <a href="https://github.com/hiwepy">hiwepy</a>
* @date : 2017年12月3日 下午4:14:13
* @version V1.0
*/
public class Dom4jResponseHandler extends AbstractResponseHandler<Document> {
// 读取输入流
protected SAXReader reader = new SAXReader();
public Dom4jResponseHandler( String charset) {
super(null, charset);
}
public Dom4jResponseHandler(HttpClientContext context, String charset) {
super(context, charset);
}
@Override
public Document handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
// 从response中取出HttpEntity对象
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
StatusLine statusLine = response.getStatusLine();
int status = statusLine.getStatusCode();
if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
//获取响应类型
ContentType contentType = ContentType.getOrDefault(entity);
if (! contentType.toString().equalsIgnoreCase(ContentType.APPLICATION_XML.toString())) {
throw new ClientProtocolException("Unexpected content type:" + contentType);
}
//String charset = contentType.getCharset() == null ? getCharset() : contentType.getCharset().name();
// 从request中取得输入流
InputStream inputStream = null;
Document document = null;
try {
inputStream = entity.getContent();
document = reader.read(inputStream);
} catch (DocumentException ex) {
throw new ClientProtocolException("Malformed XML document",ex);
} finally {
// 释放资源
IOUtils.closeQuietly(inputStream);
inputStream = null;
}
return document;
} else {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
}
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.graphics.drawable.animated;
public final class R {
public static final class attr {
public static final int font = 0x7f020070;
public static final int fontProviderAuthority = 0x7f020072;
public static final int fontProviderCerts = 0x7f020073;
public static final int fontProviderFetchStrategy = 0x7f020074;
public static final int fontProviderFetchTimeout = 0x7f020075;
public static final int fontProviderPackage = 0x7f020076;
public static final int fontProviderQuery = 0x7f020077;
public static final int fontStyle = 0x7f020078;
public static final int fontWeight = 0x7f020079;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f030000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f04003f;
public static final int notification_icon_bg_color = 0x7f040040;
public static final int ripple_material_light = 0x7f04004b;
public static final int secondary_text_default_material_light = 0x7f04004d;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f05004a;
public static final int compat_button_inset_vertical_material = 0x7f05004b;
public static final int compat_button_padding_horizontal_material = 0x7f05004c;
public static final int compat_button_padding_vertical_material = 0x7f05004d;
public static final int compat_control_corner_material = 0x7f05004e;
public static final int notification_action_icon_size = 0x7f050058;
public static final int notification_action_text_size = 0x7f050059;
public static final int notification_big_circle_margin = 0x7f05005a;
public static final int notification_content_margin_start = 0x7f05005b;
public static final int notification_large_icon_height = 0x7f05005c;
public static final int notification_large_icon_width = 0x7f05005d;
public static final int notification_main_column_padding_top = 0x7f05005e;
public static final int notification_media_narrow_margin = 0x7f05005f;
public static final int notification_right_icon_size = 0x7f050060;
public static final int notification_right_side_padding_top = 0x7f050061;
public static final int notification_small_icon_background_padding = 0x7f050062;
public static final int notification_small_icon_size_as_large = 0x7f050063;
public static final int notification_subtext_size = 0x7f050064;
public static final int notification_top_pad = 0x7f050065;
public static final int notification_top_pad_large_text = 0x7f050066;
}
public static final class drawable {
public static final int notification_action_background = 0x7f060056;
public static final int notification_bg = 0x7f060057;
public static final int notification_bg_low = 0x7f060058;
public static final int notification_bg_low_normal = 0x7f060059;
public static final int notification_bg_low_pressed = 0x7f06005a;
public static final int notification_bg_normal = 0x7f06005b;
public static final int notification_bg_normal_pressed = 0x7f06005c;
public static final int notification_icon_background = 0x7f06005d;
public static final int notification_template_icon_bg = 0x7f06005e;
public static final int notification_template_icon_low_bg = 0x7f06005f;
public static final int notification_tile_bg = 0x7f060060;
public static final int notify_panel_notification_icon_bg = 0x7f060061;
}
public static final class id {
public static final int action_container = 0x7f07000e;
public static final int action_divider = 0x7f070010;
public static final int action_image = 0x7f070011;
public static final int action_text = 0x7f070017;
public static final int actions = 0x7f070018;
public static final int async = 0x7f07001e;
public static final int blocking = 0x7f070021;
public static final int chronometer = 0x7f070029;
public static final int forever = 0x7f070036;
public static final int icon = 0x7f07003a;
public static final int icon_group = 0x7f07003b;
public static final int info = 0x7f07003e;
public static final int italic = 0x7f07003f;
public static final int line1 = 0x7f070040;
public static final int line3 = 0x7f070041;
public static final int normal = 0x7f07004a;
public static final int notification_background = 0x7f07004b;
public static final int notification_main_column = 0x7f07004c;
public static final int notification_main_column_container = 0x7f07004d;
public static final int right_icon = 0x7f070054;
public static final int right_side = 0x7f070055;
public static final int text = 0x7f070075;
public static final int text2 = 0x7f070076;
public static final int time = 0x7f07007a;
public static final int title = 0x7f07007b;
}
public static final class integer {
public static final int status_bar_notification_info_maxnum = 0x7f080004;
}
public static final class layout {
public static final int notification_action = 0x7f09001d;
public static final int notification_action_tombstone = 0x7f09001e;
public static final int notification_template_custom_big = 0x7f090025;
public static final int notification_template_icon_group = 0x7f090026;
public static final int notification_template_part_chronometer = 0x7f09002a;
public static final int notification_template_part_time = 0x7f09002b;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0b0026;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0c00fa;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00fb;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00fd;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0c0100;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0c0102;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0c016b;
public static final int Widget_Compat_NotificationActionText = 0x7f0c016c;
}
public static final class styleable {
public static final int[] FontFamily = { 0x7f020072, 0x7f020073, 0x7f020074, 0x7f020075, 0x7f020076, 0x7f020077 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x7f020070, 0x7f020078, 0x7f020079 };
public static final int FontFamilyFont_font = 0;
public static final int FontFamilyFont_fontStyle = 1;
public static final int FontFamilyFont_fontWeight = 2;
}
}
|
package org.folio.circulation.services;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.folio.circulation.domain.representations.StoredFeeFineAction.StoredFeeFineActionBuilder;
import static org.folio.circulation.services.feefine.FeeRefundProcessor.createLostItemFeeRefundProcessor;
import static org.folio.circulation.support.AsyncCoordinationUtil.allOf;
import static org.folio.circulation.support.results.Result.failed;
import static org.folio.circulation.support.results.Result.succeeded;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.folio.circulation.domain.Account;
import org.folio.circulation.domain.ServicePoint;
import org.folio.circulation.domain.User;
import org.folio.circulation.domain.representations.StoredAccount;
import org.folio.circulation.domain.representations.StoredFeeFineAction;
import org.folio.circulation.infrastructure.storage.ServicePointRepository;
import org.folio.circulation.infrastructure.storage.feesandfines.AccountRepository;
import org.folio.circulation.infrastructure.storage.feesandfines.FeeFineActionRepository;
import org.folio.circulation.infrastructure.storage.users.UserRepository;
import org.folio.circulation.services.feefine.AccountRefundContext;
import org.folio.circulation.services.feefine.FeeRefundProcessor;
import org.folio.circulation.services.support.CreateAccountCommand;
import org.folio.circulation.services.support.RefundAccountCommand;
import org.folio.circulation.support.Clients;
import org.folio.circulation.support.ServerErrorFailure;
import org.folio.circulation.support.results.CommonFailures;
import org.folio.circulation.support.results.Result;
import lombok.val;
public class FeeFineFacade {
private final AccountRepository accountRepository;
private final FeeFineActionRepository feeFineActionRepository;
private final UserRepository userRepository;
private final ServicePointRepository servicePointRepository;
private final FeeRefundProcessor lostItemRefundProcessor;
public FeeFineFacade(Clients clients) {
this.accountRepository = new AccountRepository(clients);
this.feeFineActionRepository = new FeeFineActionRepository(clients);
this.userRepository = new UserRepository(clients);
this.servicePointRepository = new ServicePointRepository(clients);
this.lostItemRefundProcessor = createLostItemFeeRefundProcessor();
}
public CompletableFuture<Result<Void>> createAccounts(
Collection<CreateAccountCommand> accountAndActions) {
return allOf(accountAndActions, this::createAccount)
.thenApply(r -> r.<Void>map(list -> null))
.exceptionally(CommonFailures::failedDueToServerError);
}
private CompletableFuture<Result<Void>> createAccount(CreateAccountCommand creation) {
final StoredAccount account = new StoredAccount(
creation.getLoan(),
creation.getItem(),
creation.getFeeFineOwner(),
creation.getFeeFine(),
creation.getAmount());
return accountRepository.create(account)
.thenCompose(r -> r.after(createdAccount -> createAccountCreatedAction(createdAccount, creation)));
}
private CompletableFuture<Result<Void>> createAccountCreatedAction(
Account createdAccount, CreateAccountCommand creation) {
final StoredFeeFineActionBuilder builder = StoredFeeFineAction.builder();
return populateCreatedBy(builder, creation)
.thenCompose(r -> r.after(updatedBuilder -> populateCreatedAt(updatedBuilder, creation)))
.thenApply(r -> r.map(updatedBuilder -> updatedBuilder
.withBalance(createdAccount.getRemaining())
.withAmount(createdAccount.getAmount())
.withUserId(createdAccount.getUserId())
.withAction(createdAccount.getFeeFineType())
.withAccountId(createdAccount.getId())
.build()))
.thenCompose(r -> r.after(feeFineActionRepository::create))
.thenApply(r -> r.map(notUsed -> null));
}
public CompletableFuture<Result<Void>> refundAndCloseAccounts(List<RefundAccountCommand> accounts) {
return allOf(accounts, this::refundAndCloseAccount)
.thenApply(r -> r.<Void>map(list -> null))
.exceptionally(CommonFailures::failedDueToServerError);
}
private CompletableFuture<Result<Void>> refundAndCloseAccount(RefundAccountCommand refund) {
val context = new AccountRefundContext(refund.getAccountToRefund(),
refund.getCancellationReason());
return fetchUser(refund.getStaffUserId())
.thenApply(r -> r.map(context::withUser))
.thenComposeAsync(r -> r.after(notUsed -> fetchServicePoint(refund.getServicePointId())))
.thenApply(r -> r.map(context::withServicePoint))
.thenCompose(r -> r.after(this::processRefundAndClose));
}
private CompletableFuture<Result<Void>> processRefundAndClose(AccountRefundContext context) {
if (!lostItemRefundProcessor.canHandleAccountRefund(context.getAccount())) {
return completedFuture(noRefundProcessorForFeeType(context.getAccount().getFeeFineType()));
}
return createRefundAndCloseActions(context)
.thenCompose(r -> r.after(notUsed -> updateAccount(context)));
}
private Result<Void> noRefundProcessorForFeeType(String feeFineType) {
return failed(new ServerErrorFailure(
"No refund processor available for fee/fine of type: " + feeFineType));
}
private CompletableFuture<Result<Void>> updateAccount(AccountRefundContext context) {
final Account account = context.getAccount();
if (account.hasTransferredAmount()) {
lostItemRefundProcessor.onTransferAmountRefundActionSaved(context);
}
if (account.hasPaidAmount()) {
lostItemRefundProcessor.onPaidAmountRefundActionSaved(context);
}
if (account.hasRemainingAmount()) {
lostItemRefundProcessor.onRemainingAmountActionSaved(context);
}
return accountRepository.update(StoredAccount.fromAccount(context.getAccount()));
}
private CompletableFuture<Result<Void>> createRefundAndCloseActions(
AccountRefundContext context) {
final Account account = context.getAccount();
if (account.hasTransferredAmount()) {
lostItemRefundProcessor.onHasTransferAmount(context);
}
if (account.hasPaidAmount()) {
lostItemRefundProcessor.onHasPaidAmount(context);
}
if (account.hasRemainingAmount()) {
lostItemRefundProcessor.onHasRemainingAmount(context);
}
return feeFineActionRepository.createAll(context.getActions());
}
private CompletableFuture<Result<StoredFeeFineActionBuilder>> populateCreatedBy(
StoredFeeFineActionBuilder builder, CreateAccountCommand command) {
if (command.isCreatedByAutomatedProcess()) {
return completedFuture(succeeded(builder.createdByAutomatedProcess()));
}
return userRepository.getUser(command.getStaffUserId())
.thenApply(r -> r.map(builder::withCreatedBy));
}
private CompletableFuture<Result<User>> fetchUser(String userId) {
return userRepository.getUser(userId);
}
private CompletableFuture<Result<ServicePoint>> fetchServicePoint(String servicePointId) {
return servicePointRepository.getServicePointById(servicePointId);
}
private CompletableFuture<Result<StoredFeeFineActionBuilder>> populateCreatedAt(
StoredFeeFineActionBuilder builder, CreateAccountCommand command) {
if (command.isCreatedByAutomatedProcess()) {
return completedFuture(succeeded(builder));
}
return fetchServicePoint(command.getCurrentServicePointId())
.thenApply(r -> r.map(builder::withCreatedAt));
}
}
|
package ch.eth.jcd.badgers.vfs.test.compression;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import ch.eth.jcd.badgers.vfs.compression.BadgersRLECompressionInputStream;
import ch.eth.jcd.badgers.vfs.compression.BadgersRLECompressionOutputStream;
import ch.eth.jcd.badgers.vfs.test.testutil.UnittestLogger;
public class BadgersRLECompressionTest {
private static final Logger LOGGER = Logger.getLogger(BadgersRLECompressionTest.class);
@BeforeClass
public static void beforeClass() {
UnittestLogger.init();
}
@Test
public void testMaximumCompression() throws IOException {
byte[] rawData = new byte[2048];
byte[] rawDataCopy = rawData.clone();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BadgersRLECompressionOutputStream out = new BadgersRLECompressionOutputStream(outputStream);
out.write(rawData);
out.flush();
out.close();
byte[] encrypted = outputStream.toByteArray();
LOGGER.debug("Byte length before encryption: " + rawData.length);
LOGGER.debug("Byte length after encryption: " + encrypted.length);
ByteArrayInputStream inputStream = new ByteArrayInputStream(encrypted);
BadgersRLECompressionInputStream in = new BadgersRLECompressionInputStream(inputStream);
Assert.assertEquals(rawData.length, in.read(rawDataCopy));
in.close();
for (int i = 0; i < rawData.length; i++) {
Assert.assertEquals(rawData[i], rawDataCopy[i]);
}
}
@Test
public void testRandomInput() throws IOException {
Random rnd = new Random();
byte[] rawData = new byte[rnd.nextInt(255)];
// byte[] rawData = new byte[] { -1, -1, -2 };
byte[] rawDataCopy = new byte[rawData.length];// = new byte[2048];
rnd.nextBytes(rawData);
/*
* byte[] rawData = new byte[2048]; byte[] rawDataCopy = new byte[2048]; new Random().nextBytes(rawData);
*/
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BadgersRLECompressionOutputStream out = new BadgersRLECompressionOutputStream(outputStream);
out.write(rawData);
out.close();
byte[] encrypted = outputStream.toByteArray();
LOGGER.debug("Byte length before encryption: " + rawData.length);
LOGGER.debug("Byte length after encryption: " + encrypted.length);
ByteArrayInputStream inputStream = new ByteArrayInputStream(encrypted);
BadgersRLECompressionInputStream in = new BadgersRLECompressionInputStream(inputStream);
Assert.assertEquals(rawData.length, in.read(rawDataCopy));
in.close();
for (int i = 0; i < rawData.length; i++) {
Assert.assertEquals("Expected equal data, is not equal at " + i, rawData[i], rawDataCopy[i]);
}
}
@Test
public void testStringInput() throws IOException {
String stringDatas = "Miss Kalissippi from Mississippi is a " + "cowgirl who yells yippi when she rides her horse in "
+ "the horse show in Mississippiiiiiiii";
byte[] rawDataCopy = new byte[2048];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BadgersRLECompressionOutputStream out = new BadgersRLECompressionOutputStream(outputStream);
out.write(stringDatas.getBytes());
out.close();
byte[] encrypted = outputStream.toByteArray();
LOGGER.debug("Byte length before encryption: " + stringDatas.length());
LOGGER.debug("Byte length after encryption: " + encrypted.length);
ByteArrayInputStream inputStream = new ByteArrayInputStream(encrypted);
BadgersRLECompressionInputStream in = new BadgersRLECompressionInputStream(inputStream);
Assert.assertEquals(stringDatas.length(), in.read(rawDataCopy));
in.close();
byte[] rawData = stringDatas.getBytes();
for (int i = 0; i < rawData.length; i++) {
Assert.assertEquals("Expected equal data, is not equal at " + i, rawData[i], rawDataCopy[i]);
}
}
}
|
package com.randomappsinc.berniesanderssoundboard.Activities;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ListView;
import com.randomappsinc.berniesanderssoundboard.Adapters.SourcesAdapter;
import com.randomappsinc.berniesanderssoundboard.R;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnItemClick;
/**
* Created by alexanderchiou on 11/17/15.
*/
public class SourcesActivity extends StandardActivity {
@Bind(R.id.sources) ListView sources;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sources);
ButterKnife.bind(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sources.setAdapter(new SourcesAdapter(this));
}
@OnItemClick(R.id.sources)
public void onItemClick(int position) {
String sourceUrl = getResources().getStringArray(R.array.sources_links)[position];
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(sourceUrl)));
}
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2020 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.html2pdf.css.w3c.css21.text;
import com.itextpdf.html2pdf.css.w3c.W3CCssTest;
public class WhiteSpacePre001Test extends W3CCssTest {
@Override
protected String getHtmlFileName() {
return "white-space-pre-001.xht";
}
}
|
/**
*
*/
package com.msi.tough.monitor;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import com.msi.tough.core.Appctx;
import com.msi.tough.servlet.StandardContextListener;
//import com.msi.tough.monitor.hedwig.ServiceSubscriber;
/**
* @author tdhite
*/
public class MonitorContextListener extends StandardContextListener {
private ServletContext servletContext;
private static long gather_sleep;
static {
gather_sleep = Long.parseLong((String) Appctx
.getConfigurationBean("GatherSleepTime"));
}
private final List<HypervisorMonitor> monitors = new ArrayList<HypervisorMonitor>();
//private final List<ServiceSubscriber> sublist = new ArrayList<ServiceSubscriber>();
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
* ServletContextEvent)
*/
@Override
public void contextDestroyed(final ServletContextEvent event) {
super.contextDestroyed(event);
// stopThreads();
}
/*
* (non-Javadoc)
*
* @see
* javax.servlet.ServletContextListener#contextInitialized(javax.servlet
* .ServletContextEvent)
*/
@Override
public void contextInitialized(final ServletContextEvent event) {
super.contextInitialized(event);
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
servletContext = event.getServletContext();
// try {
servletContext.setAttribute("monitor.hypervisormonitor.list", monitors);
servletContext.setAttribute("monitor.hypervisormonitor.sleep",
gather_sleep);
// startThreads();
// } catch (final ParseException e) {
// logger.error(e.getMessage());
// e.printStackTrace();
// logger.error("A general parse exception occurred at startup - Monitor may not work correctly!");
// }
}
//
// private void startThreads() throws ParseException {
// final ArrayList<HypervisorConnector> connectors = new
// ArrayList<HypervisorConnector>();
//
// final Session session = HibernateUtil.newSession();
// session.beginTransaction();
//
// final String hql =
// "from com.msi.tough.model.monitor.HypervisorConfigBean where enable='Y'";
// final Query query = session.createQuery(hql);
//
// session.getTransaction().commit();
// final List<HypervisorConfigBean> hvlist = query.list();
// try {
// session.close();
// } catch (final Exception e) {
// }
//
// for (final HypervisorConfigBean config : hvlist) {
// final HypervisorConnector conn = HypervisorConnectionFactory
// .getConnector(config);
// connectors.add(conn);
// }
//
// final MeasureHandler mHandler = Appctx.getBean("measurehandler");
// for (final HypervisorConnector conn : connectors) {
// HypervisorMonitor mon = null;
// try {
// mon = new HypervisorMonitor(mHandler, conn, gather_sleep);
// } catch (final MSIMonitorException e) {
// logger.error(e.getMessage());
// e.printStackTrace();
// logger.error("A general MSIMonitorException occurred at startup - Monitor may not work correctly!");
// } catch (final Exception e) {
// logger.error(e.getMessage());
// e.printStackTrace();
// logger.error("A general exception occurred at startup - Monitor may not work correctly!");
// } finally {
// if (mon == null) {
// logger.error("Monitor failed to start for mHandler: "
// + mHandler.toString());
// } else {
// monitors.add(mon);
// }
// }
// }
//
// /*
// * ServiceSubscriber asSub = new ServiceSubscriber(Constants.AS_TOPIC);
// * try { asSub.subscribe(new ASMetricHandler()); } catch
// * (CouldNotConnectException e) { logger.log(Level.SEVERE,
// * e.getMessage()); e.printStackTrace(); logger.log(Level.SEVERE,
// *
// "A CouldNotConnectException occurred at startup - subscription may not work correctly!"
// * ); } catch (ClientAlreadySubscribedException e) {
// * logger.log(Level.SEVERE, e.getMessage()); e.printStackTrace();
// * logger.log(Level.SEVERE,
// *
// "A ClientAlreadySubscribedException occurred at startup - subscription may not work correctly!"
// * ); } catch (ServiceDownException e) { logger.log(Level.SEVERE,
// * e.getMessage()); e.printStackTrace(); logger.log(Level.SEVERE,
// *
// "A ServiceDownException occurred at startup - subscription may not work correctly!"
// * ); } catch (UnsupportedEncodingException e) {
// * logger.log(Level.SEVERE, e.getMessage()); e.printStackTrace();
// * logger.log(Level.SEVERE,
// *
// "A UnsupportedEncodingException occurred at startup - subscription may not work correctly!"
// * ); } catch (ClientNotSubscribedException e) {
// * logger.log(Level.SEVERE, e.getMessage()); e.printStackTrace();
// * logger.log(Level.SEVERE,
// *
// "A ClientNotSubscribedException occurred at startup - subscription may not work correctly!"
// * ); } catch (InvalidSubscriberIdException e) {
// * logger.log(Level.SEVERE, e.getMessage()); e.printStackTrace();
// * logger.log(Level.SEVERE,
// *
// "A InvalidSubscriberIdException occurred at startup - subscription may not work correctly!"
// * ); } sublist.add(asSub);
// */
// }
//
// private void stopThreads() {
// if (monitors != null) {
// for (final HypervisorMonitor mon : monitors) {
// mon.terminate();
// }
// }
/*
* if(this.sublist != null){ for(ServiceSubscriber sub : this.sublist){ try
* { sub.terminate(); } catch (ClientNotSubscribedException e) {
* logger.log(Level.SEVERE, e.getMessage()); e.printStackTrace();
* logger.log(Level.SEVERE,
* "A ClientNotSubscribedException occurred at startup - subscription may not work correctly!"
* ); } catch (InvalidSubscriberIdException e) { logger.log(Level.SEVERE,
* e.getMessage()); e.printStackTrace(); logger.log(Level.SEVERE,
* "A InvalidSubscriberIdException occurred at startup - subscription may not work correctly!"
* ); } catch (CouldNotConnectException e) { logger.log(Level.SEVERE,
* e.getMessage()); e.printStackTrace(); logger.log(Level.SEVERE,
* "A CouldNotConnectException occurred at startup - subscription may not work correctly!"
* ); } catch (ServiceDownException e) { logger.log(Level.SEVERE,
* e.getMessage()); e.printStackTrace(); logger.log(Level.SEVERE,
* "A ServiceDownException occurred at startup - subscription may not work correctly!"
* ); } } }
*/
// }
}
|
package com.controlefinanca;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "controleFinanca";
}
}
|
/*
* 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.geektimes.http.server.jdk.servlet;
import java.util.Collection;
/**
* URL Patterns Matcher
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 1.0.0
*/
public interface URLPatternsMatcher {
boolean matches(Collection<String> urlPatterns, String requestURI);
}
|
/*
* Copyright (c) 2017 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.siddhi.extension.io.http.sink;
import io.siddhi.core.SiddhiAppRuntime;
import io.siddhi.core.SiddhiManager;
import io.siddhi.core.stream.input.InputHandler;
import io.siddhi.extension.io.http.sink.util.HttpServerListenerHandler;
import io.siddhi.extension.map.xml.sinkmapper.XMLSinkMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
/**
* Test cases for different method types.
*/
public class HttpSinkMethodTypeTestCase {
private static final Logger log = LogManager.getLogger(HttpSinkMethodTypeTestCase.class);
private String payload;
private String expected;
@BeforeTest
public void init() {
payload = "<events>"
+ "<event>"
+ "<symbol>WSO2</symbol>"
+ "<price>55.645</price>"
+ "<volume>100</volume>"
+ "</event>"
+ "</events>";
expected = "<events>"
+ "<event>"
+ "<symbol>WSO2</symbol>"
+ "<price>55.645</price>"
+ "<volume>100</volume>"
+ "</event>"
+ "</events>\n";
}
/**
* Creating test for publishing events from GET method.
*
* @throws Exception Interrupted exception
*/
@Test
public void testHTTPTestGetMethod() throws Exception {
log.info("Creating test for publishing events from GET method.");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("xml-output-mapper", XMLSinkMapper.class);
String inStreamDefinition = "Define stream FooStream (message String,method String,headers String);"
+ "@sink(type='http',publisher.url='http://localhost:8005/abc',method='{{method}}',"
+ "headers='{{headers}}',"
+ "@map(type='xml', "
+ "@payload('{{message}}'))) "
+ "Define stream BarStream (message String,method String,headers String);";
String query = ("@info(name = 'query') " +
"from FooStream "
+ "select message,method,headers "
+ "insert into BarStream;"
);
SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(inStreamDefinition +
query);
InputHandler fooStream = siddhiAppRuntime.getInputHandler("FooStream");
siddhiAppRuntime.start();
HttpServerListenerHandler lst = new HttpServerListenerHandler(8005);
lst.run();
fooStream.send(new Object[]{payload, "GET", "Name:John,Age:23"});
while (!lst.getServerListener().isMessageArrive()) {
Thread.sleep(10);
}
String eventData = lst.getServerListener().getData();
Assert.assertEquals("", eventData);
siddhiAppRuntime.shutdown();
lst.shutdown();
}
/**
* Creating test for publishing events from POST method.
*
* @throws Exception Interrupted exception
*/
@Test(dependsOnMethods = "testHTTPTestDeleteMethod")
public void testHTTPTestPOSTMethod() throws Exception {
log.info("Creating test for publishing events from PUT method.");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("xml-output-mapper", XMLSinkMapper.class);
String inStreamDefinition = "Define stream FooStream (message String,method String,headers String);"
+ "@sink(type='http',publisher.url='http://localhost:8005/abc',method='{{method}}',"
+ "headers='{{headers}}',"
+ "@map(type='xml', "
+ "@payload('{{message}}'))) "
+ "Define stream BarStream (message String,method String,headers String);";
String query = ("@info(name = 'query') " +
"from FooStream "
+ "select message,method,headers "
+ "insert into BarStream;"
);
SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(inStreamDefinition +
query);
InputHandler fooStream = siddhiAppRuntime.getInputHandler("FooStream");
siddhiAppRuntime.start();
HttpServerListenerHandler lst = new HttpServerListenerHandler(8005);
lst.run();
fooStream.send(new Object[]{payload, "POST", "Name:John,Age:23"});
while (!lst.getServerListener().isMessageArrive()) {
Thread.sleep(10);
}
String eventData = lst.getServerListener().getData();
Assert.assertEquals(expected, eventData);
siddhiAppRuntime.shutdown();
lst.shutdown();
}
/**
* Creating test for publishing events from PUT method.
*
* @throws Exception Interrupted exception
*/
@Test(dependsOnMethods = "testHTTPTestGetMethod")
public void testHTTPTestPutMethod() throws Exception {
log.info("Creating test for publishing events from PUT method.");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("xml-output-mapper", XMLSinkMapper.class);
String inStreamDefinition = "Define stream FooStream (message String,method String,headers String);"
+ "@sink(type='http',publisher.url='http://localhost:8005/abc',method='{{method}}',"
+ "headers='{{headers}}',"
+ "@map(type='xml', "
+ "@payload('{{message}}'))) "
+ "Define stream BarStream (message String,method String,headers String);";
String query = ("@info(name = 'query') " +
"from FooStream "
+ "select message,method,headers "
+ "insert into BarStream;"
);
SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(inStreamDefinition +
query);
InputHandler fooStream = siddhiAppRuntime.getInputHandler("FooStream");
siddhiAppRuntime.start();
HttpServerListenerHandler lst = new HttpServerListenerHandler(8005);
lst.run();
fooStream.send(new Object[]{payload, "PUT", "Name:John,Age:23"});
while (!lst.getServerListener().isMessageArrive()) {
Thread.sleep(10);
}
String eventData = lst.getServerListener().getData();
Assert.assertEquals(expected, eventData);
siddhiAppRuntime.shutdown();
lst.shutdown();
}
/**
* Creating test for publishing events from DELETE method.
*
* @throws Exception Interrupted exception
*/
@Test(dependsOnMethods = "testHTTPTestPutMethod")
public void testHTTPTestDeleteMethod() throws Exception {
log.info("Creating test for publishing events from DELETE method.");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("xml-output-mapper", XMLSinkMapper.class);
String inStreamDefinition = "Define stream FooStream (message String,method String,headers String);"
+ "@sink(type='http',publisher.url='http://localhost:8005/abc',method='{{method}}',"
+ "headers='{{headers}}',"
+ "@map(type='xml', "
+ "@payload('{{message}}'))) "
+ "Define stream BarStream (message String,method String,headers String);";
String query = ("@info(name = 'query') " +
"from FooStream "
+ "select message,method,headers "
+ "insert into BarStream;"
);
SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(inStreamDefinition +
query);
InputHandler fooStream = siddhiAppRuntime.getInputHandler("FooStream");
siddhiAppRuntime.start();
HttpServerListenerHandler lst = new HttpServerListenerHandler(8005);
lst.run();
fooStream.send(new Object[]{payload, "DELETE", "'Name:John','Age:23'"});
while (!lst.getServerListener().isMessageArrive()) {
Thread.sleep(10);
}
String eventData = lst.getServerListener().getData();
Assert.assertEquals(expected, eventData);
siddhiAppRuntime.shutdown();
lst.shutdown();
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.seaborne.delta ;
import static org.junit.Assert.assertTrue;
import java.net.BindException;
import org.apache.jena.atlas.web.WebLib;
import org.apache.jena.fuseki.main.FusekiServer;
import org.apache.jena.graph.Triple;
import org.apache.jena.rdfconnection.RDFConnection;
import org.apache.jena.rdfconnection.RDFConnectionFactory;
import org.apache.jena.sparql.sse.SSE;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.seaborne.delta.lib.IOX;
import org.seaborne.delta.lib.LogX;
import org.seaborne.delta.server.http.DeltaServer;
import org.seaborne.delta.server.local.DPS;
import org.seaborne.delta.server.local.LocalServerConfig;
import org.seaborne.delta.server.local.LocalServers;
/**
* Other tests for Delta+Fuseki, not using the setup in {@link BaseTestDeltaFuseki},
*
* @see TestDeltaFusekiGood
* @see TestDeltaFusekiBad
*/
public class TestDeltaFuseki {
@BeforeClass public static void setForTesting() {
LogX.setJavaLogging("src/test/resources/logging.properties");
}
@Before public void beforeClass() { DPS.resetSystem(); }
@After public void afterClass() { DPS.resetSystem(); }
@Test public void test1() {
int PORT1 = WebLib.choosePort();
int PORT2 = WebLib.choosePort();
DeltaServer deltaServer = runServer();
// Know port in assembler file - 1077
FusekiServer.Builder builder = FusekiServer.create().loopback(true).parseConfigFile("testing/fuseki/fuseki-assembler-ext.ttl");
FusekiServer fusekiServer1 = builder.port(PORT1).build();
FusekiServer fusekiServer2 = builder.port(PORT2).build();
fusekiServer1.start();
fusekiServer2.start();
Triple t = SSE.parseTriple("(<x:s> <x:p> <x:o>)");
RDFConnection conn1 = RDFConnectionFactory.connect("http://localhost:"+PORT1+"/ds");
try ( RDFConnection conn1a = conn1 ) {
conn1.update("INSERT DATA { <x:s> <x:p> <x:o> }");
boolean b = conn1.queryAsk("ASK { <x:s> <x:p> <x:o> }");
assertTrue(b);
}
RDFConnection conn2 = RDFConnectionFactory.connect("http://localhost:"+PORT2+"/ds");
try ( RDFConnection conn2a = conn2 ) {
boolean b = conn2.queryAsk("ASK { <x:s> <x:p> <x:o> }");
assertTrue(b);
}
deltaServer.stop();
}
@Test public void concurrent_update() {
}
private static DeltaServer runServer() {
LocalServerConfig localServerConfig = LocalServers.configMem();
DeltaServer server = DeltaServer.create(1077, localServerConfig);
try {
// Server.
server.start();
return server;
} catch ( BindException ex) {
throw IOX.exception(ex);
}
}
}
|
public class Main {
public static void main(String[] args) {
Student student = new Student("lol", 17, new Group("123", "B"));
Group group = student.getGroup();
System.out.println(group);
group.setGroup("234");
group.setSubgroup("A");
System.out.println(student.getGroup());
}
}
|
/*******************************************************************************
* Copyright by Dr. Bianca Hoffmann, Ruman Gerst, Dr. Zoltán Cseresnyés and Prof. Dr. Marc Thilo Figge
*
* Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge
* https://www.leibniz-hki.de/en/applied-systems-biology.html
* HKI-Center for Systems Biology of Infection
* Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Insitute (HKI)
* Adolf-Reichwein-Straße 23, 07745 Jena, Germany
*
* The project code is licensed under BSD 2-Clause.
* See the LICENSE file provided with the code for the full license.
******************************************************************************/
package org.hkijena.mcat.ui.parameters;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.function.Supplier;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.hkijena.mcat.api.MCATValidatable;
import org.hkijena.mcat.api.MCATValidityReport;
import org.hkijena.mcat.utils.UIUtils;
import org.scijava.Context;
/**
* UI that generates a set of parameter values
*/
public abstract class MCATParameterGeneratorUI extends JPanel implements Supplier<List<Object>>, MCATValidatable {
private Context context;
/**
* Creates a new instance
*
* @param context the SciJava context
*/
public MCATParameterGeneratorUI(Context context) {
this.context = context;
}
public Context getContext() {
return context;
}
/**
* Shows a dialog that allows the user to setup the generator
*
* @param parent The parent component
* @param context The SciJava context
* @param uiClass The generator UI class
* @return the generated values or null if the user cancelled
*/
public static List<Object> showDialog(Component parent, Context context, Class<? extends MCATParameterGeneratorUI> uiClass) {
Dialog dialog = new Dialog(SwingUtilities.getWindowAncestor(parent), context, uiClass);
dialog.setTitle("");
dialog.setModal(true);
dialog.pack();
dialog.setSize(new Dimension(500, 400));
dialog.setLocationRelativeTo(parent);
UIUtils.addEscapeListener(dialog);
dialog.setVisible(true);
if (dialog.cancelled)
return null;
else
return dialog.getGeneratedValue();
}
/**
* Dialog around an {@link MCATParameterGeneratorUI}
*/
private static class Dialog extends JDialog {
private boolean cancelled = true;
private MCATParameterGeneratorUI generatorUI;
public Dialog(Window windowAncestor, Context context, Class<? extends MCATParameterGeneratorUI> uiClass) {
super(windowAncestor);
try {
this.generatorUI = uiClass.getConstructor(Context.class).newInstance(context);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
initialize();
}
private void initialize() {
getContentPane().setLayout(new BorderLayout());
getContentPane().add(generatorUI, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(Box.createHorizontalGlue());
JButton cancelButton = new JButton("Cancel", UIUtils.getIconFromResources("remove.png"));
cancelButton.addActionListener(e -> {
this.cancelled = true;
this.setVisible(false);
});
buttonPanel.add(cancelButton);
JButton confirmButton = new JButton("Generate", UIUtils.getIconFromResources("run.png"));
confirmButton.addActionListener(e -> {
MCATValidityReport report = new MCATValidityReport();
generatorUI.reportValidity(report);
if (!report.isValid()) {
// UIUtils.openValidityReportDialog(this, report, true);
JOptionPane.showMessageDialog(this, "The parameters are invalid!", "Generate", JOptionPane.ERROR_MESSAGE);
return;
}
this.cancelled = false;
this.setVisible(false);
});
buttonPanel.add(confirmButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public List<Object> getGeneratedValue() {
return generatorUI.get();
}
public boolean isCancelled() {
return cancelled;
}
}
}
|
/*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* 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.
*/
package org.fourthline.cling.protocol.sync;
import org.fourthline.cling.UpnpService;
import org.fourthline.cling.binding.xml.DescriptorBindingException;
import org.fourthline.cling.binding.xml.DeviceDescriptorBinder;
import org.fourthline.cling.binding.xml.ServiceDescriptorBinder;
import org.fourthline.cling.model.message.StreamRequestMessage;
import org.fourthline.cling.model.message.StreamResponseMessage;
import org.fourthline.cling.model.message.UpnpResponse;
import org.fourthline.cling.model.message.header.ContentTypeHeader;
import org.fourthline.cling.model.message.header.ServerHeader;
import org.fourthline.cling.model.message.header.UpnpHeader;
import org.fourthline.cling.model.meta.Icon;
import org.fourthline.cling.model.meta.LocalDevice;
import org.fourthline.cling.model.meta.LocalService;
import org.fourthline.cling.model.resource.DeviceDescriptorResource;
import org.fourthline.cling.model.resource.IconResource;
import org.fourthline.cling.model.resource.Resource;
import org.fourthline.cling.model.resource.ServiceDescriptorResource;
import org.fourthline.cling.protocol.ReceivingSync;
import org.fourthline.cling.transport.RouterException;
import org.seamless.util.Exceptions;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Handles reception of device/service descriptor and icon retrieval messages.
*
* <p>
* Requested device and service XML descriptors are generated on-the-fly for every request.
* </p>
* <p>
* Descriptor XML is dynamically generated depending on the control point - some control
* points require different metadata than others for the same device and services.
* </p>
*
* @author Christian Bauer
*/
public class ReceivingRetrieval extends ReceivingSync<StreamRequestMessage, StreamResponseMessage> {
final private static Logger log = Logger.getLogger(ReceivingRetrieval.class.getName());
public ReceivingRetrieval(UpnpService upnpService, StreamRequestMessage inputMessage) {
super(upnpService, inputMessage);
}
protected StreamResponseMessage executeSync() throws RouterException {
if (!getInputMessage().hasHostHeader()) {
log.fine("Ignoring message, missing HOST header: " + getInputMessage());
return new StreamResponseMessage(new UpnpResponse(UpnpResponse.Status.PRECONDITION_FAILED));
}
URI requestedURI = getInputMessage().getOperation().getURI();
Resource foundResource = getUpnpService().getRegistry().getResource(requestedURI);
if (foundResource == null) {
foundResource = onResourceNotFound(requestedURI);
if (foundResource == null) {
log.fine("No local resource found: " + getInputMessage());
return null;
}
}
return createResponse(requestedURI, foundResource);
}
protected StreamResponseMessage createResponse(URI requestedURI, Resource resource) {
StreamResponseMessage response;
try {
if (DeviceDescriptorResource.class.isAssignableFrom(resource.getClass())) {
log.fine("Found local device matching relative request URI: " + requestedURI);
LocalDevice device = (LocalDevice) resource.getModel();
DeviceDescriptorBinder deviceDescriptorBinder =
getUpnpService().getConfiguration().getDeviceDescriptorBinderUDA10();
String deviceDescriptor = deviceDescriptorBinder.generate(
device,
getRemoteClientInfo(),
getUpnpService().getConfiguration().getNamespace()
);
response = new StreamResponseMessage(
deviceDescriptor,
new ContentTypeHeader(ContentTypeHeader.DEFAULT_CONTENT_TYPE)
);
} else if (ServiceDescriptorResource.class.isAssignableFrom(resource.getClass())) {
log.fine("Found local service matching relative request URI: " + requestedURI);
LocalService service = (LocalService) resource.getModel();
ServiceDescriptorBinder serviceDescriptorBinder =
getUpnpService().getConfiguration().getServiceDescriptorBinderUDA10();
String serviceDescriptor = serviceDescriptorBinder.generate(service);
response = new StreamResponseMessage(
serviceDescriptor,
new ContentTypeHeader(ContentTypeHeader.DEFAULT_CONTENT_TYPE)
);
} else if (IconResource.class.isAssignableFrom(resource.getClass())) {
log.fine("Found local icon matching relative request URI: " + requestedURI);
Icon icon = (Icon) resource.getModel();
response = new StreamResponseMessage(icon.getData(), icon.getMimeType());
} else {
log.fine("Ignoring GET for found local resource: " + resource);
return null;
}
} catch (DescriptorBindingException ex) {
log.warning("Error generating requested device/service descriptor: " + ex.toString());
log.log(Level.WARNING, "Exception root cause: ", Exceptions.unwrap(ex));
response = new StreamResponseMessage(UpnpResponse.Status.INTERNAL_SERVER_ERROR);
}
response.getHeaders().add(UpnpHeader.Type.SERVER, new ServerHeader());
return response;
}
/**
* Called if the {@link org.fourthline.cling.registry.Registry} had no result.
*
* @param requestedURIPath The requested URI path
* @return <code>null</code> or your own {@link Resource}
*/
protected Resource onResourceNotFound(URI requestedURIPath) {
return null;
}
}
|
/*-
* #%L
* anchor-plugin-io
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* 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.
* #L%
*/
package org.anchoranalysis.plugin.io.bean.summarizer.image;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import org.anchoranalysis.image.core.dimensions.Dimensions;
// Wrap with a nicer toString() representation
@AllArgsConstructor
@EqualsAndHashCode
class WrappedImageDim implements Comparable<WrappedImageDim> {
private final Dimensions dimensions;
@Override
public String toString() {
// Whether we display in 3d form or 2d is dependent on if there's more than 1 z-slice
if (dimensions.z() > 1) {
return String.format("%dx%dx%d", dimensions.x(), dimensions.y(), dimensions.z());
} else {
return String.format("%dx%d", dimensions.x(), dimensions.y());
}
}
@Override
public int compareTo(WrappedImageDim other) {
// Order by volume, smaller first
return Long.compare(dimensions.calculateVolume(), other.dimensions.calculateVolume());
}
}
|
package com.example.careshipapp.gui.activities;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.careshipapp.gui.adapters.ShowAllAdapter;
import com.example.careshipapp.gui.models.ShowAllModel;
import com.example.careshipapp.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class ShowAllActivity extends AppCompatActivity {
RecyclerView recyclerView;
ShowAllAdapter showAllAdapter;
List<ShowAllModel> showAllModelList;
Toolbar toolbar;
FirebaseFirestore firestore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_all);
toolbar = findViewById(R.id.show_all_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
String type = getIntent().getStringExtra("type");
firestore = FirebaseFirestore.getInstance();
recyclerView = findViewById(R.id.show_all_rec);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
showAllModelList = new ArrayList<>();
showAllAdapter = new ShowAllAdapter(this, showAllModelList);
recyclerView.setAdapter(showAllAdapter);
EditText editText = findViewById(R.id.editTextSearch);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
filter(editable.toString());
}
private void filter(String text){
ArrayList<ShowAllModel> filteredList = new ArrayList<>();
for(ShowAllModel model : showAllModelList){
if(model.getName().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(model);
}
}
showAllAdapter.filterList(filteredList);
}
});
if (type == null || type.isEmpty()) {
firestore.collection("ShowAll")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot doc : task.getResult().getDocuments()) {
ShowAllModel showAllModel = doc.toObject(ShowAllModel.class);
showAllModelList.add(showAllModel);
showAllAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(ShowAllActivity.this, "" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
if (type != null && type.equalsIgnoreCase("commoncold")) {
firestore.collection("ShowAll").whereEqualTo("type", "commoncold")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot doc : task.getResult().getDocuments()) {
ShowAllModel showAllModel = doc.toObject(ShowAllModel.class);
showAllModelList.add(showAllModel);
showAllAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(ShowAllActivity.this, "" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
if (type != null && type.equalsIgnoreCase("heartdisease")) {
firestore.collection("ShowAll").whereEqualTo("type", "heartdisease")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot doc : task.getResult().getDocuments()) {
ShowAllModel showAllModel = doc.toObject(ShowAllModel.class);
showAllModelList.add(showAllModel);
showAllAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(ShowAllActivity.this, "" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
if (type != null && type.equalsIgnoreCase("asthma")) {
firestore.collection("ShowAll").whereEqualTo("type", "asthma")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot doc : task.getResult().getDocuments()) {
ShowAllModel showAllModel = doc.toObject(ShowAllModel.class);
showAllModelList.add(showAllModel);
showAllAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(ShowAllActivity.this, "" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
if (type != null && type.equalsIgnoreCase("allergy")) {
firestore.collection("ShowAll").whereEqualTo("type", "allergy")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot doc : task.getResult().getDocuments()) {
ShowAllModel showAllModel = doc.toObject(ShowAllModel.class);
showAllModelList.add(showAllModel);
showAllAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(ShowAllActivity.this, "" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
if (type != null && type.equalsIgnoreCase("anxiety")) {
firestore.collection("ShowAll").whereEqualTo("type", "anxiety")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot doc : task.getResult().getDocuments()) {
ShowAllModel showAllModel = doc.toObject(ShowAllModel.class);
showAllModelList.add(showAllModel);
showAllAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(ShowAllActivity.this, "" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
|
/*
* Copyright 2016 MovingBlocks
*
* 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.terasology.particles.components.generators;
import org.joml.Vector2f;
import org.joml.Vector2i;
import org.terasology.entitySystem.Component;
import org.terasology.module.sandbox.API;
import org.terasology.rendering.assets.texture.Texture;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;
/**
* Generator used to choose a particle's textureOffset (from a tile-map texture)
*/
@API
public class TextureOffsetGeneratorComponent implements Component {
public List<Vector2f> validOffsets;
public TextureOffsetGeneratorComponent() {
this.validOffsets = new LinkedList<>();
}
/**
* @param validOffsets The offsets that the generator will choose from.
* Specify the offsets relative to the size of the image.
* For example: If you have a texture atlas with 6 images in a 4x2 grid, then your
* offsets would be:
* <ul>
* <li>(0.0, 0.0) for the leftmost image on the first row</li>
* <li>(0.75, 0.5) for the rightmost image on the second row</li>
* <li>(0.25, 0.0) for the second image on the first row</li>
* </ul
*/
public TextureOffsetGeneratorComponent(final Vector2f[] validOffsets) {
this.validOffsets = new LinkedList<>();
for (Vector2f offset : validOffsets) {
this.validOffsets.add(new Vector2f(offset));
}
}
/**
* @param atlas The texture atlas that is being used
* @param atlasSize How many textures the atlas contains in it's width and height.
* @param validTextures Indices of the valid textures
*/
public TextureOffsetGeneratorComponent(final Texture atlas, final Vector2i atlasSize, final Vector2i[] validTextures) {
final float textureWidth = atlas.getWidth() / (float) atlasSize.x();
final float textureHeight = atlas.getHeight() / (float) atlasSize.y();
Function<Vector2i, Vector2f> absolute2Relative = (absolute) -> new Vector2f(
absolute.x() * textureWidth,
absolute.y() * textureHeight
);
this.validOffsets = new LinkedList<>();
for (Vector2i offset : validTextures) {
this.validOffsets.add(absolute2Relative.apply(offset));
}
}
}
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.admanager.jaxws.v201811;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getExchangeRatesByStatementResponse element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getExchangeRatesByStatementResponse">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://www.google.com/apis/ads/publisher/v201811}ExchangeRatePage" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "getExchangeRatesByStatementResponse")
public class ExchangeRateServiceInterfacegetExchangeRatesByStatementResponse {
protected ExchangeRatePage rval;
/**
* Gets the value of the rval property.
*
* @return
* possible object is
* {@link ExchangeRatePage }
*
*/
public ExchangeRatePage getRval() {
return rval;
}
/**
* Sets the value of the rval property.
*
* @param value
* allowed object is
* {@link ExchangeRatePage }
*
*/
public void setRval(ExchangeRatePage value) {
this.rval = value;
}
}
|
package net.whg.graph;
import java.util.UUID;
/**
* Represents a connection showing how data should move from one node to another
* node within a graph. The connection is represented as moving from an output
* argument of node A to an input argument of node B.
*/
public class Connection {
private final Node nodeA;
private final Node nodeB;
private final int aIndex;
private final int bIndex;
private final UUID uuid;
/**
* Creates a new Connection instance between two nodes and their respective
* input and output argument indices.
*
* @param nodeA - The node that the connection is moving out of.
* @param aIndex - The output argument index of node A.
* @param nodeB - The node that the connection is moving in to.
* @param bIndex - The input argument index of node B.
*/
public Connection(Node nodeA, int aIndex, Node nodeB, int bIndex) {
this.nodeA = nodeA;
this.nodeB = nodeB;
this.aIndex = aIndex;
this.bIndex = bIndex;
uuid = UUID.randomUUID();
}
/**
* Gets the node this connection is coming out of.
*
* @return The node.
*/
public Node nodeA() {
return nodeA;
}
/**
* Gets the node this connection is going in to.
*
* @return The node.
*/
public Node nodeB() {
return nodeB;
}
/**
* Gets the output argument index of the node this connection is coming out of.
*
* @return The argument index.
*/
public int aIndex() {
return aIndex;
}
/**
* Gets the input argument index of the node this connection is going in to.
*
* @return The argument index.
*/
public int bIndex() {
return bIndex;
}
/**
* Gets the UUID of this connection instance.
*
* @return The UUID.
*/
public UUID uuid() {
return uuid;
}
}
|
package io.swagger.api;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.log.Log;
import io.swagger.model.Sbz001aReq;
import io.swagger.model.Sbz001aRes;
import io.swagger.service.Sbz001Service;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-12-29T06:09:07.235Z[GMT]")
@Tag(name = "SampleBizSvA")
@RestController
public class Sbz001ApiController implements Sbz001Api {
private static final Logger log = LoggerFactory.getLogger(Sbz001ApiController.class);
private final ObjectMapper objectMapper;
private final HttpServletRequest request;
@Autowired
private Sbz001Service service;
@org.springframework.beans.factory.annotation.Autowired
public Sbz001ApiController(ObjectMapper objectMapper, HttpServletRequest request) {
this.objectMapper = objectMapper;
this.request = request;
}
@Log
public ResponseEntity<Sbz001aRes> sbz001(
@Parameter(in = ParameterIn.DEFAULT, description = "description here", required = true, schema = @Schema()) @Valid @RequestBody Sbz001aReq body) {
String accept = request.getHeader("Accept");
if (accept == null || !accept.contains("application/json")) {
return new ResponseEntity<Sbz001aRes>(HttpStatus.BAD_REQUEST);
}
Sbz001aRes res = service.execute(body);
return new ResponseEntity<Sbz001aRes>(res, HttpStatus.OK);
}
}
|
package Abstract_class.Abs_01;
public abstract class Abs_01_1 {
public abstract void eat();
public void sleep() {
System.out.println("sleep");
}
public final int i ;
public Abs_01_1(int i) {
super();
this.i = i;
}
}
|
/*
* Copyright 2016 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.profiler.instrument;
import com.navercorp.pinpoint.profiler.instrument.interceptor.InterceptorDefinition;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.List;
/**
* @author jaehong.kim
*/
public class ASMMethodNodeAdapter {
private final String declaringClassInternalName;
private final MethodNode methodNode;
private final ASMMethodVariables methodVariables;
public ASMMethodNodeAdapter(final String declaringClassInternalName, final MethodNode methodNode) {
if (declaringClassInternalName == null || methodNode == null) {
throw new IllegalArgumentException("declaring class internal name and method annotation must not be null. class=" + declaringClassInternalName + ", methodNode=" + methodNode);
}
if (methodNode.instructions == null || methodNode.desc == null) {
throw new IllegalArgumentException("method annotation's instructions or desc must not be null. class=" + declaringClassInternalName + ", method=" + methodNode.name + methodNode.desc);
}
this.declaringClassInternalName = declaringClassInternalName;
this.methodNode = methodNode;
this.methodVariables = new ASMMethodVariables(declaringClassInternalName, methodNode);
}
public MethodNode getMethodNode() {
return this.methodNode;
}
public String getDeclaringClassInternalName() {
return this.declaringClassInternalName;
}
// find interceptor local variable.
public boolean hasInterceptor() {
return this.methodVariables.hasInterceptor();
}
public String getName() {
if (isConstructor()) {
// simple class name.
int index = this.declaringClassInternalName.lastIndexOf('/');
if (index < 0) {
return this.declaringClassInternalName;
} else {
return this.declaringClassInternalName.substring(index + 1);
}
}
return this.methodNode.name;
}
public void setName(final String name) {
if (isConstructor()) {
// skip.
return;
}
this.methodNode.name = name;
}
public String[] getParameterTypes() {
return this.methodVariables.getParameterTypes();
}
public String[] getParameterNames() {
return this.methodVariables.getParameterNames();
}
public String getReturnType() {
return this.methodVariables.getReturnType();
}
public int getAccess() {
return this.methodNode.access;
}
public void setAccess(final int access) {
this.methodNode.access = access;
}
public boolean isConstructor() {
return this.methodNode.name.equals("<init>");
}
public String getDesc() {
return this.methodNode.desc;
}
public int getLineNumber() {
AbstractInsnNode node = this.methodNode.instructions.getFirst();
while (node != null) {
if (node.getType() == AbstractInsnNode.LINE) {
return ((LineNumberNode) node).line;
}
node = node.getNext();
}
return 0;
}
public List<String> getExceptions() {
return this.methodNode.exceptions;
}
public String getSignature() {
return this.methodNode.signature;
}
public String getLongName() {
return this.declaringClassInternalName + "/" + getName() + getDesc();
}
public boolean isStatic() {
return (this.methodNode.access & Opcodes.ACC_STATIC) != 0;
}
public boolean isAbstract() {
return (this.methodNode.access & Opcodes.ACC_ABSTRACT) != 0;
}
public boolean isPrivate() {
return (this.methodNode.access & Opcodes.ACC_PRIVATE) != 0;
}
public boolean isNative() {
return (this.methodNode.access & Opcodes.ACC_NATIVE) != 0;
}
public boolean hasAnnotation(final Class<?> annotationClass) {
if (annotationClass == null) {
return false;
}
final String desc = Type.getDescriptor(annotationClass);
return hasAnnotation(desc, this.methodNode.invisibleAnnotations) || hasAnnotation(desc, this.methodNode.visibleAnnotations);
}
private boolean hasAnnotation(final String annotationClassDesc, final List<AnnotationNode> annotationNodes) {
if (annotationClassDesc == null || annotationNodes == null) {
return false;
}
for (AnnotationNode annotation : annotationNodes) {
if (annotation.desc != null && annotation.desc.equals(annotationClassDesc)) {
return true;
}
}
return false;
}
public void addDelegator(final String superClassInternalName) {
if (superClassInternalName == null) {
throw new NullPointerException("super class internal name");
}
final InsnList instructions = this.methodNode.instructions;
if (isStatic()) {
this.methodVariables.initLocalVariables(instructions);
// load parameters
this.methodVariables.loadArgs(instructions);
// invoke static
instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, superClassInternalName, this.methodNode.name, this.methodNode.desc, false));
} else {
this.methodVariables.initLocalVariables(instructions);
// load this
this.methodVariables.loadVar(instructions, 0);
// load parameters
this.methodVariables.loadArgs(instructions);
// invoke special
instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, superClassInternalName, this.methodNode.name, this.methodNode.desc, false));
}
// return
this.methodVariables.returnValue(instructions);
}
public void rename(final String name) {
if (name == null) {
throw new IllegalArgumentException("methodName");
}
final ASMMethodInsnNodeRemapper.Builder remapBuilder = new ASMMethodInsnNodeRemapper.Builder();
remapBuilder.addFilter(this.declaringClassInternalName, this.methodNode.name, this.methodNode.desc);
remapBuilder.setName(name);
// change recursive call.
ASMMethodInsnNodeRemapper remapper = remapBuilder.build();
remapMethodInsnNode(remapper);
// change name.
this.methodNode.name = name;
}
public void remapMethodInsnNode(final ASMMethodInsnNodeRemapper remapper) {
AbstractInsnNode insnNode = this.methodNode.instructions.getFirst();
while (insnNode != null) {
if (insnNode instanceof MethodInsnNode) {
final MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode;
remapper.mapping(methodInsnNode);
}
insnNode = insnNode.getNext();
}
}
public void remapLocalVariables(final String name, final String desc) {
if (methodNode.localVariables == null) {
return;
}
final List<LocalVariableNode> localVariableNodes = methodNode.localVariables;
for (LocalVariableNode node : localVariableNodes) {
if (node.name.equals(name)) {
node.desc = desc;
}
}
}
private void initInterceptorLocalVariables(final int interceptorId, final InterceptorDefinition interceptorDefinition, final int apiId) {
final InsnList instructions = new InsnList();
if (this.methodVariables.initInterceptorLocalVariables(instructions, interceptorId, interceptorDefinition, apiId)) {
// if first time.
this.methodNode.instructions.insertBefore(this.methodVariables.getEnterInsnNode(), instructions);
}
}
public void addBeforeInterceptor(final int interceptorId, final InterceptorDefinition interceptorDefinition, final int apiId) {
initInterceptorLocalVariables(interceptorId, interceptorDefinition, apiId);
final InsnList instructions = new InsnList();
this.methodVariables.loadInterceptorLocalVariables(instructions, interceptorDefinition, false);
// cong.x.guo: 这里嵌入before的代码 before()
final String description = Type.getMethodDescriptor(interceptorDefinition.getBeforeMethod());
instructions.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, Type.getInternalName(interceptorDefinition.getInterceptorBaseClass()), "before", description, true));
this.methodNode.instructions.insertBefore(this.methodVariables.getEnterInsnNode(), instructions);
}
public void addAfterInterceptor(final int interceptorId, final InterceptorDefinition interceptorDefinition, final int apiId) {
initInterceptorLocalVariables(interceptorId, interceptorDefinition, apiId);
// add try catch block.
final ASMTryCatch tryCatch = new ASMTryCatch(this.methodNode);
this.methodNode.instructions.insertBefore(this.methodVariables.getEnterInsnNode(), tryCatch.getStartLabelNode());
this.methodNode.instructions.insert(this.methodVariables.getExitInsnNode(), tryCatch.getEndLabelNode());
// find return.
AbstractInsnNode insnNode = this.methodNode.instructions.getFirst();
while (insnNode != null) {
final int opcode = insnNode.getOpcode();
if (this.methodVariables.isReturnCode(opcode)) {
final InsnList instructions = new InsnList();
this.methodVariables.storeResultVar(instructions, opcode);
invokeAfterInterceptor(instructions, interceptorDefinition, false);
this.methodNode.instructions.insertBefore(insnNode, instructions);
}
insnNode = insnNode.getNext();
}
// try catch handler.
InsnList instructions = new InsnList();
this.methodVariables.storeThrowableVar(instructions);
invokeAfterInterceptor(instructions, interceptorDefinition, true);
// throw exception.
this.methodVariables.loadInterceptorThrowVar(instructions);
this.methodNode.instructions.insert(tryCatch.getEndLabelNode(), instructions);
tryCatch.sort();
}
private void invokeAfterInterceptor(final InsnList instructions, final InterceptorDefinition interceptorDefinition, final boolean throwable) {
this.methodVariables.loadInterceptorLocalVariables(instructions, interceptorDefinition, true);
final String description = Type.getMethodDescriptor(interceptorDefinition.getAfterMethod());
instructions.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, Type.getInternalName(interceptorDefinition.getInterceptorBaseClass()), "after", description, true));
}
}
|
package com.luomor.coco.mp.common.utils;
import java.security.MessageDigest;
import java.util.Objects;
/**
* MD5加密工具类
*/
public class MD5Util {
private static final String DEFAULT_MD_5_SALT = "fjdsl321312kf349832&*^*903294[JNLIUIK]%fsdjfkl";//加盐md5盐值
/**
* 获得字符串的md5值
*
* @return md5加密后的字符串
*/
public static String getMd5(String s) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 校验字符串的md5值
*
* @param str 目标字符串
* @param md5 基准md5
* @return 校验结果
*/
public static boolean checkMd5(String str, String md5) {
return Objects.requireNonNull(getMd5(str)).equalsIgnoreCase(md5);
}
/**
* 获得加盐md5,算法过程是原字符串md5后连接加盐字符串后再进行md5
*
* @param str 待加密的字符串
* @param salt 盐
* @return 加盐md5
*/
public static String getMd5AndSalt(String str, String salt) {
return getMd5(Objects.requireNonNull(getMd5(str)).concat(salt));
}
/**
* 获得加盐md5,算法过程是原字符串md5后连接加盐字符串后再进行md5
* 使用默认盐值
*
* @param str 待加密的字符串
* @return 加盐md5
*/
public static String getMd5AndSalt(String str) {
return getMd5(Objects.requireNonNull(getMd5(str)).concat(DEFAULT_MD_5_SALT));
}
}
|
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.editor.impl.softwrap;
/**
* Strategy interface for ruling if soft wraps should be processed.
* <p/>
* Implementations of this interface are not obliged to be thread-safe.
*
* @author Denis Zhdanov
* @since 10/6/10 8:08 AM
*/
public interface SoftWrapApplianceStrategy {
/**
* Allows to answer if soft wraps should be processed.
*
* @return <code>true</code> if soft wraps should be processed; <code>false</code> otherwise
*/
boolean processSoftWraps();
}
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2020 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.model.sql.parser;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.ExpressionVisitor;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.parser.SimpleNode;
/**
* CustomExpression
*/
public class CustomExpression implements Expression {
private final String expression;
private SimpleNode simpleNode;
public CustomExpression(String expression) {
this.expression = expression;
}
@Override
public void accept(ExpressionVisitor expressionVisitor) {
expressionVisitor.visit(new StringValue(expression));
}
@Override
public String toString() {
return expression;
}
@Override
public SimpleNode getASTNode() {
return simpleNode;
}
@Override
public void setASTNode(SimpleNode simpleNode) {
this.simpleNode = simpleNode;
}
}
|
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.roger.missview.library.util;
import android.graphics.Bitmap;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import static android.graphics.BitmapFactory.Options;
/**
* Wrapper for {@link android.graphics.BitmapRegionDecoder} with some extra functionality.
*/
public class BitmapRegionLoader {
private boolean mValid = false;
private int mRotation = 0;
private int mOriginalWidth;
private int mOriginalHeight;
private Rect mTempRect = new Rect();
private InputStream mInputStream;
private volatile BitmapRegionDecoder mBitmapRegionDecoder;
private Matrix mRotateMatrix;
public static BitmapRegionLoader newInstance(InputStream in) {
return newInstance(in, 0);
}
public static BitmapRegionLoader newInstance(InputStream in, int rotation) {
if (in == null) {
Log.e("BitmapRegionLoader", "InputStream is null!");
return null;
}
BitmapRegionLoader loader = new BitmapRegionLoader(in);
if (loader.mValid) {
loader.mRotation = rotation;
if (loader.mRotation != 0) {
loader.mRotateMatrix = new Matrix();
loader.mRotateMatrix.postRotate(rotation);
}
return loader;
}
return null;
}
private BitmapRegionLoader(InputStream in) {
mInputStream = in;
try {
mBitmapRegionDecoder = BitmapRegionDecoder.newInstance(in, false);
mOriginalWidth = mBitmapRegionDecoder.getWidth();
mOriginalHeight = mBitmapRegionDecoder.getHeight();
mValid = true;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Key difference, aside from support for ration, from
* {@link android.graphics.BitmapRegionDecoder#decodeRegion(android.graphics.Rect, android.graphics.BitmapFactory.Options)} in this implementation is that even
* if <code>inBitmap</code> is given, a sub-bitmap might be returned.
*/
public synchronized Bitmap decodeRegion(Rect rect, Options options) {
int unsampledInBitmapWidth = -1;
int unsampledInBitmapHeight = -1;
int sampleSize = Math.max(1, options != null ? options.inSampleSize : 1);
if (options != null && options.inBitmap != null) {
unsampledInBitmapWidth = options.inBitmap.getWidth() * sampleSize;
unsampledInBitmapHeight = options.inBitmap.getHeight() * sampleSize;
}
// Decode with rotation
switch (mRotation) {
case 90:
mTempRect.set(
rect.top, mOriginalHeight - rect.right,
rect.bottom, mOriginalHeight - rect.left);
break;
case 180:
mTempRect.set(
mOriginalWidth - rect.right, mOriginalHeight - rect.bottom,
mOriginalWidth - rect.left, mOriginalHeight - rect.top);
break;
case 270:
mTempRect.set(
mOriginalWidth - rect.bottom, rect.left,
mOriginalWidth - rect.top, rect.right);
break;
default:
mTempRect.set(rect);
}
Bitmap bitmap = mBitmapRegionDecoder.decodeRegion(mTempRect, options);
if (options != null && options.inBitmap != null &&
((mTempRect.width() != unsampledInBitmapWidth
|| mTempRect.height() != unsampledInBitmapHeight))) {
// Need to extract the sub-bitmap
Bitmap subBitmap = Bitmap.createBitmap(
bitmap, 0, 0,
mTempRect.width() / sampleSize,
mTempRect.height() / sampleSize);
if (bitmap != options.inBitmap) {
bitmap.recycle();
}
bitmap = subBitmap;
}
if (mRotateMatrix != null) {
// Rotate decoded bitmap
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(),
mRotateMatrix, true);
if (options == null || bitmap != options.inBitmap) {
bitmap.recycle();
}
bitmap = rotatedBitmap;
}
return bitmap;
}
public synchronized int getWidth() {
return (mRotation == 90 || mRotation == 270) ? mOriginalHeight : mOriginalWidth;
}
public synchronized int getHeight() {
return (mRotation == 90 || mRotation == 270) ? mOriginalWidth : mOriginalHeight;
}
public synchronized void destroy() {
mBitmapRegionDecoder.recycle();
mBitmapRegionDecoder = null;
try {
mInputStream.close();
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
}
|
/**
* 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.bookkeeper.mledger;
import java.util.List;
import com.google.common.base.Predicate;
import com.google.common.collect.Range;
import org.apache.bookkeeper.common.annotation.InterfaceAudience;
import org.apache.bookkeeper.common.annotation.InterfaceStability;
import org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback;
import org.apache.bookkeeper.mledger.impl.PositionImpl;
@InterfaceAudience.LimitedPrivate
@InterfaceStability.Stable
public interface ReadOnlyCursor {
/**
* Read entries from the ManagedLedger, up to the specified number. The returned list can be smaller.
*
* @param numberOfEntriesToRead maximum number of entries to return
* @return the list of entries
* @throws ManagedLedgerException
*/
List<Entry> readEntries(int numberOfEntriesToRead) throws InterruptedException, ManagedLedgerException;
/**
* Asynchronously read entries from the ManagedLedger.
*
* @param numberOfEntriesToRead maximum number of entries to return
* @param callback callback object
* @param ctx opaque context
* @see #readEntries(int)
*/
void asyncReadEntries(int numberOfEntriesToRead, ReadEntriesCallback callback, Object ctx);
/**
* Get the read position. This points to the next message to be read from the cursor.
*
* @return the read position
*/
Position getReadPosition();
/**
* Tells whether this cursor has already consumed all the available entries.
* <p>
* <p/>
* This method is not blocking.
*
* @return true if there are pending entries to read, false otherwise
*/
boolean hasMoreEntries();
/**
* Return the number of messages that this cursor still has to read.
* <p>
* <p/>
* This method has linear time complexity on the number of ledgers included in the managed ledger.
*
* @return the number of entries
*/
long getNumberOfEntries();
/**
* Skip n entries from the read position of this cursor.
*
* @param numEntriesToSkip number of entries to skip
*/
void skipEntries(int numEntriesToSkip);
/**
* Find the newest entry that matches the given predicate.
*
* @param constraint search only active entries or all entries
* @param condition predicate that reads an entry an applies a condition
* @return Position of the newest entry that matches the given predicate
* @throws InterruptedException
* @throws ManagedLedgerException
*/
Position findNewestMatching(ManagedCursor.FindPositionConstraint constraint, Predicate<Entry> condition) throws InterruptedException, ManagedLedgerException;
/**
* Return the number of messages that this cursor still has to read.
*
* <p/>This method has linear time complexity on the number of ledgers included in the managed ledger.
*
* @param range the range between two positions
* @return the number of entries in range
*/
long getNumberOfEntries(Range<PositionImpl> range);
/**
* Close the cursor and releases the associated resources.
*
* @throws InterruptedException
* @throws ManagedLedgerException
*/
void close() throws InterruptedException, ManagedLedgerException;
/**
* Close the cursor asynchronously and release the associated resources.
*
* @param callback callback object
* @param ctx opaque context
*/
void asyncClose(AsyncCallbacks.CloseCallback callback, Object ctx);
}
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.nn;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TInt32;
import org.tensorflow.types.TInt64;
import org.tensorflow.types.family.TNumber;
/**
* Calculates the CTC Loss (log probability) for each batch entry. Also calculates
* the gradient. This class performs the softmax operation for you, so inputs
* should be e.g. linear projections of outputs by an LSTM.
*
* @param <T> data type for {@code loss} output
*/
@Operator(
group = "nn"
)
public final class CtcLoss<T extends TNumber> extends RawOp {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "CTCLoss";
private Output<T> loss;
private Output<T> gradient;
private CtcLoss(Operation operation) {
super(operation);
int outputIdx = 0;
loss = operation.output(outputIdx++);
gradient = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new CTCLoss operation.
*
* @param scope current scope
* @param inputs 3-D, shape: {@code (max_time x batch_size x num_classes)}, the logits.
* @param labelsIndices The indices of a {@code SparseTensor<int32, 2>}.
* {@code labels_indices(i, :) == [b, t]} means {@code labels_values(i)} stores the id for
* {@code (batch b, time t)}.
* @param labelsValues The values (labels) associated with the given batch and time.
* @param sequenceLength A vector containing sequence lengths (batch).
* @param options carries optional attribute values
* @param <T> data type for {@code CTCLoss} output and operands
* @return a new instance of CtcLoss
*/
@Endpoint(
describeByClass = true
)
public static <T extends TNumber> CtcLoss<T> create(Scope scope, Operand<T> inputs,
Operand<TInt64> labelsIndices, Operand<TInt32> labelsValues, Operand<TInt32> sequenceLength,
Options... options) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "CtcLoss");
opBuilder.addInput(inputs.asOutput());
opBuilder.addInput(labelsIndices.asOutput());
opBuilder.addInput(labelsValues.asOutput());
opBuilder.addInput(sequenceLength.asOutput());
if (options != null) {
for (Options opts : options) {
if (opts.preprocessCollapseRepeated != null) {
opBuilder.setAttr("preprocess_collapse_repeated", opts.preprocessCollapseRepeated);
}
if (opts.ctcMergeRepeated != null) {
opBuilder.setAttr("ctc_merge_repeated", opts.ctcMergeRepeated);
}
if (opts.ignoreLongerOutputsThanInputs != null) {
opBuilder.setAttr("ignore_longer_outputs_than_inputs", opts.ignoreLongerOutputsThanInputs);
}
}
}
return new CtcLoss<>(opBuilder.build());
}
/**
* Sets the preprocessCollapseRepeated option.
*
* @param preprocessCollapseRepeated Scalar, if true then repeated labels are
* collapsed prior to the CTC calculation.
* @return this Options instance.
*/
public static Options preprocessCollapseRepeated(Boolean preprocessCollapseRepeated) {
return new Options().preprocessCollapseRepeated(preprocessCollapseRepeated);
}
/**
* Sets the ctcMergeRepeated option.
*
* @param ctcMergeRepeated Scalar. If set to false, <em>during</em> CTC calculation
* repeated non-blank labels will not be merged and are interpreted as
* individual labels. This is a simplified version of CTC.
* @return this Options instance.
*/
public static Options ctcMergeRepeated(Boolean ctcMergeRepeated) {
return new Options().ctcMergeRepeated(ctcMergeRepeated);
}
/**
* Sets the ignoreLongerOutputsThanInputs option.
*
* @param ignoreLongerOutputsThanInputs Scalar. If set to true, during CTC
* calculation, items that have longer output sequences than input sequences
* are skipped: they don't contribute to the loss term and have zero-gradient.
* @return this Options instance.
*/
public static Options ignoreLongerOutputsThanInputs(Boolean ignoreLongerOutputsThanInputs) {
return new Options().ignoreLongerOutputsThanInputs(ignoreLongerOutputsThanInputs);
}
/**
* Gets loss.
* A vector (batch) containing log-probabilities.
* @return loss.
*/
public Output<T> loss() {
return loss;
}
/**
* Gets gradient.
* The gradient of {@code loss}. 3-D, shape:
* {@code (max_time x batch_size x num_classes)}.
* @return gradient.
*/
public Output<T> gradient() {
return gradient;
}
/**
* Optional attributes for {@link org.tensorflow.op.nn.CtcLoss}
*/
public static class Options {
private Boolean preprocessCollapseRepeated;
private Boolean ctcMergeRepeated;
private Boolean ignoreLongerOutputsThanInputs;
private Options() {
}
/**
* Sets the preprocessCollapseRepeated option.
*
* @param preprocessCollapseRepeated Scalar, if true then repeated labels are
* collapsed prior to the CTC calculation.
* @return this Options instance.
*/
public Options preprocessCollapseRepeated(Boolean preprocessCollapseRepeated) {
this.preprocessCollapseRepeated = preprocessCollapseRepeated;
return this;
}
/**
* Sets the ctcMergeRepeated option.
*
* @param ctcMergeRepeated Scalar. If set to false, <em>during</em> CTC calculation
* repeated non-blank labels will not be merged and are interpreted as
* individual labels. This is a simplified version of CTC.
* @return this Options instance.
*/
public Options ctcMergeRepeated(Boolean ctcMergeRepeated) {
this.ctcMergeRepeated = ctcMergeRepeated;
return this;
}
/**
* Sets the ignoreLongerOutputsThanInputs option.
*
* @param ignoreLongerOutputsThanInputs Scalar. If set to true, during CTC
* calculation, items that have longer output sequences than input sequences
* are skipped: they don't contribute to the loss term and have zero-gradient.
* @return this Options instance.
*/
public Options ignoreLongerOutputsThanInputs(Boolean ignoreLongerOutputsThanInputs) {
this.ignoreLongerOutputsThanInputs = ignoreLongerOutputsThanInputs;
return this;
}
}
public static class Inputs<T extends TNumber> extends RawOpInputs<CtcLoss<T>> {
/**
* 3-D, shape: {@code (max_time x batch_size x num_classes)}, the logits.
*/
public final Operand<T> inputs;
/**
* The indices of a {@code SparseTensor<int32, 2>}.
* {@code labels_indices(i, :) == [b, t]} means {@code labels_values(i)} stores the id for
* {@code (batch b, time t)}.
*/
public final Operand<TInt64> labelsIndices;
/**
* The values (labels) associated with the given batch and time.
*/
public final Operand<TInt32> labelsValues;
/**
* A vector containing sequence lengths (batch).
*/
public final Operand<TInt32> sequenceLength;
/**
* Scalar, if true then repeated labels are
* collapsed prior to the CTC calculation.
*/
public final boolean preprocessCollapseRepeated;
/**
* Scalar. If set to false, *during* CTC calculation
* repeated non-blank labels will not be merged and are interpreted as
* individual labels. This is a simplified version of CTC.
*/
public final boolean ctcMergeRepeated;
/**
* Scalar. If set to true, during CTC
* calculation, items that have longer output sequences than input sequences
* are skipped: they don't contribute to the loss term and have zero-gradient.
*/
public final boolean ignoreLongerOutputsThanInputs;
/**
* The T attribute
*/
public final DataType T;
public Inputs(GraphOperation op) {
super(new CtcLoss<>(op), op, Arrays.asList("preprocess_collapse_repeated", "ctc_merge_repeated", "ignore_longer_outputs_than_inputs", "T"));
int inputIndex = 0;
inputs = (Operand<T>) op.input(inputIndex++);
labelsIndices = (Operand<TInt64>) op.input(inputIndex++);
labelsValues = (Operand<TInt32>) op.input(inputIndex++);
sequenceLength = (Operand<TInt32>) op.input(inputIndex++);
preprocessCollapseRepeated = op.attributes().getAttrBool("preprocess_collapse_repeated");
ctcMergeRepeated = op.attributes().getAttrBool("ctc_merge_repeated");
ignoreLongerOutputsThanInputs = op.attributes().getAttrBool("ignore_longer_outputs_than_inputs");
T = op.attributes().getAttrType("T");
}
}
}
|
/*
* (C) Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* qiong.wang (夜色)
*/
package com.wq.wqchat.common.message;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import com.wq.wqchat.api.Message;
import com.wq.wqchat.api.connection.Connection;
import com.wq.wqchat.api.connection.SessionContext;
import com.wq.wqchat.api.protocol.Packet;
import com.wq.wqchat.tools.common.IOUtils;
import com.wq.wqchat.tools.common.Profiler;
import com.wq.wqchat.tools.config.CC;
import io.netty.channel.ChannelFutureListener;
public abstract class BaseMessage implements Message {
private static final byte STATUS_DECODED = 1;
private static final byte STATUS_ENCODED = 2;
private static final AtomicInteger ID_SEQ = new AtomicInteger();
transient protected Packet packet;
transient protected Connection connection;
transient private byte status = 0;
public BaseMessage(Packet packet, Connection connection) {
this.packet = packet;
this.connection = connection;
}
@Override
public void decodeBody() {
if ((status & STATUS_DECODED) == 0) {
status |= STATUS_DECODED;
if (packet.getBodyLength() > 0) {
if (packet.hasFlag(Packet.FLAG_JSON_BODY)) {
decodeJsonBody0();
} else {
decodeBinaryBody0();
}
}
}
}
@Override
public void encodeBody() {
if ((status & STATUS_ENCODED) == 0) {
status |= STATUS_ENCODED;
if (packet.hasFlag(Packet.FLAG_JSON_BODY)) {
encodeJsonBody0();
} else {
encodeBinaryBody0();
}
}
}
private void decodeBinaryBody0() {
//1.解密
byte[] tmp = packet.body;
if (packet.hasFlag(Packet.FLAG_CRYPTO)) {
if (connection.getSessionContext().cipher != null) {
tmp = connection.getSessionContext().cipher.decrypt(tmp);
}
}
//2.解压
if (packet.hasFlag(Packet.FLAG_COMPRESS)) {
tmp = IOUtils.decompress(tmp);
}
if (tmp.length == 0) {
throw new RuntimeException("message decode ex");
}
packet.body = tmp;
Profiler.enter("time cost on [body decode]");
decode(packet.body);
Profiler.release();
packet.body = null;// 释放内存
}
private void encodeBinaryBody0() {
Profiler.enter("time cost on [body encode]");
byte[] tmp = encode();
Profiler.release();
if (tmp != null && tmp.length > 0) {
//1.压缩
if (tmp.length > CC.mp.core.compress_threshold) {
byte[] result = IOUtils.compress(tmp);
if (result.length > 0) {
tmp = result;
packet.addFlag(Packet.FLAG_COMPRESS);
}
}
//2.加密
SessionContext context = connection.getSessionContext();
if (context.cipher != null) {
byte[] result = context.cipher.encrypt(tmp);
if (result.length > 0) {
tmp = result;
packet.addFlag(Packet.FLAG_CRYPTO);
}
}
packet.body = tmp;
}
}
private void decodeJsonBody0() {
Map<String, Object> body = packet.getBody();
decodeJsonBody(body);
}
private void encodeJsonBody0() {
packet.setBody(encodeJsonBody());
}
private void encodeBodyRaw() {
if ((status & STATUS_ENCODED) == 0) {
status |= STATUS_ENCODED;
if (packet.hasFlag(Packet.FLAG_JSON_BODY)) {
encodeJsonBody0();
} else {
packet.body = encode();
}
}
}
public abstract void decode(byte[] body);
public abstract byte[] encode();
protected void decodeJsonBody(Map<String, Object> body) {
}
protected Map<String, Object> encodeJsonBody() {
return null;
}
@Override
public Packet getPacket() {
return packet;
}
@Override
public Connection getConnection() {
return connection;
}
@Override
public void send(ChannelFutureListener listener) {
encodeBody();
connection.send(packet, listener);
}
@Override
public void sendRaw(ChannelFutureListener listener) {
encodeBodyRaw();
connection.send(packet, listener);
}
public void send() {
send(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
public void sendRaw() {
sendRaw(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
public void close() {
send(ChannelFutureListener.CLOSE);
}
protected static int genSessionId() {
return ID_SEQ.incrementAndGet();
}
public int getSessionId() {
return packet.sessionId;
}
public BaseMessage setRecipient(InetSocketAddress recipient) {
packet.setRecipient(recipient);
return this;
}
public void setPacket(Packet packet) {
this.packet = packet;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
public ScheduledExecutorService getExecutor() {
return connection.getChannel().eventLoop();
}
public void runInRequestThread(Runnable runnable) {
connection.getChannel().eventLoop().execute(runnable);
}
@Override
public abstract String toString();
}
|
package net.minecraft.world.level.chunk;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.mojang.datafixers.util.Either;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;
import javax.annotation.Nullable;
import net.minecraft.Util;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ThreadedLevelLightEngine;
import net.minecraft.server.level.WorldGenRegion;
import net.minecraft.util.profiling.jfr.JvmProfiler;
import net.minecraft.util.profiling.jfr.callback.ProfiledDuration;
import net.minecraft.world.level.levelgen.BelowZeroRetrogen;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.blending.Blender;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureManager;
/**
* The statuses that chunks go through during different phases of generation and loading.
* Each status has an asynchronous task that is completed to generate a chunk, and one to load a chunk up to that
* status.
* Chunks are generated in sequential stages, some of which rely on nearby chunks from the previous stage. To this
* respect, tasks define a "range" that they require chunks to be generated up to the previous stage. This is
* responsible for the concentric squares seen in the chunk loading screen.
*/
public class ChunkStatus extends net.minecraftforge.registries.ForgeRegistryEntry<ChunkStatus> {
public static final int MAX_STRUCTURE_DISTANCE = 8;
private static final EnumSet<Heightmap.Types> PRE_FEATURES = EnumSet.of(Heightmap.Types.OCEAN_FLOOR_WG, Heightmap.Types.WORLD_SURFACE_WG);
public static final EnumSet<Heightmap.Types> POST_FEATURES = EnumSet.of(Heightmap.Types.OCEAN_FLOOR, Heightmap.Types.WORLD_SURFACE, Heightmap.Types.MOTION_BLOCKING, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES);
private static final ChunkStatus.LoadingTask PASSTHROUGH_LOAD_TASK = (p_62461_, p_62462_, p_62463_, p_62464_, p_62465_, p_62466_) -> {
if (p_62466_ instanceof ProtoChunk) {
ProtoChunk protochunk = (ProtoChunk)p_62466_;
if (!p_62466_.getStatus().isOrAfter(p_62461_)) {
protochunk.setStatus(p_62461_);
}
}
return CompletableFuture.completedFuture(Either.left(p_62466_));
};
public static final ChunkStatus EMPTY = registerSimple("empty", (ChunkStatus)null, -1, PRE_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_156307_, p_156308_, p_156309_, p_156310_, p_156311_) -> {
});
public static final ChunkStatus STRUCTURE_STARTS = register("structure_starts", EMPTY, 0, PRE_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_187861_, p_187862_, p_187863_, p_187864_, p_187865_, p_187866_, p_187867_, p_187868_, p_187869_, p_187870_) -> {
if (!p_187869_.getStatus().isOrAfter(p_187861_)) {
if (p_187863_.getServer().getWorldData().worldGenSettings().generateFeatures()) {
p_187864_.createStructures(p_187863_.registryAccess(), p_187863_.structureFeatureManager(), p_187869_, p_187865_, p_187863_.getSeed());
}
if (p_187869_ instanceof ProtoChunk) {
ProtoChunk protochunk = (ProtoChunk)p_187869_;
protochunk.setStatus(p_187861_);
}
p_187863_.onStructureStartsAvailable(p_187869_);
}
return CompletableFuture.completedFuture(Either.left(p_187869_));
}, (p_196811_, p_196812_, p_196813_, p_196814_, p_196815_, p_196816_) -> {
if (!p_196816_.getStatus().isOrAfter(p_196811_)) {
if (p_196816_ instanceof ProtoChunk) {
ProtoChunk protochunk = (ProtoChunk)p_196816_;
protochunk.setStatus(p_196811_);
}
p_196812_.onStructureStartsAvailable(p_196816_);
}
return CompletableFuture.completedFuture(Either.left(p_196816_));
});
public static final ChunkStatus STRUCTURE_REFERENCES = registerSimple("structure_references", STRUCTURE_STARTS, 8, PRE_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_196843_, p_196844_, p_196845_, p_196846_, p_196847_) -> {
WorldGenRegion worldgenregion = new WorldGenRegion(p_196844_, p_196846_, p_196843_, -1);
p_196845_.createReferences(worldgenregion, p_196844_.structureFeatureManager().forWorldGenRegion(worldgenregion), p_196847_);
});
public static final ChunkStatus BIOMES = register("biomes", STRUCTURE_REFERENCES, 8, PRE_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_196832_, p_196833_, p_196834_, p_196835_, p_196836_, p_196837_, p_196838_, p_196839_, p_196840_, p_196841_) -> {
if (!p_196841_ && p_196840_.getStatus().isOrAfter(p_196832_)) {
return CompletableFuture.completedFuture(Either.left(p_196840_));
} else {
WorldGenRegion worldgenregion = new WorldGenRegion(p_196834_, p_196839_, p_196832_, -1);
return p_196835_.createBiomes(p_196834_.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY), p_196833_, Blender.of(worldgenregion), p_196834_.structureFeatureManager().forWorldGenRegion(worldgenregion), p_196840_).thenApply((p_196819_) -> {
if (p_196819_ instanceof ProtoChunk) {
((ProtoChunk)p_196819_).setStatus(p_196832_);
}
return Either.left(p_196819_);
});
}
});
public static final ChunkStatus NOISE = register("noise", BIOMES, 8, PRE_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_196821_, p_196822_, p_196823_, p_196824_, p_196825_, p_196826_, p_196827_, p_196828_, p_196829_, p_196830_) -> {
if (!p_196830_ && p_196829_.getStatus().isOrAfter(p_196821_)) {
return CompletableFuture.completedFuture(Either.left(p_196829_));
} else {
WorldGenRegion worldgenregion = new WorldGenRegion(p_196823_, p_196828_, p_196821_, 0);
return p_196824_.fillFromNoise(p_196822_, Blender.of(worldgenregion), p_196823_.structureFeatureManager().forWorldGenRegion(worldgenregion), p_196829_).thenApply((p_196792_) -> {
if (p_196792_ instanceof ProtoChunk) {
ProtoChunk protochunk = (ProtoChunk)p_196792_;
BelowZeroRetrogen belowzeroretrogen = protochunk.getBelowZeroRetrogen();
if (belowzeroretrogen != null) {
BelowZeroRetrogen.replaceOldBedrock(protochunk);
if (belowzeroretrogen.hasBedrockHoles()) {
belowzeroretrogen.applyBedrockMask(protochunk);
}
}
protochunk.setStatus(p_196821_);
}
return Either.left(p_196792_);
});
}
});
public static final ChunkStatus SURFACE = registerSimple("surface", NOISE, 8, PRE_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_156247_, p_156248_, p_156249_, p_156250_, p_156251_) -> {
WorldGenRegion worldgenregion = new WorldGenRegion(p_156248_, p_156250_, p_156247_, 0);
p_156249_.buildSurface(worldgenregion, p_156248_.structureFeatureManager().forWorldGenRegion(worldgenregion), p_156251_);
});
public static final ChunkStatus CARVERS = registerSimple("carvers", SURFACE, 8, PRE_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_187819_, p_187820_, p_187821_, p_187822_, p_187823_) -> {
WorldGenRegion worldgenregion = new WorldGenRegion(p_187820_, p_187822_, p_187819_, 0);
if (p_187823_ instanceof ProtoChunk) {
ProtoChunk protochunk = (ProtoChunk)p_187823_;
Blender.addAroundOldChunksCarvingMaskFilter(worldgenregion, protochunk);
}
p_187821_.applyCarvers(worldgenregion, p_187820_.getSeed(), p_187820_.getBiomeManager(), p_187820_.structureFeatureManager().forWorldGenRegion(worldgenregion), p_187823_, GenerationStep.Carving.AIR);
});
public static final ChunkStatus LIQUID_CARVERS = registerSimple("liquid_carvers", CARVERS, 8, POST_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_196805_, p_196806_, p_196807_, p_196808_, p_196809_) -> {
});
public static final ChunkStatus FEATURES = register("features", LIQUID_CARVERS, 8, POST_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_187808_, p_187809_, p_187810_, p_187811_, p_187812_, p_187813_, p_187814_, p_187815_, p_187816_, p_187817_) -> {
ProtoChunk protochunk = (ProtoChunk)p_187816_;
protochunk.setLightEngine(p_187813_);
if (p_187817_ || !p_187816_.getStatus().isOrAfter(p_187808_)) {
Heightmap.primeHeightmaps(p_187816_, EnumSet.of(Heightmap.Types.MOTION_BLOCKING, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Heightmap.Types.OCEAN_FLOOR, Heightmap.Types.WORLD_SURFACE));
WorldGenRegion worldgenregion = new WorldGenRegion(p_187810_, p_187815_, p_187808_, 1);
p_187811_.applyBiomeDecoration(worldgenregion, p_187816_, p_187810_.structureFeatureManager().forWorldGenRegion(worldgenregion));
Blender.generateBorderTicks(worldgenregion, p_187816_);
protochunk.setStatus(p_187808_);
}
return CompletableFuture.completedFuture(Either.left(p_187816_));
});
public static final ChunkStatus LIGHT = register("light", FEATURES, 1, POST_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_196794_, p_196795_, p_196796_, p_196797_, p_196798_, p_196799_, p_196800_, p_196801_, p_196802_, p_196803_) -> {
return lightChunk(p_196794_, p_196799_, p_196802_);
}, (p_196784_, p_196785_, p_196786_, p_196787_, p_196788_, p_196789_) -> {
return lightChunk(p_196784_, p_196787_, p_196789_);
});
public static final ChunkStatus SPAWN = registerSimple("spawn", LIGHT, 0, POST_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_187763_, p_187764_, p_187765_, p_187766_, p_187767_) -> {
if (!p_187767_.isUpgrading()) {
p_187765_.spawnOriginalMobs(new WorldGenRegion(p_187764_, p_187766_, p_187763_, -1));
}
});
public static final ChunkStatus HEIGHTMAPS = registerSimple("heightmaps", SPAWN, 0, POST_FEATURES, ChunkStatus.ChunkType.PROTOCHUNK, (p_196758_, p_196759_, p_196760_, p_196761_, p_196762_) -> {
});
public static final ChunkStatus FULL = register("full", HEIGHTMAPS, 0, POST_FEATURES, ChunkStatus.ChunkType.LEVELCHUNK, (p_196771_, p_196772_, p_196773_, p_196774_, p_196775_, p_196776_, p_196777_, p_196778_, p_196779_, p_196780_) -> {
return p_196777_.apply(p_196779_);
}, (p_196764_, p_196765_, p_196766_, p_196767_, p_196768_, p_196769_) -> {
return p_196768_.apply(p_196769_);
});
private static final List<ChunkStatus> STATUS_BY_RANGE = ImmutableList.of(FULL, FEATURES, LIQUID_CARVERS, BIOMES, STRUCTURE_STARTS, STRUCTURE_STARTS, STRUCTURE_STARTS, STRUCTURE_STARTS, STRUCTURE_STARTS, STRUCTURE_STARTS, STRUCTURE_STARTS, STRUCTURE_STARTS);
private static final IntList RANGE_BY_STATUS = Util.make(new IntArrayList(getStatusList().size()), (p_196782_) -> {
int i = 0;
for(int j = getStatusList().size() - 1; j >= 0; --j) {
while(i + 1 < STATUS_BY_RANGE.size() && j <= STATUS_BY_RANGE.get(i + 1).getIndex()) {
++i;
}
p_196782_.add(0, i);
}
});
private final String name;
private final int index;
private final ChunkStatus parent;
private final ChunkStatus.GenerationTask generationTask;
private final ChunkStatus.LoadingTask loadingTask;
private final int range;
private final ChunkStatus.ChunkType chunkType;
private final EnumSet<Heightmap.Types> heightmapsAfter;
private static CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> lightChunk(ChunkStatus pStatus, ThreadedLevelLightEngine pLightEngine, ChunkAccess pChunk) {
boolean flag = isLighted(pStatus, pChunk);
if (!pChunk.getStatus().isOrAfter(pStatus)) {
((ProtoChunk)pChunk).setStatus(pStatus);
}
return pLightEngine.lightChunk(pChunk, flag).thenApply(Either::left);
}
private static ChunkStatus registerSimple(String pKey, @Nullable ChunkStatus pParent, int pTaskRange, EnumSet<Heightmap.Types> pHeightmaps, ChunkStatus.ChunkType pType, ChunkStatus.SimpleGenerationTask pGenerationTask) {
return register(pKey, pParent, pTaskRange, pHeightmaps, pType, pGenerationTask);
}
private static ChunkStatus register(String pKey, @Nullable ChunkStatus pParent, int pTaskRange, EnumSet<Heightmap.Types> pHeightmaps, ChunkStatus.ChunkType pType, ChunkStatus.GenerationTask pGenerationTask) {
return register(pKey, pParent, pTaskRange, pHeightmaps, pType, pGenerationTask, PASSTHROUGH_LOAD_TASK);
}
private static ChunkStatus register(String pKey, @Nullable ChunkStatus pParent, int pTaskRange, EnumSet<Heightmap.Types> pHeightmaps, ChunkStatus.ChunkType pType, ChunkStatus.GenerationTask pGenerationTask, ChunkStatus.LoadingTask pLoadingTask) {
return Registry.register(Registry.CHUNK_STATUS, pKey, new ChunkStatus(pKey, pParent, pTaskRange, pHeightmaps, pType, pGenerationTask, pLoadingTask));
}
public static List<ChunkStatus> getStatusList() {
List<ChunkStatus> list = Lists.newArrayList();
ChunkStatus chunkstatus;
for(chunkstatus = FULL; chunkstatus.getParent() != chunkstatus; chunkstatus = chunkstatus.getParent()) {
list.add(chunkstatus);
}
list.add(chunkstatus);
Collections.reverse(list);
return list;
}
private static boolean isLighted(ChunkStatus pStatus, ChunkAccess pChunk) {
return pChunk.getStatus().isOrAfter(pStatus) && pChunk.isLightCorrect();
}
public static ChunkStatus getStatusAroundFullChunk(int pRadius) {
if (pRadius >= STATUS_BY_RANGE.size()) {
return EMPTY;
} else {
return pRadius < 0 ? FULL : STATUS_BY_RANGE.get(pRadius);
}
}
public static int maxDistance() {
return STATUS_BY_RANGE.size();
}
public static int getDistance(ChunkStatus pStatus) {
return RANGE_BY_STATUS.getInt(pStatus.getIndex());
}
public ChunkStatus(String pName, @Nullable ChunkStatus pParent, int pRange, EnumSet<Heightmap.Types> pHeightmapsAfter, ChunkStatus.ChunkType pChunkType, ChunkStatus.GenerationTask pGenerationTask, ChunkStatus.LoadingTask pLoadingTask) {
this.name = pName;
this.parent = pParent == null ? this : pParent;
this.generationTask = pGenerationTask;
this.loadingTask = pLoadingTask;
this.range = pRange;
this.chunkType = pChunkType;
this.heightmapsAfter = pHeightmapsAfter;
this.index = pParent == null ? 0 : pParent.getIndex() + 1;
}
public int getIndex() {
return this.index;
}
public String getName() {
return this.name;
}
public ChunkStatus getParent() {
return this.parent;
}
public CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> generate(Executor p_187789_, ServerLevel p_187790_, ChunkGenerator p_187791_, StructureManager p_187792_, ThreadedLevelLightEngine p_187793_, Function<ChunkAccess, CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>> p_187794_, List<ChunkAccess> p_187795_, boolean p_187796_) {
ChunkAccess chunkaccess = p_187795_.get(p_187795_.size() / 2);
ProfiledDuration profiledduration = JvmProfiler.INSTANCE.onChunkGenerate(chunkaccess.getPos(), p_187790_.dimension(), this.name);
CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> completablefuture = this.generationTask.doWork(this, p_187789_, p_187790_, p_187791_, p_187792_, p_187793_, p_187794_, p_187795_, chunkaccess, p_187796_);
return profiledduration != null ? completablefuture.thenApply((p_196756_) -> {
profiledduration.finish();
return p_196756_;
}) : completablefuture;
}
public CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> load(ServerLevel pLevel, StructureManager pStructureManager, ThreadedLevelLightEngine pLightEngine, Function<ChunkAccess, CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>> pTask, ChunkAccess pLoadingChunk) {
return this.loadingTask.doWork(this, pLevel, pStructureManager, pLightEngine, pTask, pLoadingChunk);
}
/**
* Distance in chunks between the edge of the center chunk and the edge of the chunk region needed for the task. The
* task will only affect the center chunk, only reading from the chunks in the margin.
*/
public int getRange() {
return this.range;
}
public ChunkStatus.ChunkType getChunkType() {
return this.chunkType;
}
public static ChunkStatus byName(String pKey) {
return Registry.CHUNK_STATUS.get(ResourceLocation.tryParse(pKey));
}
public EnumSet<Heightmap.Types> heightmapsAfter() {
return this.heightmapsAfter;
}
public boolean isOrAfter(ChunkStatus pStatus) {
return this.getIndex() >= pStatus.getIndex();
}
public String toString() {
return Registry.CHUNK_STATUS.getKey(this).toString();
}
public static enum ChunkType {
PROTOCHUNK,
LEVELCHUNK;
}
interface GenerationTask {
CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> doWork(ChunkStatus p_187871_, Executor p_187872_, ServerLevel p_187873_, ChunkGenerator p_187874_, StructureManager p_187875_, ThreadedLevelLightEngine p_187876_, Function<ChunkAccess, CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>> p_187877_, List<ChunkAccess> p_187878_, ChunkAccess p_187879_, boolean p_187880_);
}
interface LoadingTask {
CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> doWork(ChunkStatus pStatus, ServerLevel pLevel, StructureManager pStructureManager, ThreadedLevelLightEngine pLightEngine, Function<ChunkAccess, CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>> pTask, ChunkAccess pLoadingChunk);
}
/**
* A {@link GenerationTask} which completes all work synchronously.
*/
interface SimpleGenerationTask extends ChunkStatus.GenerationTask {
default CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> doWork(ChunkStatus p_187882_, Executor p_187883_, ServerLevel p_187884_, ChunkGenerator p_187885_, StructureManager p_187886_, ThreadedLevelLightEngine p_187887_, Function<ChunkAccess, CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>> p_187888_, List<ChunkAccess> p_187889_, ChunkAccess p_187890_, boolean p_187891_) {
if (p_187891_ || !p_187890_.getStatus().isOrAfter(p_187882_)) {
this.doWork(p_187882_, p_187884_, p_187885_, p_187889_, p_187890_);
if (p_187890_ instanceof ProtoChunk) {
((ProtoChunk)p_187890_).setStatus(p_187882_);
}
}
return CompletableFuture.completedFuture(Either.left(p_187890_));
}
void doWork(ChunkStatus pStatus, ServerLevel pLevel, ChunkGenerator pGenerator, List<ChunkAccess> pChunks, ChunkAccess pLoadingChunk);
}
}
|
package com.example.testtask;
|
package net.thevpc.nuts.runtime.core.format.text;
import net.thevpc.nuts.runtime.core.format.text.renderer.StyleRenderer;
import java.io.IOException;
import net.thevpc.nuts.NutsSession;
public interface FormattedPrintStreamRenderer {
StyleRenderer createStyleRenderer(AnsiEscapeCommand format, RenderedRawStream out, NutsSession session);
void startFormat(RenderedRawStream out, AnsiEscapeCommand format, NutsSession session) throws IOException;
void endFormat(RenderedRawStream out, AnsiEscapeCommand color, NutsSession session) throws IOException;
}
|
package ufersa.sd.leituraEscritaReentrantLock;
public class Leitor implements Runnable {
private Informacao informacao;
private String nome;
public Leitor(String nome, Informacao informacao) {
this.nome = nome;
this.informacao = informacao;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
String texto = informacao.getInfo();
System.out.println(nome + " => leu "+ texto);
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/*
* (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Kevin Leturc <kleturc@nuxeo.com>
*/
package org.nuxeo.ecm.core.bulk;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.nuxeo.ecm.core.bulk.message.BulkStatus.State.ABORTED;
import static org.nuxeo.ecm.core.bulk.message.BulkStatus.State.COMPLETED;
import static org.nuxeo.ecm.core.bulk.message.BulkStatus.State.RUNNING;
import static org.nuxeo.ecm.core.bulk.message.BulkStatus.State.SCHEDULED;
import static org.nuxeo.ecm.core.bulk.message.BulkStatus.State.UNKNOWN;
import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.apache.commons.collections4.map.PassiveExpiringMap;
import org.apache.logging.log4j.Logger;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.core.api.scroll.ScrollService;
import org.nuxeo.ecm.core.bulk.message.BulkBucket;
import org.nuxeo.ecm.core.bulk.message.BulkCommand;
import org.nuxeo.ecm.core.bulk.message.BulkStatus;
import org.nuxeo.ecm.core.scroll.DocumentScrollRequest;
import org.nuxeo.ecm.core.scroll.GenericScrollRequest;
import org.nuxeo.lib.stream.computation.Record;
import org.nuxeo.lib.stream.log.LogAppender;
import org.nuxeo.lib.stream.log.LogManager;
import org.nuxeo.lib.stream.log.Name;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.kv.KeyValueService;
import org.nuxeo.runtime.kv.KeyValueStore;
import org.nuxeo.runtime.kv.KeyValueStoreProvider;
import org.nuxeo.runtime.stream.StreamService;
/**
* Basic implementation of {@link BulkService}.
*
* @since 10.2
*/
public class BulkServiceImpl implements BulkService {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(BulkServiceImpl.class);
// @deprecated since 11.1 log config is not needed anymore
@Deprecated
public static final String BULK_LOG_MANAGER_NAME = "bulk";
public static final String BULK_KV_STORE_NAME = "bulk";
public static final String COMMAND_STREAM = "bulk/command";
// @since 11.1
public static final Name COMMAND_STREAM_NAME = Name.ofUrn(COMMAND_STREAM);
public static final String STATUS_STREAM = "bulk/status";
// @since 11.1
public static final Name STATUS_STREAM_NAME = Name.ofUrn(STATUS_STREAM);
public static final String DONE_STREAM = "bulk/done";
// @since 11.1
public static final Name DONE_STREAM_NAME = Name.ofUrn(DONE_STREAM);
public static final String COMMAND_PREFIX = "command:";
// @deprecated since 11.4 not needed anymore
@Deprecated(since = "11.4")
public static final String RECORD_CODEC = "avro";
public static final String STATUS_PREFIX = "status:";
public static final String PRODUCE_IMMEDIATE_OPTION = "produceImmediate";
// How long we keep the command and its status in the kv store once completed
public static final long COMPLETED_TTL_SECONDS = 3_600;
// How long we keep the command and its status in the kv store once aborted
public static final long ABORTED_TTL_SECONDS = 7_200;
// @since 11.3
protected final AtomicLong externalScrollerCounter = new AtomicLong();
// @since 11.3
protected final Map<String, BulkCommand> externalCommands = new PassiveExpiringMap<>(60, TimeUnit.SECONDS);
@Override
public String submit(BulkCommand command) {
log.debug("Run action with command={}", command);
// check command
BulkAdminService adminService = Framework.getService(BulkAdminService.class);
if (!adminService.getActions().contains(command.getAction())) {
throw new IllegalArgumentException("Unknown action for command: " + command);
}
BulkActionValidation actionValidation = adminService.getActionValidation(command.getAction());
// Try to validate the action if a validation class is provided
if (actionValidation != null) {
actionValidation.validate(command);
}
RepositoryManager repoManager = Framework.getService(RepositoryManager.class);
if (repoManager != null) {
if (isEmpty(command.getRepository())) {
command.setRepository(repoManager.getDefaultRepositoryName());
} else if (repoManager.getRepository(command.getRepository()) == null) {
throw new IllegalArgumentException("Unknown repository: " + command);
}
}
if (command.getBucketSize() == 0 || command.getBatchSize() == 0) {
if (command.getBucketSize() == 0) {
command.setBucketSize(adminService.getBucketSize(command.getAction()));
}
if (command.getBatchSize() == 0) {
command.setBatchSize(adminService.getBatchSize(command.getAction()));
}
}
if (command.getQueryLimit() == null) {
command.setQueryLimit(adminService.getQueryLimit(command.getAction()));
}
if (command.getScroller() == null && !command.useExternalScroller()) {
String actionScroller = adminService.getDefaultScroller(command.getAction());
if (!isBlank(actionScroller)) {
command.setScroller(actionScroller);
}
}
checkIfScrollerExists(command);
// store the bulk command and status in the key/value store
BulkStatus status = new BulkStatus(command.getId());
status.setState(SCHEDULED);
status.setAction(command.getAction());
status.setUsername(command.getUsername());
status.setSubmitTime(Instant.now());
setStatus(status);
byte[] commandAsBytes = setCommand(command);
String shardKey;
if (adminService.isSequentialCommands(command.getAction())) {
// no concurrency all commands for this action goes to the same partition
shardKey = command.getAction();
} else {
// use a random value
shardKey = command.getId();
}
// send command to bulk processor
log.debug("Submit action with command: {}", command);
return submit(shardKey, command.getId(), commandAsBytes);
}
protected void checkIfScrollerExists(BulkCommand command) {
ScrollService scrollService = Framework.getService(ScrollService.class);
if (command.useExternalScroller()) {
// nothing to do
} else if (command.useGenericScroller()) {
if (!scrollService.exists(
GenericScrollRequest.builder(command.getScroller(), command.getQuery()).build())) {
throw new IllegalArgumentException("Unknown Generic Scroller for command: " + command);
}
} else if (!scrollService.exists(
DocumentScrollRequest.builder(command.getQuery()).name(command.getScroller()).build())) {
throw new IllegalArgumentException("Unknown Document Scroller for command: " + command);
}
}
@SuppressWarnings("resource") // LogManager not ours to close
protected String submit(String shardKey, String key, byte[] bytes) {
LogManager logManager = Framework.getService(StreamService.class).getLogManager();
LogAppender<Record> logAppender = logManager.getAppender(COMMAND_STREAM_NAME);
Record record = Record.of(key, bytes);
log.debug("Append shardKey: {}, record: {}", shardKey, record);
logAppender.append(shardKey, record);
return key;
}
@Override
public BulkStatus getStatus(String commandId) {
KeyValueStore keyValueStore = getKvStore();
byte[] statusAsBytes = keyValueStore.get(STATUS_PREFIX + commandId);
if (statusAsBytes == null) {
log.debug("Request status of unknown command: {}", commandId);
return BulkStatus.unknownOf(commandId);
}
return BulkCodecs.getStatusCodec().decode(statusAsBytes);
}
/**
* Stores the status in the kv store returns the encoded status
*/
public byte[] setStatus(BulkStatus status) {
KeyValueStore kvStore = getKvStore();
byte[] statusAsBytes = BulkCodecs.getStatusCodec().encode(status);
switch (status.getState()) {
case ABORTED:
kvStore.put(STATUS_PREFIX + status.getId(), statusAsBytes, ABORTED_TTL_SECONDS);
// we remove the command from the kv store, so computation have to handle abort
kvStore.put(COMMAND_PREFIX + status.getId(), (String) null);
break;
case COMPLETED:
kvStore.put(STATUS_PREFIX + status.getId(), statusAsBytes, COMPLETED_TTL_SECONDS);
kvStore.setTTL(COMMAND_PREFIX + status.getId(), COMPLETED_TTL_SECONDS);
break;
default:
kvStore.put(STATUS_PREFIX + status.getId(), statusAsBytes);
}
return statusAsBytes;
}
@Override
public BulkCommand getCommand(String commandId) {
KeyValueStore keyValueStore = getKvStore();
byte[] statusAsBytes = keyValueStore.get(COMMAND_PREFIX + commandId);
if (statusAsBytes == null) {
return null;
}
return BulkCodecs.getCommandCodec().decode(statusAsBytes);
}
@Override
public BulkStatus abort(String commandId) {
BulkStatus status = getStatus(commandId);
if (COMPLETED.equals(status.getState())) {
log.debug("Cannot abort a completed command: {}", commandId);
return status;
}
status.setState(ABORTED);
// set the status in the KV store
setStatus(status);
// Send a delta to the status computation
BulkStatus delta = BulkStatus.deltaOf(commandId);
delta.setCompletedTime(Instant.now());
delta.setState(ABORTED);
Record record = Record.of(commandId, BulkCodecs.getStatusCodec().encode(delta));
Framework.getService(StreamService.class).getStreamManager().append(STATUS_STREAM, record);
return status;
}
@Override
public Map<String, Serializable> getResult(String commandId) {
return getStatus(commandId).getResult();
}
/**
* Stores the command in the kv store, returns the encoded command.
*/
public byte[] setCommand(BulkCommand command) {
KeyValueStore kvStore = getKvStore();
byte[] commandAsBytes = BulkCodecs.getCommandCodec().encode(command);
kvStore.put(COMMAND_PREFIX + command.getId(), commandAsBytes);
return commandAsBytes;
}
@Override
public boolean await(String commandId, Duration duration) throws InterruptedException {
long deadline = System.currentTimeMillis() + duration.toMillis();
BulkStatus status;
do {
status = getStatus(commandId);
switch (status.getState()) {
case COMPLETED:
case ABORTED:
return true;
case UNKNOWN:
log.error("Unknown status for command: {}", commandId);
return false;
default:
// continue
}
Thread.sleep(100);
} while (deadline > System.currentTimeMillis());
log.debug("await timeout on {} after {} ms", () -> getStatus(commandId), duration::toMillis);
return false;
}
public KeyValueStore getKvStore() {
return Framework.getService(KeyValueService.class).getKeyValueStore(BULK_KV_STORE_NAME);
}
@Override
public boolean await(Duration duration) throws InterruptedException {
KeyValueStoreProvider kv = (KeyValueStoreProvider) getKvStore();
Set<String> commandIds = kv.keyStream(STATUS_PREFIX)
.map(k -> k.replaceFirst(STATUS_PREFIX, ""))
.collect(Collectors.toSet());
log.debug("Wait for command ids: {}", commandIds);
// nanoTime is always monotonous
long deadline = System.nanoTime() + duration.toNanos();
for (String commandId : commandIds) {
log.debug("Wait for command id: {}", commandId);
for (;;) {
BulkStatus status = getStatus(commandId);
log.debug("Status of command: {} = {}", commandId, status);
BulkStatus.State state = status.getState();
log.debug("State of command: {} = {}", commandId, state);
if (state == COMPLETED || state == ABORTED || state == UNKNOWN) {
break;
}
Thread.sleep(200);
if (deadline < System.nanoTime()) {
log.debug("await timeout, at least one uncompleted command: {}", status);
return false;
}
}
}
return true;
}
@Override
public List<BulkStatus> getStatuses(String username) {
KeyValueStoreProvider kv = (KeyValueStoreProvider) getKvStore();
return kv.keyStream(STATUS_PREFIX)
.map(kv::get)
.map(BulkCodecs.getStatusCodec()::decode)
.filter(status -> username.equals(status.getUsername()))
.collect(Collectors.toList());
}
@Override
public void appendExternalBucket(BulkBucket bucket) {
String commandId = bucket.getCommandId();
BulkCommand command = externalCommands.computeIfAbsent(commandId, this::getCommand);
String stream = Framework.getService(BulkAdminService.class).getInputStream(command.getAction());
String key = commandId + ":" + externalScrollerCounter.incrementAndGet();
Record record = Record.of(key, BulkCodecs.getBucketCodec().encode(bucket));
log.debug("Append key: {}, record: {}", key, record);
Framework.getService(StreamService.class).getStreamManager().append(stream, record);
}
@Override
public void completeExternalScroll(String commandId, long count) {
BulkStatus delta = BulkStatus.deltaOf(commandId);
delta.setState(RUNNING);
delta.setScrollEndTime(Instant.now());
delta.setTotal(count);
Record record = Record.of(commandId, BulkCodecs.getStatusCodec().encode(delta));
log.debug("Complete external scroll with key: {}, count: {}, record: {}", commandId, count, record);
Framework.getService(StreamService.class).getStreamManager().append(STATUS_STREAM, record);
}
}
|
package me.carda.awesome_notifications.notifications.models;
import android.content.Context;
import java.util.HashMap;
import java.util.Map;
import androidx.annotation.Nullable;
import me.carda.awesome_notifications.Definitions;
import me.carda.awesome_notifications.notifications.enumerators.DefaultRingtoneType;
import me.carda.awesome_notifications.notifications.enumerators.GroupSort;
import me.carda.awesome_notifications.notifications.enumerators.MediaSource;
import me.carda.awesome_notifications.notifications.enumerators.GroupAlertBehaviour;
import me.carda.awesome_notifications.notifications.enumerators.NotificationImportance;
import me.carda.awesome_notifications.notifications.enumerators.NotificationPrivacy;
import me.carda.awesome_notifications.notifications.exceptions.AwesomeNotificationException;
import me.carda.awesome_notifications.utils.AudioUtils;
import me.carda.awesome_notifications.utils.BitmapUtils;
import me.carda.awesome_notifications.utils.BooleanUtils;
import me.carda.awesome_notifications.utils.CompareUtils;
import me.carda.awesome_notifications.utils.MediaUtils;
import me.carda.awesome_notifications.utils.StringUtils;
public class NotificationChannelModel extends AbstractModel {
public String channelKey;
public String channelName;
public String channelDescription;
public Boolean channelShowBadge;
public String channelGroupKey;
public NotificationImportance importance;
public Boolean playSound;
public String soundSource;
public DefaultRingtoneType defaultRingtoneType;
public Boolean enableVibration;
public long[] vibrationPattern;
public Boolean enableLights;
public Integer ledColor;
public Integer ledOnMs;
public Integer ledOffMs;
public String groupKey;
public GroupSort groupSort;
public GroupAlertBehaviour groupAlertBehavior;
// Note: this is set on the Android to save details about the icon that should be used when re-hydrating delayed notifications when a device has been restarted.
public Integer iconResourceId;
public String icon;
public Long defaultColor;
public Boolean locked;
public Boolean onlyAlertOnce;
public Boolean criticalAlerts;
public NotificationPrivacy defaultPrivacy;
public NotificationChannelModel(){}
public void refreshIconResource(Context context){
if(iconResourceId == null && icon != null){
if(MediaUtils.getMediaSourceType(icon) == MediaSource.Resource) {
int resourceIndex = BitmapUtils.getDrawableResourceId(context, icon);
if (resourceIndex > 0) {
iconResourceId = resourceIndex;
} else {
iconResourceId = null;
}
}
}
}
public boolean isChannelEnabled(){
return importance != null && importance != NotificationImportance.None;
}
public String getChannelHashKey(Context context, boolean fullHashObject){
refreshIconResource(context);
if(fullHashObject){
String jsonData = this.toJson();
return StringUtils.digestString(jsonData);
}
NotificationChannelModel channelCopied = this.clone();
channelCopied.channelName = "";
channelCopied.channelDescription = "";
channelCopied.groupKey = null;
String jsonData = channelCopied.toJson();
return channelKey + "_" + StringUtils.digestString(jsonData);
}
@Override
public boolean equals(@Nullable Object obj) {
if(super.equals(obj)) return true;
if(!(obj instanceof NotificationChannelModel)) return false;
NotificationChannelModel other = (NotificationChannelModel) obj;
return
CompareUtils.assertEqualObjects(other.iconResourceId, this.iconResourceId) &&
CompareUtils.assertEqualObjects(other.defaultColor, this.defaultColor) &&
CompareUtils.assertEqualObjects(other.channelKey, this.channelKey) &&
CompareUtils.assertEqualObjects(other.channelName, this.channelName) &&
CompareUtils.assertEqualObjects(other.channelDescription, this.channelDescription) &&
CompareUtils.assertEqualObjects(other.channelShowBadge, this.channelShowBadge) &&
CompareUtils.assertEqualObjects(other.importance, this.importance) &&
CompareUtils.assertEqualObjects(other.playSound, this.playSound) &&
CompareUtils.assertEqualObjects(other.soundSource, this.soundSource) &&
CompareUtils.assertEqualObjects(other.enableVibration, this.enableVibration) &&
CompareUtils.assertEqualObjects(other.vibrationPattern, this.vibrationPattern) &&
CompareUtils.assertEqualObjects(other.enableLights, this.enableLights) &&
CompareUtils.assertEqualObjects(other.ledColor, this.ledColor) &&
CompareUtils.assertEqualObjects(other.ledOnMs, this.ledOnMs) &&
CompareUtils.assertEqualObjects(other.ledOffMs, this.ledOffMs) &&
CompareUtils.assertEqualObjects(other.groupKey, this.groupKey) &&
CompareUtils.assertEqualObjects(other.locked, this.locked) &&
CompareUtils.assertEqualObjects(other.criticalAlerts, this.criticalAlerts) &&
CompareUtils.assertEqualObjects(other.onlyAlertOnce, this.onlyAlertOnce) &&
CompareUtils.assertEqualObjects(other.defaultPrivacy, this.defaultPrivacy) &&
CompareUtils.assertEqualObjects(other.defaultRingtoneType, this.defaultRingtoneType) &&
CompareUtils.assertEqualObjects(other.groupSort, this.groupSort) &&
CompareUtils.assertEqualObjects(other.groupAlertBehavior, this.groupAlertBehavior);
}
@Override
public NotificationChannelModel fromMap(Map<String, Object> arguments) {
iconResourceId = getValueOrDefault(arguments, Definitions.NOTIFICATION_ICON_RESOURCE_ID, Integer.class);
icon = getValueOrDefault(arguments, Definitions.NOTIFICATION_ICON, String.class);
if(icon != null){
if(MediaUtils.getMediaSourceType(icon) != MediaSource.Resource){
icon = null;
}
}
defaultColor = getValueOrDefault(arguments, Definitions.NOTIFICATION_DEFAULT_COLOR, Long.class);
channelKey = getValueOrDefault(arguments, Definitions.NOTIFICATION_CHANNEL_KEY, String.class);
channelName = getValueOrDefault(arguments, Definitions.NOTIFICATION_CHANNEL_NAME, String.class);
channelDescription = getValueOrDefault(arguments, Definitions.NOTIFICATION_CHANNEL_DESCRIPTION, String.class);
channelShowBadge = getValueOrDefault(arguments, Definitions.NOTIFICATION_CHANNEL_SHOW_BADGE, Boolean.class);
channelGroupKey = getValueOrDefault(arguments, Definitions.NOTIFICATION_CHANNEL_GROUP_KEY, String.class);
playSound = getValueOrDefault(arguments, Definitions.NOTIFICATION_PLAY_SOUND, Boolean.class);
soundSource = getValueOrDefault(arguments, Definitions.NOTIFICATION_SOUND_SOURCE, String.class);
criticalAlerts = getValueOrDefault(arguments, Definitions.NOTIFICATION_CHANNEL_CRITICAL_ALERTS, Boolean.class);
enableVibration = getValueOrDefault(arguments, Definitions.NOTIFICATION_ENABLE_VIBRATION, Boolean.class);
vibrationPattern = getValueOrDefault(arguments, Definitions.NOTIFICATION_VIBRATION_PATTERN, long[].class);
ledColor = getValueOrDefault(arguments, Definitions.NOTIFICATION_LED_COLOR, Integer.class);
enableLights = getValueOrDefault(arguments, Definitions.NOTIFICATION_ENABLE_LIGHTS, Boolean.class);
ledOnMs = getValueOrDefault(arguments, Definitions.NOTIFICATION_LED_ON_MS, Integer.class);
ledOffMs = getValueOrDefault(arguments, Definitions.NOTIFICATION_LED_OFF_MS, Integer.class);
importance =
getEnumValueOrDefault(arguments, Definitions.NOTIFICATION_IMPORTANCE, NotificationImportance.class, NotificationImportance.values());
groupSort =
getEnumValueOrDefault(arguments, Definitions.NOTIFICATION_GROUP_SORT, GroupSort.class, GroupSort.values());
groupAlertBehavior =
getEnumValueOrDefault(arguments, Definitions.NOTIFICATION_GROUP_ALERT_BEHAVIOR, GroupAlertBehaviour.class, GroupAlertBehaviour.values());
defaultPrivacy =
getEnumValueOrDefault(arguments, Definitions.NOTIFICATION_DEFAULT_PRIVACY, NotificationPrivacy.class, NotificationPrivacy.values());
defaultRingtoneType =
getEnumValueOrDefault(arguments, Definitions.NOTIFICATION_DEFAULT_RINGTONE_TYPE, DefaultRingtoneType.class, DefaultRingtoneType.values());
groupKey = getValueOrDefault(arguments, Definitions.NOTIFICATION_GROUP_KEY, String.class);
locked = getValueOrDefault(arguments, Definitions.NOTIFICATION_LOCKED, Boolean.class);
onlyAlertOnce = getValueOrDefault(arguments, Definitions.NOTIFICATION_ONLY_ALERT_ONCE, Boolean.class);
return this;
}
public Map<String, Object> toMap(){
Map<String, Object> returnedObject = new HashMap<>();
returnedObject.put(Definitions.NOTIFICATION_ICON_RESOURCE_ID, this.iconResourceId);
returnedObject.put(Definitions.NOTIFICATION_ICON, this.icon);
returnedObject.put(Definitions.NOTIFICATION_DEFAULT_COLOR, this.defaultColor);
returnedObject.put(Definitions.NOTIFICATION_CHANNEL_KEY, this.channelKey);
returnedObject.put(Definitions.NOTIFICATION_CHANNEL_NAME, this.channelName);
returnedObject.put(Definitions.NOTIFICATION_CHANNEL_DESCRIPTION, this.channelDescription);
if(this.channelShowBadge != null)
returnedObject.put(Definitions.NOTIFICATION_CHANNEL_SHOW_BADGE, this.channelShowBadge);
if(this.channelGroupKey != null)
returnedObject.put(Definitions.NOTIFICATION_CHANNEL_GROUP_KEY, this.channelGroupKey);
if(this.playSound != null)
returnedObject.put(Definitions.NOTIFICATION_PLAY_SOUND, this.playSound);
if(this.soundSource != null)
returnedObject.put(Definitions.NOTIFICATION_SOUND_SOURCE, this.soundSource);
if(this.enableVibration != null)
returnedObject.put(Definitions.NOTIFICATION_ENABLE_VIBRATION, this.enableVibration);
if(this.vibrationPattern != null)
returnedObject.put(Definitions.NOTIFICATION_VIBRATION_PATTERN, this.vibrationPattern);
if(this.enableLights != null)
returnedObject.put(Definitions.NOTIFICATION_ENABLE_LIGHTS, this.enableLights);
if(this.ledColor != null)
returnedObject.put(Definitions.NOTIFICATION_LED_COLOR, this.ledColor);
if(this.ledOnMs != null)
returnedObject.put(Definitions.NOTIFICATION_LED_ON_MS, this.ledOnMs);
if(this.ledOffMs != null)
returnedObject.put(Definitions.NOTIFICATION_LED_OFF_MS, this.ledOffMs);
if(this.groupKey != null)
returnedObject.put(Definitions.NOTIFICATION_GROUP_KEY, this.groupKey);
if(this.groupSort != null)
returnedObject.put(Definitions.NOTIFICATION_GROUP_SORT, this.groupSort.toString());
if(this.importance != null)
returnedObject.put(Definitions.NOTIFICATION_IMPORTANCE, this.importance.toString());
if(this.groupAlertBehavior != null)
returnedObject.put(Definitions.NOTIFICATION_GROUP_ALERT_BEHAVIOR, this.groupAlertBehavior.toString());
if(this.defaultPrivacy != null)
returnedObject.put(Definitions.NOTIFICATION_DEFAULT_PRIVACY, this.defaultPrivacy.toString());
if(this.defaultRingtoneType != null)
returnedObject.put(Definitions.NOTIFICATION_DEFAULT_RINGTONE_TYPE, this.defaultRingtoneType.toString());
if(this.locked != null)
returnedObject.put(Definitions.NOTIFICATION_LOCKED, this.locked);
if(this.onlyAlertOnce != null)
returnedObject.put(Definitions.NOTIFICATION_ONLY_ALERT_ONCE, this.onlyAlertOnce);
if(this.criticalAlerts != null && this.criticalAlerts)
returnedObject.put(Definitions.NOTIFICATION_CHANNEL_CRITICAL_ALERTS, this.criticalAlerts);
return returnedObject;
}
@Override
public String toJson() {
return templateToJson();
}
@Override
public NotificationChannelModel fromJson(String json){
return (NotificationChannelModel) super.templateFromJson(json);
}
@Override
public void validate(Context context) throws AwesomeNotificationException {
if(StringUtils.isNullOrEmpty(channelKey))
throw new AwesomeNotificationException("Channel key cannot be null or empty");
if(StringUtils.isNullOrEmpty(channelName))
throw new AwesomeNotificationException("Channel name cannot be null or empty");
if(StringUtils.isNullOrEmpty(channelDescription))
throw new AwesomeNotificationException("Channel description cannot be null or empty");
if(playSound == null)
throw new AwesomeNotificationException("Play sound selector cannot be null or empty");
if (ledColor != null && (ledOnMs == null || ledOffMs == null)) {
throw new AwesomeNotificationException("Standard led on and off times cannot be null or empty");
}
if(BooleanUtils.getValue(playSound) && !StringUtils.isNullOrEmpty(soundSource))
if(!AudioUtils.isValidAudio(context, soundSource))
throw new AwesomeNotificationException("Audio media is not valid");
}
public NotificationChannelModel clone() {
NotificationChannelModel cloned = new NotificationChannelModel();
cloned.iconResourceId = this.iconResourceId;
cloned.defaultColor = this.defaultColor;
cloned.channelKey = this.channelKey;
cloned.channelName = this.channelName;
cloned.channelDescription = this.channelDescription;
cloned.channelShowBadge = this.channelShowBadge;
cloned.importance = this.importance;
cloned.playSound = this.playSound;
cloned.soundSource = this.soundSource;
cloned.enableVibration = this.enableVibration;
cloned.vibrationPattern = this.vibrationPattern;
cloned.enableLights = this.enableLights;
cloned.ledColor = this.ledColor;
cloned.ledOnMs = this.ledOnMs;
cloned.ledOffMs = this.ledOffMs;
cloned.groupKey = this.groupKey;
cloned.locked = this.locked;
cloned.onlyAlertOnce = this.onlyAlertOnce;
cloned.defaultPrivacy = this.defaultPrivacy;
cloned.defaultRingtoneType = this.defaultRingtoneType;
cloned.groupSort = this.groupSort;
cloned.groupAlertBehavior = this.groupAlertBehavior;
cloned.criticalAlerts = this.criticalAlerts;
return cloned;
}
}
|
package nz.sodium;
/**
* A handle for a listener that was registered with {@link Cell#listen(Handler)} or {@link Stream#listen(Handler)}.
*/
public class Listener {
public Listener() {}
/**
* Deregister the listener that was registered so it will no longer be called back,
* allowing associated resources to be garbage collected.
*/
public void unlisten() {}
/**
* Combine listeners into one so that invoking {@link #unlisten()} on the returned
* listener will unlisten both the inputs.
*/
public final Listener append(final Listener two) {
final Listener one = this;
return new Listener() {
public void unlisten() {
one.unlisten();
two.unlisten();
}
};
}
}
|
package de.consol.cloudnative;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloApplicationTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void hi_callHiEndpoint_shouldReturnHi() {
final String appliationUrl = "http://localhost:" + port;
final ResponseEntity<String> response = restTemplate.getForEntity(appliationUrl + "/", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
assertThat(response.getBody(), containsString("Hi"));
}
}
|
package ie.gmit.sw.request;
/**
* An enum that defines the various types of requests.
*/
public enum RequestType {
Lookup,
Add,
Remove
}
|
package ru.job4j.tracker;
import java.sql.Timestamp;
/**.
* Класс заявки
*/
public class Item {
/**.
* Уникальный идентификатор заявки
*/
private String id;
/**.
* Название заявки
*/
private String name;
/**.
* Описание заявки
*/
private String desc;
/**.
* Дата создания заявки
*/
private long created;
/**.
* Массив с коменатриями к заявке
*/
private String[] comments;
/**.
* Констурктор заявки
* @param id - айди
* @param name - имя
* @param desc - описание
*/
public Item(String id, String name, String desc) {
this.id = id;
this.name = name;
this.desc = desc;
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
this.created = timestamp.getTime();
}
/**.
********** ГЕТТЕРЫ ***********
*/
/**.
* ID зявки
* @return - строка ID
*/
public String getItemId() {
return id;
}
/**.
* Имя зявки
* @return - строка имени
*/
public String getItemName() {
return name;
}
/**.
* Описание заявки
* @return - строка описания
*/
public String getItemDesc() {
return desc;
}
/**.
********** СЕТТЕРЫ ***********
*/
/**.
* ID зявки
* @param id - id заявки
*/
public void setItemId(String id) {
this.id = id;
}
/**.
* Имя зявки
* @param name - имя заявки
*/
public void setItemName(String name) {
this.name = name;
}
/**.
* Описание заявки
* @param desc - строка описания
*/
public void setItemDesc(String desc) {
this.desc = desc;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.api.ldap.codec.actions.request.search.filter;
import org.apache.directory.api.asn1.DecoderException;
import org.apache.directory.api.asn1.ber.grammar.GrammarAction;
import org.apache.directory.api.i18n.I18n;
import org.apache.directory.api.ldap.codec.api.LdapMessageContainer;
import org.apache.directory.api.ldap.codec.search.ExtensibleMatchFilter;
import org.apache.directory.api.ldap.codec.search.Filter;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The action used to initialize the Extensible Match filter
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class InitExtensibleMatchFilter extends GrammarAction<LdapMessageContainer<SearchRequest>>
{
/** The logger */
private static final Logger LOG = LoggerFactory.getLogger( InitExtensibleMatchFilter.class );
/**
* Instantiates a new init extensible match filter action.
*/
public InitExtensibleMatchFilter()
{
super( "Init Extensible Match filter Value" );
}
/**
* {@inheritDoc}
*/
public void action( LdapMessageContainer<SearchRequest> container ) throws DecoderException
{
// We can allocate the ExtensibleMatch Filter
Filter extensibleMatchFilter = new ExtensibleMatchFilter( container.getCurrentTLV().getId() );
container.addCurrentFilter( extensibleMatchFilter );
container.setTerminalFilter( extensibleMatchFilter );
if ( LOG.isDebugEnabled() )
{
LOG.debug( I18n.msg( I18n.MSG_05146_INITIALIZE_EXT_FILTER ) );
}
}
}
|
package org.asciidoc.intellij.inspections;
public class AsciiDocDescriptionExistsInspectionTest extends AsciiDocQuickFixTestBase {
@Override
public void setUp() throws Exception {
super.setUp();
//noinspection unchecked
myFixture.enableInspections(AsciiDocDescriptionExistsInspection.class);
}
public void testAddMissingDescriptionJustTitle() {
myFixture.testHighlighting("modules/ROOT/pages/justTitle.adoc", "antora.yml");
applySingleQuickFix("Add page attribute description");
myFixture.checkResultByFile("modules/ROOT/pages/justTitle-after.adoc", true);
}
public void testAddMissingDescriptionTitleWithExistingAttributes() {
myFixture.testHighlighting("modules/ROOT/pages/titleWithAttributes.adoc", "antora.yml");
applySingleQuickFix("Add page attribute description");
myFixture.checkResultByFile("modules/ROOT/pages/titleWithAttributes-after.adoc", true);
}
public void testAddMissingDescriptionTitleWithWithText() {
myFixture.testHighlighting("modules/ROOT/pages/titleWithText.adoc", "antora.yml");
applySingleQuickFix("Add page attribute description");
myFixture.checkResultByFile("modules/ROOT/pages/titleWithText-after.adoc", true);
}
public void testDescriptionExists() {
// show that existing description is recognized
myFixture.testHighlighting("modules/ROOT/pages/descriptionExists.adoc", "antora.yml");
}
@Override
protected String getBasePath() {
return "inspections/descriptionExists";
}
}
|
package com.cts.springdatamvc.controller;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DefaultController{
@GetMapping({"","/","/home"})
public ModelAndView getHomePage() {
return new ModelAndView("dashboard");
}
@ModelAttribute
public void populateCommonData(Model model){
Map<String,String> navLinks = new LinkedHashMap<>();
navLinks.put("home", "Home");
navLinks.put("emps", "Employees");
navLinks.put("newEmp","New Employee");
navLinks.put("searchEmp", "Search Employee");
model.addAttribute("links", navLinks);
model.addAttribute("appTitle", "Employee Record Manager");
}
@RequestMapping("/header")
public ModelAndView headerSectionRequestHandler(){
ModelAndView mv = new ModelAndView("headerSection");
return mv;
}
@RequestMapping("/footer")
public ModelAndView footerSectionRequestHandler(){
return new ModelAndView("footerSection");
}
}
|
/*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.foundation;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import apple.NSObject;
@Generated
@Library("Foundation")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class NSException extends NSObject {
static {
NatJ.register();
}
@Generated
protected NSException(Pointer peer) {
super(peer);
}
@Generated
@Selector("init")
public native NSException init();
@Generated
@Selector("name")
public native String name();
}
|
package com.example.base_station_game;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseAuthWeakPasswordException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import studio.carbonylgroup.textfieldboxes.ExtendedEditText;
public class RegisterActivity extends AppCompatActivity {
private DatabaseReference mDatabase;
public User user;
private ExtendedEditText username_field;
private ExtendedEditText email_field;
private ExtendedEditText team_field;
private ExtendedEditText password_field;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().hide();
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void register(View v) {
email_field = findViewById(R.id.email_text);
String email=email_field.getText().toString();
team_field = findViewById(R.id.team_text);
String team=team_field.getText().toString();
username_field = findViewById(R.id.username_text);
String username=username_field.getText().toString();
password_field = findViewById(R.id.password_text);
String password=password_field.getText().toString();
if ( password.equals("") || email.equals("") || team.equals("") || username.equals(""))
{
Toast.makeText(RegisterActivity.this, R.string.all_fields,
Toast.LENGTH_SHORT).show();
}
else {
if(team.length()<2 || team.length()>12){
team_field.setError(getString(R.string.team_restriction));
}
else {
if(username.length()<2 || username.length()>10) {
username_field.setError(getString(R.string.pw_restriction));
}
else{
mDatabase = FirebaseDatabase.getInstance().getReference();
// If you use . - or other symbols this fail
DatabaseReference ref = mDatabase.child("usernames").child(username); //check at reference of user if it already exists
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
username_field.setError(getString(R.string.username_gone));
username_field.requestFocus();
} else {
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, task -> {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, username + " registered!",
Toast.LENGTH_SHORT).show();
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
user = new User(firebaseUser.getUid(), firebaseUser.getEmail(), username, team);
mDatabase.child("Users").child(user.getUID()).child("username").setValue(user.getUsername());
mDatabase.child("Users").child(user.getUID()).child("email").setValue(user.getEmail());
mDatabase.child("Users").child(user.getUID()).child("uid").setValue(user.getUID());
mDatabase.child("Users").child(user.getUID()).child("team").setValue(user.getTeam());
mDatabase.child("Users").child(user.getUID()).child("token").setValue(token);
mDatabase.child("usernames").child(username).setValue(user.getUID());
mDatabase.child("Teams").child(team).child(firebaseUser.getUid()).setValue(username);
startMap();
} else {
Log.d("token error", "token couldnt get generated");
}
}
});
} else {
try {
throw task.getException();
} catch (FirebaseAuthWeakPasswordException e) {
password_field.setError(getString(R.string.char_min));
password_field.requestFocus();
} catch (FirebaseAuthInvalidCredentialsException e) {
} catch (FirebaseAuthUserCollisionException e) {
email_field.setError(getString(R.string.acc_exists));
email_field.requestFocus();
// mTxtEmail.requestFocus();
} catch (Exception e) {
Log.e("Uncaught Error", e.getMessage());
}
Toast.makeText(RegisterActivity.this, R.string.reg_fail,
Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}
public void startMap(){
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
}
|
/*
* 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.dolphinscheduler.plugin.task.flink;
import static org.apache.dolphinscheduler.plugin.task.api.TaskConstants.RWXR_XR_X;
import org.apache.dolphinscheduler.plugin.task.api.AbstractYarnTask;
import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext;
import org.apache.dolphinscheduler.plugin.task.api.model.Property;
import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo;
import org.apache.dolphinscheduler.plugin.task.api.parameters.AbstractParameters;
import org.apache.dolphinscheduler.plugin.task.api.parser.ParamUtils;
import org.apache.dolphinscheduler.plugin.task.api.parser.ParameterUtils;
import org.apache.dolphinscheduler.plugin.task.api.utils.ArgsUtils;
import org.apache.dolphinscheduler.plugin.task.api.utils.MapUtils;
import org.apache.dolphinscheduler.plugin.task.api.utils.OSUtils;
import org.apache.dolphinscheduler.spi.utils.JSONUtils;
import org.apache.dolphinscheduler.spi.utils.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class FlinkTask extends AbstractYarnTask {
/**
* flink parameters
*/
private FlinkParameters flinkParameters;
/**
* taskExecutionContext
*/
private TaskExecutionContext taskExecutionContext;
public FlinkTask(TaskExecutionContext taskExecutionContext) {
super(taskExecutionContext);
this.taskExecutionContext = taskExecutionContext;
}
@Override
public void init() {
logger.info("flink task params {}", taskExecutionContext.getTaskParams());
flinkParameters = JSONUtils.parseObject(taskExecutionContext.getTaskParams(), FlinkParameters.class);
if (flinkParameters == null || !flinkParameters.checkParameters()) {
throw new RuntimeException("flink task params is not valid");
}
flinkParameters.setQueue(taskExecutionContext.getQueue());
if (ProgramType.SQL != flinkParameters.getProgramType()) {
setMainJarName();
}
}
/**
* create command
*
* @return command
*/
@Override
protected String buildCommand() {
List<String> args = new ArrayList<>();
if (ProgramType.SQL != flinkParameters.getProgramType()) {
// execute flink run [OPTIONS] <jar-file> <arguments>
args.add(FlinkConstants.FLINK_COMMAND);
args.add(FlinkConstants.FLINK_RUN);
args.addAll(populateFlinkOptions());
} else {
// execute sql-client.sh -f <script file>
args.add(FlinkConstants.FLINK_SQL_COMMAND);
args.addAll(populateFlinkSqlOptions());
}
String command = ParameterUtils.convertParameterPlaceholders(String.join(" ", args), taskExecutionContext.getDefinedParams());
logger.info("flink task command : {}", command);
return command;
}
/**
* build flink options
*
* @return argument list
*/
private List<String> populateFlinkOptions() {
List<String> args = new ArrayList<>();
String deployMode = StringUtils.isNotEmpty(flinkParameters.getDeployMode()) ? flinkParameters.getDeployMode() : FlinkConstants.DEPLOY_MODE_CLUSTER;
if (!FlinkConstants.DEPLOY_MODE_LOCAL.equals(deployMode)) {
populateFlinkOnYarnOptions(args);
}
// -p
int parallelism = flinkParameters.getParallelism();
if (parallelism > 0) {
args.add(FlinkConstants.FLINK_PARALLELISM);
args.add(String.format("%d", parallelism));
}
/**
* -sae
*
* If the job is submitted in attached mode, perform a best-effort cluster shutdown when the CLI is terminated abruptly.
* The task status will be synchronized with the cluster job status.
*/
args.add(FlinkConstants.FLINK_SHUTDOWN_ON_ATTACHED_EXIT);
// -s -yqu -yat -yD -D
String others = flinkParameters.getOthers();
if (StringUtils.isNotEmpty(others)) {
args.add(others);
}
// -c
ProgramType programType = flinkParameters.getProgramType();
String mainClass = flinkParameters.getMainClass();
if (programType != ProgramType.PYTHON && StringUtils.isNotEmpty(mainClass)) {
args.add(FlinkConstants.FLINK_MAIN_CLASS);
args.add(flinkParameters.getMainClass());
}
ResourceInfo mainJar = flinkParameters.getMainJar();
if (mainJar != null) {
// -py
if(ProgramType.PYTHON == programType) {
args.add(FlinkConstants.FLINK_PYTHON);
}
args.add(mainJar.getRes());
}
String mainArgs = flinkParameters.getMainArgs();
if (StringUtils.isNotEmpty(mainArgs)) {
// combining local and global parameters
Map<String, Property> paramsMap = ParamUtils.convert(taskExecutionContext, getParameters());
if (MapUtils.isEmpty(paramsMap)) {
paramsMap = new HashMap<>();
}
if (MapUtils.isNotEmpty(taskExecutionContext.getParamsMap())) {
paramsMap.putAll(taskExecutionContext.getParamsMap());
}
args.add(ParameterUtils.convertParameterPlaceholders(mainArgs, ParamUtils.convert(paramsMap)));
}
return args;
}
private void populateFlinkOnYarnOptions(List<String> args) {
// -m yarn-cluster
args.add(FlinkConstants.FLINK_RUN_MODE);
args.add(FlinkConstants.FLINK_YARN_CLUSTER);
// -ys
int slot = flinkParameters.getSlot();
if (slot > 0) {
args.add(FlinkConstants.FLINK_YARN_SLOT);
args.add(String.format("%d", slot));
}
// -ynm
String appName = flinkParameters.getAppName();
if (StringUtils.isNotEmpty(appName)) {
args.add(FlinkConstants.FLINK_APP_NAME);
args.add(ArgsUtils.escape(appName));
}
/**
* -yn
*
* Note: judge flink version, the parameter -yn has removed from flink 1.10
*/
String flinkVersion = flinkParameters.getFlinkVersion();
if (flinkVersion == null || FlinkConstants.FLINK_VERSION_BEFORE_1_10.equals(flinkVersion)) {
int taskManager = flinkParameters.getTaskManager();
if (taskManager > 0) {
args.add(FlinkConstants.FLINK_TASK_MANAGE);
args.add(String.format("%d", taskManager));
}
}
// -yjm
String jobManagerMemory = flinkParameters.getJobManagerMemory();
if (StringUtils.isNotEmpty(jobManagerMemory)) {
args.add(FlinkConstants.FLINK_JOB_MANAGE_MEM);
args.add(jobManagerMemory);
}
// -ytm
String taskManagerMemory = flinkParameters.getTaskManagerMemory();
if (StringUtils.isNotEmpty(taskManagerMemory)) {
args.add(FlinkConstants.FLINK_TASK_MANAGE_MEM);
args.add(taskManagerMemory);
}
// -yqu
String others = flinkParameters.getOthers();
if (StringUtils.isEmpty(others) || !others.contains(FlinkConstants.FLINK_QUEUE)) {
String queue = flinkParameters.getQueue();
if (StringUtils.isNotEmpty(queue)) {
args.add(FlinkConstants.FLINK_QUEUE);
args.add(queue);
}
}
}
/**
* build flink sql options
*
* @return argument list
*/
private List<String> populateFlinkSqlOptions() {
List<String> args = new ArrayList<>();
List<String> defalutOptions = new ArrayList<>();
String deployMode = StringUtils.isNotEmpty(flinkParameters.getDeployMode()) ? flinkParameters.getDeployMode() : FlinkConstants.DEPLOY_MODE_CLUSTER;
/**
* Currently flink sql on yarn only supports yarn-per-job mode
*/
if (!FlinkConstants.DEPLOY_MODE_LOCAL.equals(deployMode)) {
populateFlinkSqlOnYarnOptions(defalutOptions);
} else {
// execution.target
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_EXECUTION_TARGET, FlinkConstants.EXECUTION_TARGET_LOACL));
}
// parallelism.default
int parallelism = flinkParameters.getParallelism();
if (parallelism > 0) {
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_PARALLELISM_DEFAULT, parallelism));
}
// -i
args.add(FlinkConstants.FLINK_SQL_INIT_FILE);
args.add(generateInitScriptFile(StringUtils.join(defalutOptions, FlinkConstants.FLINK_SQL_NEWLINE).concat(FlinkConstants.FLINK_SQL_NEWLINE)));
// -f
args.add(FlinkConstants.FLINK_SQL_SCRIPT_FILE);
args.add(generateScriptFile());
String others = flinkParameters.getOthers();
if (StringUtils.isNotEmpty(others)) {
args.add(others);
}
return args;
}
private void populateFlinkSqlOnYarnOptions(List<String> defalutOptions) {
// execution.target
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_EXECUTION_TARGET, FlinkConstants.EXECUTION_TARGET_YARN_PER_JOB));
// taskmanager.numberOfTaskSlots
int slot = flinkParameters.getSlot();
if (slot > 0) {
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_TASKMANAGER_NUMBEROFTASKSLOTS, slot));
}
// yarn.application.name
String appName = flinkParameters.getAppName();
if (StringUtils.isNotEmpty(appName)) {
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_YARN_APPLICATION_NAME, ArgsUtils.escape(appName)));
}
// jobmanager.memory.process.size
String jobManagerMemory = flinkParameters.getJobManagerMemory();
if (StringUtils.isNotEmpty(jobManagerMemory)) {
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_JOBMANAGER_MEMORY_PROCESS_SIZE, jobManagerMemory));
}
// taskmanager.memory.process.size
String taskManagerMemory = flinkParameters.getTaskManagerMemory();
if (StringUtils.isNotEmpty(taskManagerMemory)) {
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_TASKMANAGER_MEMORY_PROCESS_SIZE, taskManagerMemory));
}
// yarn.application.queue
String others = flinkParameters.getOthers();
if (StringUtils.isEmpty(others) || !others.contains(FlinkConstants.FLINK_QUEUE)) {
String queue = flinkParameters.getQueue();
if (StringUtils.isNotEmpty(queue)) {
defalutOptions.add(String.format(FlinkConstants.FLINK_FORMAT_YARN_APPLICATION_QUEUE, queue));
}
}
}
private String generateInitScriptFile(String parameters) {
String initScriptFileName = String.format("%s/%s_init.sql", taskExecutionContext.getExecutePath(), taskExecutionContext.getTaskAppId());
File file = new File(initScriptFileName);
Path path = file.toPath();
if (!Files.exists(path)) {
Set<PosixFilePermission> perms = PosixFilePermissions.fromString(RWXR_XR_X);
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
try {
if (OSUtils.isWindows()) {
Files.createFile(path);
} else {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
Files.createFile(path, attr);
}
// Flink sql common parameters are written to the script file
logger.info("common parameters : {}", parameters);
Files.write(path, parameters.getBytes(), StandardOpenOption.APPEND);
// Flink init script is written to the script file
if (StringUtils.isNotEmpty(flinkParameters.getInitScript())) {
String script = flinkParameters.getInitScript().replaceAll("\\r\\n", "\n");
flinkParameters.setInitScript(script);
logger.info("init script : {}", flinkParameters.getInitScript());
Files.write(path, flinkParameters.getInitScript().getBytes(), StandardOpenOption.APPEND);
}
} catch (IOException e) {
throw new RuntimeException("generate flink sql script error", e);
}
}
return initScriptFileName;
}
private String generateScriptFile() {
String scriptFileName = String.format("%s/%s_node.sql", taskExecutionContext.getExecutePath(), taskExecutionContext.getTaskAppId());
File file = new File(scriptFileName);
Path path = file.toPath();
if (!Files.exists(path)) {
String script = flinkParameters.getRawScript().replaceAll("\\r\\n", "\n");
flinkParameters.setRawScript(script);
logger.info("raw script : {}", flinkParameters.getRawScript());
logger.info("task execute path : {}", taskExecutionContext.getExecutePath());
Set<PosixFilePermission> perms = PosixFilePermissions.fromString(RWXR_XR_X);
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
try {
if (OSUtils.isWindows()) {
Files.createFile(path);
} else {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
Files.createFile(path, attr);
}
// Flink sql raw script is written to the script file
Files.write(path, flinkParameters.getRawScript().getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
throw new RuntimeException("generate flink sql script error", e);
}
}
return scriptFileName;
}
@Override
protected void setMainJarName() {
ResourceInfo mainJar = flinkParameters.getMainJar();
String resourceName = getResourceNameOfMainJar(mainJar);
mainJar.setRes(resourceName);
flinkParameters.setMainJar(mainJar);
}
@Override
public AbstractParameters getParameters() {
return flinkParameters;
}
}
|
package com.github.whymesay.toy.monarch.transport;
import com.github.whymesay.toy.monarch.common.domain.RpcRequest;
import com.github.whymesay.toy.monarch.common.domain.RpcResponse;
import java.util.concurrent.Future;
/**
* The interface Client.
*
* @author whymesay
* @date 2020 /10/3 15:57
*/
public interface Client {
/**
* Request rpc future.
*
* @param request the request
* @return the future
*/
Future<RpcResponse> send(RpcRequest request);
/**
* Close.
*/
void close();
}
|
package com.fasterxml.jackson.core.read;
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.core.json.JsonFactory;
import com.fasterxml.jackson.core.json.JsonReadFeature;
/**
* Unit tests for verifying that support for (non-standard) comments
* works as expected.
*/
public class CommentParsingTest
extends com.fasterxml.jackson.core.BaseTest
{
final static String DOC_WITH_SLASHSTAR_COMMENT =
"[ /* comment:\n ends here */ 1 /* one more ok to have \"unquoted\" and non-ascii: \u3456 \u00A0 */ ]"
;
final static String DOC_WITH_SLASHSLASH_COMMENT =
"[ // comment...\n 1 \r // one more, not array: [] \u00A0 & \u3456 \n ]"
;
/*
/**********************************************************
/* Test method wrappers
/**********************************************************
*/
/**
* Unit test for verifying that by default comments are not
* recognized.
*/
public void testDefaultSettings()
{
JsonFactory f = new JsonFactory();
assertFalse(f.isEnabled(JsonReadFeature.ALLOW_JAVA_COMMENTS));
JsonParser p = f.createParser(ObjectReadContext.empty(), new StringReader("[ 1 ]"));
p.close();
}
public void testCommentsDisabled()
{
_testDisabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_INPUT_STREAM);
_testDisabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_INPUT_STREAM);
_testDisabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_INPUT_STREAM_THROTTLED);
_testDisabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_INPUT_STREAM_THROTTLED);
_testDisabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_READER);
_testDisabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_READER);
_testDisabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_DATA_INPUT);
_testDisabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_DATA_INPUT);
}
public void testCommentsEnabled()
{
_testEnabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_INPUT_STREAM);
_testEnabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_INPUT_STREAM);
_testEnabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_INPUT_STREAM_THROTTLED);
_testEnabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_INPUT_STREAM_THROTTLED);
_testEnabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_READER);
_testEnabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_READER);
_testEnabled(DOC_WITH_SLASHSTAR_COMMENT, MODE_DATA_INPUT);
_testEnabled(DOC_WITH_SLASHSLASH_COMMENT, MODE_DATA_INPUT);
}
public void testCommentsWithUTF8()
{
final String JSON = "/* \u00a9 2099 Yoyodyne Inc. */\n [ \"bar? \u00a9\" ]\n";
_testWithUTF8Chars(JSON, MODE_INPUT_STREAM);
_testWithUTF8Chars(JSON, MODE_INPUT_STREAM_THROTTLED);
_testWithUTF8Chars(JSON, MODE_READER);
_testWithUTF8Chars(JSON, MODE_DATA_INPUT);
}
public void testYAMLCommentsBytes() {
final JsonFactory f = JsonFactory.builder()
.enable(JsonReadFeature.ALLOW_YAML_COMMENTS)
.build();
_testYAMLComments(f, MODE_INPUT_STREAM);
_testCommentsBeforePropValue(f, MODE_INPUT_STREAM, "# foo\n");
_testYAMLComments(f, MODE_INPUT_STREAM_THROTTLED);
_testCommentsBeforePropValue(f, MODE_INPUT_STREAM_THROTTLED, "# foo\n");
_testYAMLComments(f, MODE_DATA_INPUT);
_testCommentsBeforePropValue(f, MODE_DATA_INPUT, "# foo\n");
}
public void testYAMLCommentsChars() {
final JsonFactory f = JsonFactory.builder()
.enable(JsonReadFeature.ALLOW_YAML_COMMENTS)
.build();
_testYAMLComments(f, MODE_READER);
final String COMMENT = "# foo\n";
_testCommentsBeforePropValue(f, MODE_READER, COMMENT);
_testCommentsBetweenArrayValues(f, MODE_READER, COMMENT);
}
public void testCCommentsBytes() {
final JsonFactory f = JsonFactory.builder()
.enable(JsonReadFeature.ALLOW_JAVA_COMMENTS)
.build();
final String COMMENT = "/* foo */\n";
_testCommentsBeforePropValue(f, MODE_INPUT_STREAM, COMMENT);
_testCommentsBeforePropValue(f, MODE_INPUT_STREAM_THROTTLED, COMMENT);
_testCommentsBeforePropValue(f, MODE_DATA_INPUT, COMMENT);
}
public void testCCommentsChars() {
final JsonFactory f = JsonFactory.builder()
.enable(JsonReadFeature.ALLOW_JAVA_COMMENTS)
.build();
final String COMMENT = "/* foo */\n";
_testCommentsBeforePropValue(f, MODE_READER, COMMENT);
}
public void testCppCommentsBytes() {
final JsonFactory f = JsonFactory.builder()
.enable(JsonReadFeature.ALLOW_JAVA_COMMENTS)
.build();
final String COMMENT = "// foo\n";
_testCommentsBeforePropValue(f, MODE_INPUT_STREAM, COMMENT);
_testCommentsBeforePropValue(f, MODE_INPUT_STREAM_THROTTLED, COMMENT);
_testCommentsBeforePropValue(f, MODE_DATA_INPUT, COMMENT);
}
public void testCppCommentsChars() {
final JsonFactory f = JsonFactory.builder()
.enable(JsonReadFeature.ALLOW_JAVA_COMMENTS)
.build();
final String COMMENT = "// foo \n";
_testCommentsBeforePropValue(f, MODE_READER, COMMENT);
}
@SuppressWarnings("resource")
private void _testCommentsBeforePropValue(JsonFactory f,
int mode, String comment)
{
for (String arg : new String[] {
":%s123",
" :%s123",
"\t:%s123",
": %s123",
":\t%s123",
}) {
String commented = String.format(arg, comment);
final String DOC = "{\"abc\"" + commented + "}";
JsonParser p = createParser(f, mode, DOC);
assertEquals(JsonToken.START_OBJECT, p.nextToken());
JsonToken t = null;
try {
t = p.nextToken();
} catch (Exception e) {
throw new RuntimeException("Failed on '"+DOC+"' due to "+e, e);
}
assertEquals(JsonToken.FIELD_NAME, t);
try {
t = p.nextToken();
} catch (Exception e) {
throw new RuntimeException("Failed on '"+DOC+"' due to "+e, e);
}
assertEquals(JsonToken.VALUE_NUMBER_INT, t);
assertEquals(123, p.getIntValue());
assertEquals(JsonToken.END_OBJECT, p.nextToken());
p.close();
}
}
@SuppressWarnings("resource")
private void _testCommentsBetweenArrayValues(JsonFactory f,
int mode, String comment)
{
for (String tmpl : new String[] {
"%s,",
" %s,",
"\t%s,",
"%s ,",
"%s\t,",
" %s ,",
"\t%s\t,",
"\n%s,",
"%s\n,",
}) {
String commented = String.format(tmpl, comment);
final String DOC = "[1"+commented+"2]";
JsonParser p = createParser(f, mode, DOC);
assertEquals(JsonToken.START_ARRAY, p.nextToken());
JsonToken t = null;
try {
t = p.nextToken();
} catch (Exception e) {
throw new RuntimeException("Failed on '"+DOC+"' due to "+e, e);
}
assertEquals(JsonToken.VALUE_NUMBER_INT, t);
assertEquals(1, p.getIntValue());
try {
t = p.nextToken();
} catch (Exception e) {
throw new RuntimeException("Failed on '"+DOC+"' due to "+e, e);
}
assertEquals(JsonToken.VALUE_NUMBER_INT, t);
assertEquals(2, p.getIntValue());
assertEquals(JsonToken.END_ARRAY, p.nextToken());
p.close();
}
}
private void _testYAMLComments(JsonFactory f, int mode)
{
final String DOC = "# foo\n"
+" {\"a\" # xyz\n"
+" : # foo\n"
+" 1, # more\n"
+"\"b\": [ \n"
+" #all!\n"
+" 3 #yay!\n"
+"] # foobar\n"
+"} # x"
;
JsonParser p = createParser(f, mode, DOC);
assertEquals(JsonToken.START_OBJECT, p.nextToken());
assertEquals(JsonToken.FIELD_NAME, p.nextToken());
assertEquals("a", p.currentName());
assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(1, p.getIntValue());
assertEquals(JsonToken.FIELD_NAME, p.nextToken());
assertEquals("b", p.currentName());
assertEquals(JsonToken.START_ARRAY, p.nextToken());
assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(3, p.getIntValue());
assertEquals(JsonToken.END_ARRAY, p.nextToken());
assertEquals(JsonToken.END_OBJECT, p.nextToken());
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
}
/*
/**********************************************************
/* Helper methods
/**********************************************************
*/
private void _testWithUTF8Chars(String doc, int mode)
{
// should basically just stream through
JsonParser p = _createParser(doc, mode, true);
assertToken(JsonToken.VALUE_STRING, p.nextToken());
assertToken(JsonToken.END_ARRAY, p.nextToken());
if (mode != MODE_DATA_INPUT) {
assertNull(p.nextToken());
}
p.close();
}
private void _testDisabled(String doc, int mode)
{
JsonParser p = _createParser(doc, mode, false);
try {
p.nextToken();
fail("Expected exception for unrecognized comment");
} catch (StreamReadException je) {
// Should have something denoting that user may want to enable 'ALLOW_COMMENTS'
verifyException(je, "ALLOW_COMMENTS");
}
p.close();
}
private void _testEnabled(String doc, int mode)
{
JsonParser p = _createParser(doc, mode, true);
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(1, p.getIntValue());
assertToken(JsonToken.END_ARRAY, p.nextToken());
p.close();
}
private JsonParser _createParser(String doc, int mode, boolean enabled)
{
final JsonFactory f = JsonFactory.builder()
.configure(JsonReadFeature.ALLOW_JAVA_COMMENTS, enabled)
.build();
JsonParser p = createParser(f, mode, doc);
assertToken(JsonToken.START_ARRAY, p.nextToken());
return p;
}
}
|
/*
* The MIT License
*
* Copyright 2010 Sony Ericsson Mobile Communications. All rights reserved.
* Copyright 2012 Sony Mobile Communications AB. All rights reserved.
*
* 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.sonyericsson.hudson.plugins.gerrit.trigger.utils;
import com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer;
import com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl;
import com.sonymobile.tools.gerrit.gerritevents.GerritEventListener;
import com.sonymobile.tools.gerrit.gerritevents.dto.events.ChangeBasedEvent;
import java.util.regex.Pattern;
/**
* Various string making utility methods.
* @author Robert Sandell <robert.sandell@sonyericsson.com>
*/
public final class StringUtil {
/**
* What comes before the change and patch numbers in a refspec.
*/
public static final String REFSPEC_PREFIX = "refs/changes/";
/**
* The base URL of this plugin. Only valid for web resources.
*/
public static final String PLUGIN_URL = "/plugin/gerrit-trigger/";
/**
* the field will be used as quote "\""
*/
private static final Pattern QUOTES_PATTERN = Pattern.compile("\"");
/**
* The base URL of the plugin images.
*/
public static final String PLUGIN_IMAGES_URL = PLUGIN_URL + "images/";
/**
* The base URL of the plugin javascripts.
*/
public static final String PLUGIN_JS_URL = PLUGIN_URL + "js/";
/**
* Private Constructor for Utility Class.
*/
private StringUtil() {
}
/**
* Creates a refspec string from the data in the event.
* Unless the patch-set already has a refspec specified.
* For a change with number 3456 and patchset 1 the refspec would be refs/changes/56/3456/1
* @param event the event.
* @return the refspec.
* @see ChangeBasedEvent#getPatchSet()
* @see com.sonymobile.tools.gerrit.gerritevents.dto.attr.PatchSet#getRef()
*/
public static String makeRefSpec(ChangeBasedEvent event) {
if (event.getPatchSet() != null && event.getPatchSet().getRef() != null) {
if (event.getPatchSet().getRef().length() > 0) {
return event.getPatchSet().getRef();
}
}
StringBuilder str = new StringBuilder(REFSPEC_PREFIX);
String number = event.getChange().getNumber();
if (number.length() < 2) {
str.append("0").append(number);
} else if (number.length() == 2) {
str.append(number);
} else {
str.append(number.substring(number.length() - 2));
}
str.append("/").append(number);
str.append("/").append(event.getPatchSet().getNumber());
return str.toString();
}
/**
* Gets the path to the provided image inside this plugin.
* The path returned is "compliant" with what for example {@link hudson.model.Action#getIconFileName()} expects.
* @param imageName the fileName of the image.
* @return the full path to the image.
* @see #PLUGIN_IMAGES_URL
*/
public static String getPluginImageUrl(String imageName) {
return PLUGIN_IMAGES_URL + imageName;
}
/**
* Gets the path to the provided javascript file inside this plugin.
* @param jsName the name if the javascript.
* @return the full path to the file.
* @see #PLUGIN_JS_URL
*/
public static String getPluginJsUrl(String jsName) {
return PLUGIN_JS_URL + jsName;
}
/**
* Escape quotes in String value.
* @param value the name of String object having quotes.
* @return String object as the result of escape quotes in input.
*/
public static String escapeQuotes(String value) {
if (value == null) {
return null;
} else {
return QUOTES_PATTERN.matcher(value).replaceAll("\\\\\"");
}
}
/**
* Helper method for {@link com.sonyericsson.hudson.plugins.gerrit.trigger.NamedGerritEventListener}s.
* To display a consistent "Server: Simple Name" pattern.
* Usable by {@link com.sonyericsson.hudson.plugins.gerrit.trigger.diagnostics.Diagnostics}.
*
* @param listener the listener to get the class name from
* @param serverName the name of the server to get the server's display name from,
* null or empty string produces "Any Server"
* @return the name to display.
*/
public static String getDefaultDisplayNameForSpecificServer(GerritEventListener listener, String serverName) {
StringBuilder name = new StringBuilder("");
if (GerritServer.isAnyServer(serverName)) {
name.append("Any Server: ");
} else {
GerritServer server = PluginImpl.getServer_(serverName);
if (server != null) {
name.append(server.getDisplayName());
} else {
name.append(serverName);
}
name.append(": ");
}
name.append(listener.getClass().getSimpleName());
return name.toString();
}
}
|
/*
* 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.ignite.ci.tcbot.conf;
import com.google.common.base.MoreObjects;
import java.util.Collection;
import java.util.HashSet;
/**
*
*/
public class NotificationChannel implements INotificationChannel {
/** Email. */
private String email;
/** Slack. */
private String slack;
/** Subscribed to failures in tracked branches. */
private Collection<String> subscribed = new HashSet<>();
/** {@inheritDoc} */
@Override public boolean isSubscribed(String trackedBranchId) {
return subscribed != null && subscribed.contains(trackedBranchId);
}
/** {@inheritDoc} */
@Override public boolean isServerAllowed(String srvCode) {
return true;
}
/** {@inheritDoc} */
@Override public String email() {
return email;
}
/** {@inheritDoc} */
@Override public String slack() {
return slack;
}
public void slack(String slack) {
this.slack = slack;
}
public void subscribe(String trackedBranchName) {
this.subscribed.add(trackedBranchName);
}
/** {@inheritDoc} */
@Override public String toString() {
return MoreObjects.toStringHelper(this)
.add("email", email)
.add("slack", slack)
.add("subscribed", subscribed)
.toString();
}
}
|
package com.github.kklisura.cdt.protocol.types.page;
/*-
* #%L
* cdt-java-client
* %%
* Copyright (C) 2018 - 2020 Kenan Klisura
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.github.kklisura.cdt.protocol.support.annotations.Optional;
public class Navigate {
private String frameId;
@Optional private String loaderId;
@Optional private String errorText;
/** Frame id that has navigated (or failed to navigate) */
public String getFrameId() {
return frameId;
}
/** Frame id that has navigated (or failed to navigate) */
public void setFrameId(String frameId) {
this.frameId = frameId;
}
/** Loader identifier. */
public String getLoaderId() {
return loaderId;
}
/** Loader identifier. */
public void setLoaderId(String loaderId) {
this.loaderId = loaderId;
}
/** User friendly error message, present if and only if navigation has failed. */
public String getErrorText() {
return errorText;
}
/** User friendly error message, present if and only if navigation has failed. */
public void setErrorText(String errorText) {
this.errorText = errorText;
}
}
|
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.impl;
import com.hazelcast.map.MapInterceptor;
import com.hazelcast.spi.impl.operationexecutor.impl.PartitionOperationThread;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableMap;
/**
* Registry for {@code IMap} interceptors
*
* Interceptors are read mostly and this registry keeps all registered interceptor in an array to easily iterate on them.
* Other than that, synchronized blocks are used to prevent leaks when concurrently registering/de-registering interceptors.
* Keep in mind that all registration/de-registration operations are done in generic-operation-threads, in other words,
* synchronized methods are not used in partition-threads.
*
* This registry is created per map.
*
* @see MapInterceptor
*/
public class InterceptorRegistry {
private volatile List<MapInterceptor> interceptors = emptyList();
private volatile Map<String, MapInterceptor> id2InterceptorMap = emptyMap();
/**
* Returns all registered interceptors.
*
* This method is called by {@link PartitionOperationThread}
*
* @return all registered interceptors
* @see com.hazelcast.map.impl.recordstore.DefaultRecordStore#put
*/
public List<MapInterceptor> getInterceptors() {
return interceptors;
}
public Map<String, MapInterceptor> getId2InterceptorMap() {
return id2InterceptorMap;
}
/**
* Registers a {@link MapInterceptor} for the supplied `id`.
* If there is no registration associated with the `id`, registers interceptor,
* otherwise silently ignores registration.
*
* This method is called by {@link com.hazelcast.spi.impl.operationexecutor.impl.GenericOperationThread}
* when registering via {@link com.hazelcast.map.impl.operation.AddInterceptorOperation}
*
* @param id id of the interceptor
* @param interceptor supplied {@link MapInterceptor}
*/
public synchronized void register(String id, MapInterceptor interceptor) {
assert !(Thread.currentThread() instanceof PartitionOperationThread);
if (id2InterceptorMap.containsKey(id)) {
return;
}
Map<String, MapInterceptor> tmpMap = new HashMap<String, MapInterceptor>(id2InterceptorMap);
tmpMap.put(id, interceptor);
id2InterceptorMap = unmodifiableMap(tmpMap);
List<MapInterceptor> tmpInterceptors = new ArrayList<MapInterceptor>(interceptors);
tmpInterceptors.add(interceptor);
interceptors = unmodifiableList(tmpInterceptors);
}
/**
* De-registers {@link MapInterceptor} for the supplied `id`, if there is any.
*
* This method is called by {@link com.hazelcast.spi.impl.operationexecutor.impl.GenericOperationThread}
* when de-registering via {@link com.hazelcast.map.impl.operation.RemoveInterceptorOperation}
*
* @param id id of the interceptor
*/
public synchronized void deregister(String id) {
assert !(Thread.currentThread() instanceof PartitionOperationThread);
if (!id2InterceptorMap.containsKey(id)) {
return;
}
Map<String, MapInterceptor> tmpMap = new HashMap<String, MapInterceptor>(id2InterceptorMap);
MapInterceptor removedInterceptor = tmpMap.remove(id);
id2InterceptorMap = unmodifiableMap(tmpMap);
List<MapInterceptor> tmpInterceptors = new ArrayList<MapInterceptor>(interceptors);
tmpInterceptors.remove(removedInterceptor);
interceptors = unmodifiableList(tmpInterceptors);
}
}
|
package com.zhiliao.coupon.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zhiliao.coupon.entity.HomeSubjectSpuEntity;
import com.zhiliao.coupon.service.HomeSubjectSpuService;
import com.zhiliao.common.utils.PageUtils;
import com.zhiliao.common.utils.R;
/**
* 专题商品
*
* @author songnan
* @email nanjiye123@163.com
* @date 2020-11-02 01:03:00
*/
@RestController
@RequestMapping("coupon/homesubjectspu")
public class HomeSubjectSpuController {
@Autowired
private HomeSubjectSpuService homeSubjectSpuService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("coupon:homesubjectspu:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = homeSubjectSpuService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("coupon:homesubjectspu:info")
public R info(@PathVariable("id") Long id){
HomeSubjectSpuEntity homeSubjectSpu = homeSubjectSpuService.getById(id);
return R.ok().put("homeSubjectSpu", homeSubjectSpu);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("coupon:homesubjectspu:save")
public R save(@RequestBody HomeSubjectSpuEntity homeSubjectSpu){
homeSubjectSpuService.save(homeSubjectSpu);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("coupon:homesubjectspu:update")
public R update(@RequestBody HomeSubjectSpuEntity homeSubjectSpu){
homeSubjectSpuService.updateById(homeSubjectSpu);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("coupon:homesubjectspu:delete")
public R delete(@RequestBody Long[] ids){
homeSubjectSpuService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.messaging.remote.internal.inet;
import org.gradle.messaging.remote.internal.*;
import java.nio.channels.SocketChannel;
class SocketConnectCompletion implements ConnectCompletion {
private final SocketChannel socket;
public SocketConnectCompletion(SocketChannel socket) {
this.socket = socket;
}
@Override
public String toString() {
return String.format("%s to %s", socket.socket().getLocalSocketAddress(), socket.socket().getRemoteSocketAddress());
}
public <T> RemoteConnection<T> create(ClassLoader messageClassLoader) {
return new SocketConnection<T>(socket, new DefaultMessageSerializer<T>(messageClassLoader));
}
public <T> RemoteConnection<T> create(MessageSerializer<T> serializer) {
return new SocketConnection<T>(socket, serializer);
}
}
|
package score;
/**
* MA42 Android用Java文法 Lesson2 Ex2
*
* 学生の英数国の成績情報を表すクラス。
*
* @author Shinzo SAITO
*/
public class TestScore {
/**
* 名前。
*/
private String _name;
/**
* 英語の点数。
*/
private int _english;
/**
* 数学の点数。
*/
private int _math;
/**
* 国語の点数。
*/
private int _japanese;
/**
* フィールドにデータを格納するメソッド。
*
* @param name 名前。
* @param english 英語の点数。
* @param math 数学の点数。
* @param japanese 国語の点数。
*/
public void setData(String name, int english, int math, int japanese) {
_name = name;
_english = english;
_math = math;
_japanese = japanese;
}
/**
* フィールドにデータを格納するメソッド。
*
* @param name 名前。
*/
public void setData(String name) {
setData(name, 0, 0, 0);
}
/**
* 合計点を表示するメソッド。
*/
public void print() {
int sum = _english + _math + _japanese;
System.out.println(_name + "さんの3教科合計点: " + sum);
}
}
|
package org.hetida.designer.backend.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class BaseItemDTO extends ParentDTO {
private List<IODTO> inputs = new ArrayList<>();
private List<IODTO> outputs = new ArrayList<>();
private List<WiringDTO> wirings = new ArrayList<>();
}
|
package net.petrikainulainen.spring.social.signinmvc;
/**
* @author Petri Kainulainen
*/
public class WebTestConstants {
public static final String FORM_FIELD_EMAIL = "email";
public static final String FORM_FIELD_FIRST_NAME = "firstName";
public static final String FORM_FIELD_LAST_NAME = "lastName";
public static final String FORM_FIELD_PASSWORD = "password";
public static final String FORM_FIELD_PASSWORD_VERIFICATION = "passwordVerification";
public static final String FORM_FIELD_SIGN_IN_PROVIDER = "signInProvider";
public static final String MODEL_ATTRIBUTE_USER_FORM = "user";
public static final String SESSION_ATTRIBUTE_USER_FORM = "user";
private WebTestConstants() {}
}
|
package com.baoying.enginex.executor.common.mapper;
import java.util.List;
public abstract interface BaseMapper<IdEntity> {
/**
* @Description: 根据对象删除数据
* @param entity 对象
* @return 是否删除成功
*/
int deleteByExample(IdEntity entity);
/**
* @Description: 根据对象主键ID删除数据
* @param id 对象id编号
* @return 是否删除成功
*/
int deleteByPrimaryKey(Long id);
/**
* @Description: 插入一条新的数据
* @param entity 对象
* @return 是否插入成功
*/
int insertSelective(IdEntity entity);
/**
* @Description: 根据对象主键更新对象信息
* @param entity 对象
* @return 是否修改成功标志
*/
int updateByPrimaryKeySelective(IdEntity entity);
/**
* @Description: 根据对象获取数据条数
* @param entity 对象
* @return 返回行数
*/
int countByExample(IdEntity entity);
/**
* @Description: 根据对象主键ID获取指定数据(多个)
* @param entity 对象
* @return 对象列表
*/
List<IdEntity> selectByExample(IdEntity entity);
/**
* @Description: 根据对象主键ID获取指定数据(单个)
* @param id id编号
* @return 返回单个对象
*/
IdEntity selectByPrimaryKey(Long id);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.