text
stringlengths 7
1.01M
|
|---|
/*
* 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.commons.functor.generator.loop;
import org.apache.commons.functor.UnaryPredicate;
import org.apache.commons.functor.UnaryProcedure;
import org.apache.commons.functor.generator.Generator;
import org.apache.commons.lang3.Validate;
/**
* Wrap another {@link Generator} such that {@link #run(UnaryProcedure)} terminates once
* a condition has been satisfied (test after).
*
* @param <E> the type of elements held in this generator.
* @version $Revision: 1376354 $ $Date: 2012-08-23 00:04:55 -0300 (Thu, 23 Aug 2012) $
*/
public class GenerateUntil<E> extends LoopGenerator<E> {
/**
* The condition has to verified in order to execute the generation.
*/
private final UnaryPredicate<? super E> test;
/**
* Create a new GenerateUntil.
* @param wrapped {@link Generator}
* @param test {@link UnaryPredicate}
*/
public GenerateUntil(Generator<? extends E> wrapped, UnaryPredicate<? super E> test) {
super(Validate.notNull(wrapped, "Generator argument was null"));
this.test = Validate.notNull(test, "UnaryPredicate argument was null");
}
/**
* {@inheritDoc}
*/
public void run(final UnaryProcedure<? super E> proc) {
getWrappedGenerator().run(new UnaryProcedure<E>() {
public void run(E obj) {
proc.run(obj);
if (test.test(obj)) {
GenerateUntil.this.stop();
}
}
});
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof GenerateUntil<?>)) {
return false;
}
GenerateUntil<?> other = (GenerateUntil<?>) obj;
return other.getWrappedGenerator().equals(getWrappedGenerator()) && other.test.equals(test);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int result = "GenerateUntil".hashCode();
result <<= 2;
Generator<?> gen = getWrappedGenerator();
result ^= gen.hashCode();
result <<= 2;
result ^= test.hashCode();
return result;
}
}
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.1
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.quantlib;
public class QuantoForwardEuropeanEngine extends PricingEngine {
private transient long swigCPtr;
private transient boolean swigCMemOwnDerived;
protected QuantoForwardEuropeanEngine(long cPtr, boolean cMemoryOwn) {
super(QuantLibJNI.QuantoForwardEuropeanEngine_SWIGSmartPtrUpcast(cPtr), true);
swigCMemOwnDerived = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(QuantoForwardEuropeanEngine obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void swigSetCMemOwn(boolean own) {
swigCMemOwnDerived = own;
super.swigSetCMemOwn(own);
}
@SuppressWarnings("deprecation")
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwnDerived) {
swigCMemOwnDerived = false;
QuantLibJNI.delete_QuantoForwardEuropeanEngine(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public QuantoForwardEuropeanEngine(GeneralizedBlackScholesProcess process, YieldTermStructureHandle foreignRiskFreeRate, BlackVolTermStructureHandle exchangeRateVolatility, QuoteHandle correlation) {
this(QuantLibJNI.new_QuantoForwardEuropeanEngine(GeneralizedBlackScholesProcess.getCPtr(process), process, YieldTermStructureHandle.getCPtr(foreignRiskFreeRate), foreignRiskFreeRate, BlackVolTermStructureHandle.getCPtr(exchangeRateVolatility), exchangeRateVolatility, QuoteHandle.getCPtr(correlation), correlation), true);
}
}
|
package com.data.output;
/**
* Generated for query "getCommentEmails" on 06/09/2010 16:20:40
*
*/
public class GetCommentEmailsRtnType {
private String email;
public GetCommentEmailsRtnType() {
}
public GetCommentEmailsRtnType(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package com.lesath.apps.controller.getSchedule;
public class GetScheduleRequest {
String uuid;
public GetScheduleRequest(String uuid) {
this.uuid = uuid;
}
}
|
package com.aunghan.stockmanagementsystem.entity;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
@Column(name="token")
private String token;
@Column(name="email")
private String email;
@Column(name="access_level")
private int accessLevel;
@Column(name="is_active")
private boolean isActive;
public User(){}
public User(String username, String password, String email, int accessLevel) {
this.username = username;
this.password = password;
this.email = email;
this.accessLevel = accessLevel;
}
public String toString(){
return String.format("User=[id:%d, username:%s]", this.id, this.username);
}
}
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.auton;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.WaitCommand;
import frc.robot.util;
import frc.robot.commands.BeakAutonCommand;
import frc.robot.commands.chassis.RotateDrivetrainToAngle;
import frc.robot.commands.conveyor.ReverseInfeedAndConveyor;
import frc.robot.commands.conveyor.RunConveyor;
import frc.robot.commands.shooter.ResetDefaultIndex;
import frc.robot.subsystems.Infeed;
import frc.robot.subsystems.Shooter;
import frc.robot.utilities.Trajectories;
// NOTE: Consider using this command inline, rather than writing a subclass. For more
// information, see:
// https://docs.wpilib.org/en/stable/docs/software/commandbased/convenience-features.html
public class TwoBallTopHangarDisposal extends BeakAutonCommand {
/** Creates a new TwoBallTopHangarDisposal. */
public TwoBallTopHangarDisposal() {
// Add your commands in the addCommands() call, e.g.
// addCommands(new FooCommand(), new BarCommand());
super.addCommands(
new ResetDefaultIndex(),
new InstantCommand(() -> Infeed.getInstance().setInfeedDown()),
new WaitCommand(0.25),
new InstantCommand(() -> Infeed.getInstance().forceRunInfeed()),
util.getPathPlannerSwerveControllerCommand(Trajectories.TwoBall_Top()),
new RotateDrivetrainToAngle(Rotation2d.fromDegrees(-32.0)),
new InstantCommand(() -> Shooter.getInstance().runShooterMotors()),
new WaitCommand(0.5),
new RunConveyor().withTimeout(1.5),
new InstantCommand(() -> Shooter.getInstance().stop()),
new InstantCommand(() -> Infeed.getInstance().runInfeedSingulatorMotors(1.0)),
util.getPathPlannerSwerveControllerCommand(Trajectories.TwoBall_TopHangarDisposalFirstOpponentBall()),
new WaitCommand(0.25),
new InstantCommand(() -> Infeed.getInstance().stopInfeedSingulatorMotors()),
new RotateDrivetrainToAngle(
Trajectories.TwoBall_TopHangarDisposalSecondOpponentBall().getInitialState().holonomicRotation),
new ReverseInfeedAndConveyor().withTimeout(2.0),
new InstantCommand(() -> Infeed.getInstance().runInfeedSingulatorMotors(1.0)),
util.getPathPlannerSwerveControllerCommand(Trajectories.TwoBall_TopHangarDisposalSecondOpponentBall()),
new WaitCommand(0.25),
new RotateDrivetrainToAngle(Rotation2d.fromDegrees(175.0)),
new InstantCommand(() -> Infeed.getInstance().stopInfeedSingulatorMotors()),
new ReverseInfeedAndConveyor().withTimeout(2.0));
super.setInitialPose(Trajectories.TwoBall_Top());
}
}
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.designer.web.server.menu.connector.commands;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jbpm.designer.repository.Repository;
import org.jbpm.designer.web.profile.IDiagramProfile;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PasteCommand extends AbstractCommand {
private static Logger logger = LoggerFactory.getLogger(PasteCommand.class);
private HttpServletRequest request;
private HttpServletResponse response;
private IDiagramProfile profile;
private Repository repository;
private Map<String, Object> requestParams;
public void init(HttpServletRequest request,
HttpServletResponse response,
IDiagramProfile profile,
Repository repository,
Map<String, Object> requestParams) {
this.request = request;
this.response = response;
this.profile = profile;
this.repository = repository;
this.requestParams = requestParams;
}
public JSONObject execute() throws Exception {
String current = (String) requestParams.get("current");
List<String> targets = (List<String>) requestParams.get("targets[]");
String cut = (String) requestParams.get("cut");
String dst = (String) requestParams.get("dst");
String src = (String) requestParams.get("src");
String tree = (String) requestParams.get("tree");
return pasteDirectoriesOrAssets(profile,
current,
targets,
cut,
dst,
src,
Boolean.parseBoolean(tree));
}
}
|
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.core.parsing.antlr.extractor.registry.dialect;
import io.shardingsphere.core.parsing.antlr.extractor.SQLStatementExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.SQLStatementType;
import io.shardingsphere.core.parsing.antlr.extractor.registry.SQLStatementExtractorRegistry;
import io.shardingsphere.core.parsing.antlr.extractor.statement.type.CreateTableExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.statement.type.IndexWithTableStatementExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.statement.type.OnlyMultiTableExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.statement.type.OnlySingleTableExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.statement.type.TCLStatementExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.statement.type.dialect.mysql.MySQLAlterTableExtractor;
import java.util.HashMap;
import java.util.Map;
/**
* SQL statement extractor registry for MySQL.
*
* @author duhongjun
* @author zhangliang
*/
public final class MySQLStatementExtractorRegistry implements SQLStatementExtractorRegistry {
private static final Map<SQLStatementType, SQLStatementExtractor> EXTRACTORS = new HashMap<>();
static {
registerDDL();
registerTCL();
registerDAL();
}
private static void registerDDL() {
EXTRACTORS.put(SQLStatementType.CREATE_TABLE, new CreateTableExtractor());
EXTRACTORS.put(SQLStatementType.ALTER_TABLE, new MySQLAlterTableExtractor());
EXTRACTORS.put(SQLStatementType.DROP_TABLE, new OnlyMultiTableExtractor());
EXTRACTORS.put(SQLStatementType.TRUNCATE_TABLE, new OnlySingleTableExtractor());
EXTRACTORS.put(SQLStatementType.CREATE_INDEX, new IndexWithTableStatementExtractor());
EXTRACTORS.put(SQLStatementType.DROP_INDEX, new IndexWithTableStatementExtractor());
}
private static void registerTCL() {
EXTRACTORS.put(SQLStatementType.SET_TRANSACTION, new TCLStatementExtractor());
EXTRACTORS.put(SQLStatementType.COMMIT, new TCLStatementExtractor());
EXTRACTORS.put(SQLStatementType.ROLLBACK, new TCLStatementExtractor());
EXTRACTORS.put(SQLStatementType.SAVEPOINT, new TCLStatementExtractor());
EXTRACTORS.put(SQLStatementType.BEGIN_WORK, new TCLStatementExtractor());
}
private static void registerDAL() {
EXTRACTORS.put(SQLStatementType.SET_VARIABLE, new TCLStatementExtractor());
}
@Override
public SQLStatementExtractor getSQLStatementExtractor(final SQLStatementType type) {
return EXTRACTORS.get(type);
}
}
|
/**
* Copyright (C) 2010-2013 eBusiness Information, Excilys Group
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed To in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.androidannotations.holder;
import static com.sun.codemodel.JExpr._new;
import static com.sun.codemodel.JExpr._this;
import static com.sun.codemodel.JMod.FINAL;
import static com.sun.codemodel.JMod.PUBLIC;
import static org.androidannotations.helper.CanonicalNameConstants.REST_TEMPLATE;
import static org.androidannotations.helper.CanonicalNameConstants.STRING;
import java.util.List;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import org.androidannotations.api.rest.RestErrorHandler;
import org.androidannotations.helper.APTCodeModelHelper;
import org.androidannotations.helper.CanonicalNameConstants;
import org.androidannotations.helper.ModelConstants;
import org.androidannotations.process.ProcessHolder;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JInvocation;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
public class RestHolder extends BaseGeneratedClassHolder {
private APTCodeModelHelper codeModelHelper;
private JMethod init;
private JFieldVar rootUrlField;
private JFieldVar restTemplateField;
private JFieldVar availableHeadersField;
private JFieldVar availableCookiesField;
private JFieldVar authenticationField;
private JFieldVar restErrorHandlerField;
public RestHolder(ProcessHolder processHolder, TypeElement annotatedElement) throws Exception {
super(processHolder, annotatedElement);
codeModelHelper = new APTCodeModelHelper();
implementMethods();
}
@Override
protected void setGeneratedClass() throws Exception {
String annotatedComponentQualifiedName = annotatedElement.getQualifiedName().toString();
String subComponentQualifiedName = annotatedComponentQualifiedName + ModelConstants.GENERATION_SUFFIX;
JClass annotatedComponent = codeModel().directClass(annotatedComponentQualifiedName);
generatedClass = codeModel()._class(PUBLIC | FINAL, subComponentQualifiedName, ClassType.CLASS);
generatedClass._implements(annotatedComponent);
}
private void implementMethods() {
List<ExecutableElement> methods = codeModelHelper.getMethods(getAnnotatedElement());
// rest template
implementGetRestTemplate(methods);
implementSetRestTemplate(methods);
// root url
implementGetRootUrl(methods);
implementSetRootUrl(methods);
// authentication
implementSetBasicAuth(methods);
implementSetAuthentication(methods);
// cookies and headers
implementGetCookie(methods);
implementGetHeader(methods);
implementSetCookie(methods);
implementSetHeader(methods);
// error handler.
implementSetErrorHandler(methods);
}
private void implementGetRestTemplate(List<ExecutableElement> methods) {
JMethod getRestTemplateMethod = codeModelHelper.implementMethod(this, methods, null, REST_TEMPLATE);
if (getRestTemplateMethod != null) {
getRestTemplateMethod.body()._return(getRestTemplateField());
}
}
private void implementSetRestTemplate(List<ExecutableElement> methods) {
JMethod setRestTemplateMethod = codeModelHelper.implementMethod(this, methods, null, TypeKind.VOID.toString(), REST_TEMPLATE);
if (setRestTemplateMethod != null) {
setRestTemplateMethod.body().assign(_this().ref(getRestTemplateField()), setRestTemplateMethod.params().get(0));
}
}
private void implementGetRootUrl(List<ExecutableElement> methods) {
JMethod getRootUrlMethod = codeModelHelper.implementMethod(this, methods, "getRootUrl", STRING);
if (getRootUrlMethod != null) {
getRootUrlMethod.body()._return(getRootUrlField());
}
}
private void implementSetRootUrl(List<ExecutableElement> methods) {
JMethod setRootUrlMethod = codeModelHelper.implementMethod(this, methods, "setRootUrl", TypeKind.VOID.toString(), STRING);
if (setRootUrlMethod != null) {
setRootUrlMethod.body().assign(_this().ref(getRootUrlField()), setRootUrlMethod.params().get(0));
}
}
private void implementSetBasicAuth(List<ExecutableElement> methods) {
JMethod setAuthMethod = codeModelHelper.implementMethod(this, methods, "setHttpBasicAuth", TypeKind.VOID.toString(), STRING, STRING);
if (setAuthMethod != null) {
JClass basicAuthClass = classes().HTTP_BASIC_AUTHENTICATION;
JInvocation basicAuthentication = JExpr._new(basicAuthClass).arg(setAuthMethod.params().get(0)).arg(setAuthMethod.params().get(1));
setAuthMethod.body().assign(_this().ref(getAuthenticationField()), basicAuthentication);
}
}
private void implementSetAuthentication(List<ExecutableElement> methods) {
JMethod setAuthMethod = codeModelHelper.implementMethod(this, methods, "setAuthentication", TypeKind.VOID.toString(), CanonicalNameConstants.HTTP_AUTHENTICATION);
if (setAuthMethod != null) {
setAuthMethod.body().assign(_this().ref(getAuthenticationField()), setAuthMethod.params().get(0));
}
}
private void implementGetCookie(List<ExecutableElement> methods) {
JMethod getCookieMethod = codeModelHelper.implementMethod(this, methods, "getCookie", STRING, STRING);
if (getCookieMethod != null) {
JInvocation cookieValue = JExpr.invoke(getAvailableCookiesField(), "get").arg(getCookieMethod.params().get(0));
getCookieMethod.body()._return(cookieValue);
}
}
private void implementGetHeader(List<ExecutableElement> methods) {
JMethod getHeaderMethod = codeModelHelper.implementMethod(this, methods, "getHeader", STRING, STRING);
if (getHeaderMethod != null) {
JInvocation headerValue = JExpr.invoke(getAvailableHeadersField(), "get").arg(getHeaderMethod.params().get(0));
getHeaderMethod.body()._return(headerValue);
}
}
private void implementSetCookie(List<ExecutableElement> methods) {
JMethod setCookieMethod = codeModelHelper.implementMethod(this, methods, "setCookie", TypeKind.VOID.toString(), STRING, STRING);
if (setCookieMethod != null) {
setCookieMethod.body().invoke(getAvailableCookiesField(), "put").arg(setCookieMethod.params().get(0)).arg(setCookieMethod.params().get(1));
}
}
private void implementSetHeader(List<ExecutableElement> methods) {
JMethod setHeaderMethod = codeModelHelper.implementMethod(this, methods, "setHeader", TypeKind.VOID.toString(), STRING, STRING);
if (setHeaderMethod != null) {
setHeaderMethod.body().invoke(getAvailableHeadersField(), "put").arg(setHeaderMethod.params().get(0)).arg(setHeaderMethod.params().get(1));
}
}
private void implementSetErrorHandler(List<ExecutableElement> methods) {
JMethod setErrorHandlerMethod = codeModelHelper.implementMethod(this, methods, "setRestErrorHandler", TypeKind.VOID.toString(), RestErrorHandler.class.getName());
if (setErrorHandlerMethod != null) {
setErrorHandlerMethod.body().assign(_this().ref(getRestErrorHandlerField()), setErrorHandlerMethod.params().get(0));
}
}
public JMethod getInit() {
if (init == null) {
setInit();
}
return init;
}
private void setInit() {
init = getGeneratedClass().constructor(JMod.PUBLIC);
}
public JFieldVar getRootUrlField() {
if (rootUrlField == null) {
setRootUrlField();
}
return rootUrlField;
}
private void setRootUrlField() {
rootUrlField = getGeneratedClass().field(JMod.PRIVATE, classes().STRING, "rootUrl");
}
public JFieldVar getRestTemplateField() {
if (restTemplateField == null) {
setRestTemplateField();
}
return restTemplateField;
}
private void setRestTemplateField() {
restTemplateField = getGeneratedClass().field(JMod.PRIVATE, classes().REST_TEMPLATE, "restTemplate");
getInit().body().assign(restTemplateField, _new(classes().REST_TEMPLATE));
}
public JFieldVar getAvailableHeadersField() {
if (availableHeadersField == null) {
setAvailableHeadersField();
}
return availableHeadersField;
}
private void setAvailableHeadersField() {
JClass stringClass = classes().STRING;
JClass mapClass = classes().HASH_MAP.narrow(stringClass, stringClass);
availableHeadersField = getGeneratedClass().field(JMod.PRIVATE, mapClass, "availableHeaders");
init.body().assign(availableHeadersField, _new(mapClass));
}
public JFieldVar getAvailableCookiesField() {
if (availableCookiesField == null) {
setAvailableCookiesField();
}
return availableCookiesField;
}
private void setAvailableCookiesField() {
JClass stringClass = classes().STRING;
JClass mapClass = classes().HASH_MAP.narrow(stringClass, stringClass);
availableCookiesField = getGeneratedClass().field(JMod.PRIVATE, mapClass, "availableCookies");
init.body().assign(availableCookiesField, _new(mapClass));
}
public JFieldVar getAuthenticationField() {
if (authenticationField == null) {
setAuthenticationField();
}
return authenticationField;
}
private void setAuthenticationField() {
authenticationField = getGeneratedClass().field(JMod.PRIVATE, classes().HTTP_AUTHENTICATION, "authentication");
}
public JFieldVar getRestErrorHandlerField() {
if (restErrorHandlerField == null) {
setRestErrorHandlerField();
}
return restErrorHandlerField;
}
private void setRestErrorHandlerField() {
JClass restErrorHandlerClass = refClass(RestErrorHandler.class.getName());
restErrorHandlerField = getGeneratedClass().field(JMod.PRIVATE, restErrorHandlerClass, "restErrorHandler");
}
}
|
package de.adorsys.psd2.sandbox.tpp.rest.server.mapper;
import de.adorsys.ledgers.deposit.api.domain.MockBookingDetails;
import de.adorsys.psd2.sandbox.tpp.rest.api.domain.UserTransaction;
import de.adorsys.psd2.sandbox.tpp.rest.server.service.ParseService;
import org.junit.Test;
import org.mapstruct.factory.Mappers;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Currency;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class MockTransactionDataConverterTest {
private final MockTransactionDataConverter converter = Mappers.getMapper(MockTransactionDataConverter.class);
private final ResourceLoader resourceLoader = new DefaultResourceLoader();
private final ParseService parseService = new ParseService(resourceLoader);
@Test
public void toLocalDateTest() {
String input = "01.01.2019";
LocalDate result = converter.toLocalDate(input);
assertThat(result).isEqualTo(LocalDate.of(2019, 01, 01));
}
@Test
public void toLedgersMockTransactionTest() throws IOException {
List<UserTransaction> input = parseService.convertFileToTargetObject(resolveMultipartFile("transactions_template.csv"), UserTransaction.class);
MockBookingDetails expected = getExpectedMockTransaction();
MockBookingDetails result = converter.toLedgersMockTransaction(input.get(0));
assertThat(result).isEqualToComparingFieldByFieldRecursively(expected);
}
@Test
public void toLedgersMockTransactionsTest() throws IOException {
MockBookingDetails expected = getExpectedMockTransaction();
List<UserTransaction> input = getListWith2EqualTransactions();
List<MockBookingDetails> result = converter.toLedgersMockTransactions(input);
assertThat(result.size()).isEqualTo(2);
result.forEach(r -> assertThat(r).isEqualToComparingFieldByFieldRecursively(expected));
}
private List<UserTransaction> getListWith2EqualTransactions() throws IOException {
List<UserTransaction> transactionList = parseService.convertFileToTargetObject(resolveMultipartFile("transactions_template.csv"), UserTransaction.class);
transactionList.add(transactionList.get(0));
return transactionList;
}
private MockBookingDetails getExpectedMockTransaction() {
MockBookingDetails details = new MockBookingDetails();
details.setUserAccount("50405667");
details.setBookingDate(LocalDate.of(2017, 1, 30));
details.setValueDate(LocalDate.of(2017, 1, 30));
details.setRemittance("Gehalt Teambank");
details.setCrDrName("Teambank Ag");
details.setOtherAccount("7807800780");
details.setAmount(BigDecimal.valueOf(2116.17));
details.setCurrency(Currency.getInstance("EUR"));
return details;
}
private MultipartFile resolveMultipartFile(String fileName) throws IOException {
Resource resource = resourceLoader.getResource(fileName);
return new MockMultipartFile("file", resource.getFile().getName(), "text/plain", resource.getInputStream());
}
}
|
package com.ngdesk.sam.rules.dao;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ngdesk.commons.exceptions.BadRequestException;
import com.ngdesk.commons.managers.AuthManager;
import com.ngdesk.repositories.ModuleRepository;
@Valid
@Component
public class RuleService {
@Autowired
AuthManager authManager;
@Autowired
ModuleRepository moduleRepository;
public void validateRuleCondition(SamFileRule samFileRule) {
switch (samFileRule.getRuleCondition()) {
case "fileName, file Path, Hash":
case "fileName, file Path":
case "Hash":
if ((samFileRule.getFileName() == null)
|| (samFileRule.getFileName() != null && samFileRule.getFileName().isEmpty())) {
throw new BadRequestException("FILE_NAME_MISSING", null);
}
if ((samFileRule.getFilePath() == null)
|| (samFileRule.getFilePath() != null && samFileRule.getFilePath().isEmpty())) {
throw new BadRequestException("FILE_PATH_MISSING", null);
}
break;
case "fileName":
case "fileName, Hash":
if ((samFileRule.getFileName() == null)
|| (samFileRule.getFileName() != null && samFileRule.getFileName().isEmpty())) {
throw new BadRequestException("FILE_NAME_MISSING", null);
}
break;
default:
break;
}
}
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Connnection;
import Swing_Framework_Application.LoginPage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author suraj
*/
public class AdminPlus {
public static void main(String[] args) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/swing","root","sssss");
//Creating an query
String q="insert into admin(Name,Password) values (?,?)";
//getting The prpared statement
PreparedStatement stmnt=con.prepareStatement(q);
String username="Amol Nandiwale";
String passcode="Amol";
//setting the values into it by using the variables..
stmnt.setString(1,username);
stmnt.setString(2,passcode);
stmnt.executeUpdate();
System.out.println("Values inserted....");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
|
package pkgThree;
public class ClassAExtenderExtender extends ClassAExtender {
}
|
package com.example.g2048;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.processor
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|processor
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_class
DECL|class|MulticastWithOnExceptionFirstTest
specifier|public
class|class
name|MulticastWithOnExceptionFirstTest
extends|extends
name|MulticastWithOnExceptionTest
block|{
annotation|@
name|Override
DECL|method|createRouteBuilder ()
specifier|protected
name|RouteBuilder
name|createRouteBuilder
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|RouteBuilder
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|configure
parameter_list|()
throws|throws
name|Exception
block|{
name|onException
argument_list|(
name|Exception
operator|.
name|class
argument_list|)
operator|.
name|handled
argument_list|(
literal|true
argument_list|)
operator|.
name|to
argument_list|(
literal|"mock:handled"
argument_list|)
operator|.
name|transform
argument_list|(
name|simple
argument_list|(
literal|"Damn ${exception.message}"
argument_list|)
argument_list|)
expr_stmt|;
name|from
argument_list|(
literal|"direct:start"
argument_list|)
operator|.
name|multicast
argument_list|()
operator|.
name|to
argument_list|(
literal|"direct:bar"
argument_list|,
literal|"direct:foo"
argument_list|,
literal|"direct:baz"
argument_list|)
operator|.
name|end
argument_list|()
operator|.
name|to
argument_list|(
literal|"mock:result"
argument_list|)
expr_stmt|;
name|from
argument_list|(
literal|"direct:foo"
argument_list|)
operator|.
name|to
argument_list|(
literal|"mock:foo"
argument_list|)
expr_stmt|;
name|from
argument_list|(
literal|"direct:bar"
argument_list|)
operator|.
name|process
argument_list|(
operator|new
name|MyProcessor
argument_list|()
argument_list|)
operator|.
name|to
argument_list|(
literal|"mock:bar"
argument_list|)
expr_stmt|;
name|from
argument_list|(
literal|"direct:baz"
argument_list|)
operator|.
name|to
argument_list|(
literal|"mock:baz"
argument_list|)
expr_stmt|;
block|}
block|}
return|;
block|}
block|}
end_class
end_unit
|
/*
* Cpoyright (c) 2016 mikan. All rights reserved.
*/
package com.tasktoys.piclock;
import com.tasktoys.piclock.util.DateFormatConverter;
import com.tasktoys.piclock.util.Logs;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ResourceBundle;
import java.util.logging.Logger;
/**
* JavaFX controller class for {@code start.fxml}.
*
* @author mikan
* @since 1.0
*/
public class StartController implements Initializable {
@NonNull
private static final Logger log = Logger.getLogger(StartController.class.getName());
private static final String PATTERN = "yyyy/MM/dd";
@FXML
public VBox wrapper;
@FXML
public Button clockButton;
@FXML
public DatePicker countdownDatePicker;
@FXML
public Button countdownButton;
@FXML
public Label title;
public Label statusLabel;
@Override
public void initialize(URL location, ResourceBundle resources) {
Logs.applyLogLevel(log);
// Setup DatePicker format.
countdownDatePicker.setConverter(new DateFormatConverter(PATTERN));
countdownDatePicker.setPromptText("2016/11/30");
countdownButton.requestFocus();
// Setup status label.
try {
statusLabel.setText(InetAddress.getLocalHost().toString());
} catch (UnknownHostException e) {
log.throwing(StartController.class.getName(), "initialize", e);
statusLabel.setText("[ERROR] " + e.getMessage());
}
log.info(StartController.class.getSimpleName() + " initialized.");
}
/**
* Click handler for screen background.
*
* @param event mouse event
*/
@FXML
public void onWrapperClicked(MouseEvent event) {
switch (event.getButton()) {
case PRIMARY:
// Double-clicked
if (event.getClickCount() == 2) {
log.finer("Wrapper double-clicked.");
Stage primaryStage = PiClock.getPrimaryStage();
primaryStage.setFullScreen(!primaryStage.isFullScreen()); // Change full-screen or window.
}
break;
default:
log.finer("Wrapper clicked: ev=" + event.getEventType() + ",count=" + event.getClickCount());
break;
}
}
/**
* Click handler for "clock" button.
*
* @param event mouse event
*/
@FXML
public void onClockClicked(MouseEvent event) {
log.info("Clock button clicked.");
PiClock.setScreen(getClass(), "clock", PiClock.getPrimaryStage().isFullScreen());
}
/**
* Click handler for "countdown" button.
*
* @param event mouse event
*/
@FXML
public void onCountdownClicked(MouseEvent event) {
log.info("Countdown button clicked. prompt=" + countdownDatePicker.getPromptText());
CountdownController.setTargetDate(countdownDatePicker.getConverter().fromString(countdownDatePicker.getPromptText()));
PiClock.setScreen(getClass(), "countdown", PiClock.getPrimaryStage().isFullScreen());
}
}
|
package com.backstage.web.controller.monitor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.backstage.common.core.controller.BaseController;
import com.backstage.framework.web.domain.Server;
/**
* 服务器监控
*
* @author jack.lin
*/
@Controller
@RequestMapping("/monitor/server")
public class ServerController extends BaseController
{
private String prefix = "monitor/server";
@RequiresPermissions("monitor:server:view")
@GetMapping()
public String server(ModelMap mmap) throws Exception
{
Server server = new Server();
server.copyTo();
mmap.put("server", server);
return prefix + "/server";
}
}
|
/*
* Copyright 2019 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.eva.server.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.ac.ebi.eva.server.models.ProgressReport;
import uk.ac.ebi.eva.server.repositories.ProgressReportRepository;
@RestController
@RequestMapping(value = "/v1/import-status", produces = "application/json")
public class DbsnpProgressReportRestController {
private ProgressReportRepository repository;
public DbsnpProgressReportRestController(ProgressReportRepository repository) {
this.repository = repository;
}
@GetMapping
public Iterable<ProgressReport> getReport() {
return repository.findAll();
}
}
|
package com.power.utils;
/**
* @author sunyu
*/
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DateTimeUtil {
private final static String[] WEEK_ARR = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
public static final String DATE_FORMAT_MINITE = "yyyy-MM-dd HH:mm";
public static final String DATE_FORMAT_DAY = "yyyy-MM-dd";
public static final String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT_CHINESE = "yyyy年MM月dd日";
public static final String DATE_FORMAT_CHINESE_SECONDE = "yyyy年MM月dd日 HH:mm:ss";
public static final String DATE_FORMAT_CHINESE_WEEK_SECONDE = "yyyy年MM月dd日 E HH:mm:ss";
/**
* Generation time, time format for yyyy-MM-dd hh:mm:ss
*
* @return yyyy-MM-dd hh:mm:ss
*/
public static String getStrTimeSecond() {
Date date = new Date();
return parseDateToStr(date, DATE_FORMAT_SECOND);
}
/**
* Formats a date using a format string
*
* @param date The date to format
* @param format The format string
* @return String
*/
public static String parseDateToStr(Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
public static String parseDateToStr(java.sql.Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
/**
* Generation time,time format for yyyy-MM-dd
*
* @return yyyy-MM-dd
*/
public static String getStrTimeDay() {
Date date = new Date();
return parseDateToStr(date, DATE_FORMAT_DAY);
}
/**
* Generation sqlDate
*
* @return sqlDate
*/
public static java.sql.Date getSqlDate() {
Date utilDate = new Date();
return new java.sql.Date(utilDate.getTime());
}
public static String sqlDateToStr(java.sql.Date date) {
return parseDateToStr(date, DATE_FORMAT_DAY);
}
public static java.sql.Date strToSqlDate(String date) {
Date utilDate = strToDate(date);
return new java.sql.Date(utilDate.getTime());
}
/**
* Parses a date using a specified format string
*
* @param sDate String
* @param format String
* @return Date
*/
public static Date parseDate(String sDate, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
try {
return simpleDateFormat.parse(sDate);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* converts string type to java.util.Date type
*
* @param date String
* @return java.util.Date
*/
public static Date strToDate(String date) {
return parseDate(date, DATE_FORMAT_DAY);
}
/**
* Converts java.util.Date type to string type
*
* @param date java.util.Date
* @return String
*/
public static String dateToStr(Date date) {
return parseDateToStr(date, DATE_FORMAT_DAY);
}
/**
* Generation timestamp
*
* @return java.sql.Timestamp
*/
public static Timestamp timeStamp() {
return new Timestamp(getNowTime());
}
/**
* format a string time like '2013-02-13' to '2013-02-13 00:00:00.0'
*
* @param date String
* @return java.sql.Timestamp
*/
public static Timestamp strToStamp(String date) {
Timestamp time = null;
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT_DAY);
try {
time = new Timestamp(df.parse(date).getTime());
} catch (Exception e) {
}
}
return time;
}
public static Timestamp getTimestampFromStr(String date) {
Timestamp time = null;
try {
time = Timestamp.valueOf(date);
} catch (IllegalArgumentException e) {
}
return time;
}
/**
* @return String
*/
public static String getTime() {
Date now = new Date();
return parseDateToStr(now, "yyyy-MM-dd HH:mm:ss");
}
/**
* input began time and end time calculate run time
*
* @param beginTime long
* @param endTime long
* @return double
*/
public static double calcRunTime(long beginTime, long endTime) {
return (endTime - beginTime) / 1000.00;
}
public static void printRunTime(long beganTime, long endTime) {
System.out.println("CostTime->" + (endTime - beganTime) / 1000.00
+ " Seconds");
}
/**
* obtain now time
*
* @return Long
*/
public static Long getNowTime() {
return System.currentTimeMillis();
}
/**
* @param before
* @param after
* @return
*/
public static long getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
/**
* 将timeStamp格式化为yyyy-MM-dd HH:mm:ss
*
* @param time java.sql.Timestamp
* @return String
*/
public static String formatTime(Timestamp time) {
return formatTime(time, DATE_FORMAT_SECOND);
}
/**
* via format TimeStamp to string
*
* @param time java.sql.Timestamp
* @param fmt String
* @return String
*/
public static String formatTime(Timestamp time, String fmt) {
SimpleDateFormat df = new SimpleDateFormat(fmt);
return df.format(time);
}
/**
* set time to next day's 0 hour 0 minute 0 second
*
* @param time java.sql.Timestamp
* @return long
*/
public static long setTimeToNextDay0H0M0S(Timestamp time) {
if (time != null) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time.getTime());
cal.add(Calendar.DATE, 1);
// 时、分、秒、毫秒置零
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// time.setTime(cal.getTimeInMillis());
return cal.getTimeInMillis();
} else {
throw new NullPointerException("Timestamp can not be null");
}
}
/**
* set time to next day's 0 hour 0 minute 0 second
*
* @param millis long
* @return long
*/
public static long setTimeToNextDay0H0M0S(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.add(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// time.setTime(cal.getTimeInMillis());
return cal.getTimeInMillis();
}
/**
* if the time is today return current milliseconds else set time to next
* day's 0 hour 0 minute 0 second then return except today
*
* @param millis long
* @return long
*/
public static long setToNextDay0H0M0SExceptToday(long millis) {
long finalTime;
boolean flag = isDifferentDay(System.currentTimeMillis(), millis);
if (flag) {
finalTime = setTimeToNextDay0H0M0S(millis);
} else {
finalTime = System.currentTimeMillis();
}
return finalTime;
}
/**
* if the time is today return current milliseconds else set time to next
* day's 0 hour 0 minute 0 second then return except today
*
* @param stamp java.sql.Timestamp
* @return long
*/
public static long setToNextDay0H0M0SExceptToday(Timestamp stamp) {
long finalTime;
if (stamp != null) {
boolean flag = isDifferentDay(timeStamp(), stamp);
if (flag) {
finalTime = setTimeToNextDay0H0M0S(stamp);
} else {
finalTime = System.currentTimeMillis();
}
} else {
throw new NullPointerException("Timestamp can not be null");
}
return finalTime;
}
/**
* set time to 0 hour 0 minute 0 second
*
* @param time java.sql.Timestamp
* @return long
*/
public static long setTimeTo0H0M0S(Timestamp time) {
if (time != null) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time.getTime());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// time.setTime(cal.getTimeInMillis());
return cal.getTimeInMillis();
} else {
throw new NullPointerException("Timestamp can not be null");
}
}
/**
* set time to 0 hour 0 minute 0 second
*
* @param millis long
* @return long
*/
public static long setTimeTo0H0M0S(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// time.setTime(cal.getTimeInMillis());
return cal.getTimeInMillis();
}
/**
* set time to last day's 0 hour 0 minute 0 second
*
* @param time java.sql.Timestamp
*/
public static void setTimeToLastDay0H0M0S(Timestamp time) {
if (time != null) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time.getTime());
cal.add(Calendar.DATE, -1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
time.setTime(cal.getTimeInMillis());
} else {
throw new NullPointerException("Timestamp can not be null");
}
}
/**
* 判断是否是同一天
*
* @param calendar1 Calendar
* @param calendar2 Calendar
* @return boolean
*/
public static boolean isDifferentDay(Calendar calendar1, Calendar calendar2) {
return (calendar1.get(Calendar.YEAR) != calendar2.get(Calendar.YEAR) || calendar1
.get(Calendar.DAY_OF_YEAR) != calendar2
.get(Calendar.DAY_OF_YEAR));
}
/**
* 判断是否是同一天
*
* @param timestamp0 java.sql.Timestamp
* @param timestamp1 java.sql.Timestamp
* @return boolean
*/
public static boolean isDifferentDay(Timestamp timestamp0, Timestamp timestamp1) {
if (timestamp0 == null || timestamp1 == null) {
throw new NullPointerException("Timestamp can not be null");
} else {
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timestamp0.getTime());
Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(timestamp1.getTime());
return isDifferentDay(cal1, cal2);
}
}
/**
* 判断是否是同一天
*
* @param millis0 long
* @param millis1 long
* @return boolean
*/
public static boolean isDifferentDay(long millis0, long millis1) {
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(millis0);
Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(millis1);
return isDifferentDay(cal1, cal2);
}
/**
* 将毫秒时间格式化为字符串时间(yyyy-MM-dd)
*
* @param millSec 毫秒数
* @return String
*/
public static String long2Str(Long millSec) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_CHINESE);
Date date = new Date(millSec);
return sdf.format(date);
}
/**
* 将毫秒时间格式化为指定格式的字符串时间
*
* @param millSec 毫秒
* @param format 需要格式的样式(yyyy-MM-dd等)
* @return String
*/
public static String long2Str(long millSec, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINESE);
Date date = new Date(millSec);
return sdf.format(date);
}
/**
* 将毫秒时间格式化为指定格式的字符串时间
*
* @param millSec 毫秒
* @param format 需要格式的样式(yyyy-MM-dd等)
* @param locale 语言地域
* @return
*/
public static String long2Str(long millSec, String format, Locale locale) {
SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
Date date = new Date(millSec);
return sdf.format(date);
}
/**
* transfer string to long
*
* @param dateFormat String
* @param strDate String
* @return long
*/
public static long strToLong(String dateFormat, String strDate) {
long temp;
if (isEmpty(strDate)) {
temp = 0;
} else {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
Date date = sdf.parse(strDate);
temp = date.getTime();
} catch (ParseException e) {
temp = 0;
}
}
return temp;
}
private static boolean isEmpty(String str) {
return null == str || "".equals(str.trim())
|| "null".equals(str.trim()) || "NaN".equals(str.trim());
}
/**
* 根据当天时间戳获取从0点起经过的毫秒数
*
* @param millions long
* @return long
*/
public static long todayPastMillisecond(long millions) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millions);
return cal.get(Calendar.HOUR_OF_DAY) * 3600 + cal.get(Calendar.MINUTE) * 60;
}
/**
* 获取本月天数
*
* @return int
*/
public static int getCurrentMonthDays() {
Calendar a = Calendar.getInstance();
a.set(Calendar.DATE, 1);// 把日期设置为当月第一天
a.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天
return a.get(Calendar.DATE);
}
/**
* 根据时间获得所属月的天数
*
* @param stamp java.sql.Timestamp
* @return int
*/
public static int getCurrentMonthDays(Timestamp stamp) {
if (null != stamp) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(stamp.getTime());
cal.set(Calendar.DATE, 1);// 把日期设置为当月第一天
cal.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天
int maxDate = cal.get(Calendar.DATE);
return maxDate;
} else {
throw new NullPointerException("Timestamp can not be null");
}
}
/**
* 根据当前时间获取所属周的第一天(0HOMOS) 根据中国习惯将星期一当做第一天
*
* @param stamp java.sql.Timestamp
* @return long
*/
public static long getFirstDayOfCurrentWeek(Timestamp stamp) {
if (null != stamp) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(stamp.getTime());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
// 如果是星期天,则设置为上周
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
cal.add(Calendar.WEEK_OF_YEAR, -1);
} else {
// 如果不是星期天,则设置为本周
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
}
return cal.getTimeInMillis();
} else {
throw new NullPointerException("Timestamp can not be null");
}
}
/**
* 根据时间获取所属周的第一天(0HOMOS) 根据中国习惯将星期一当做第一天
*
* @param ms long
* @return long
*/
public static long getFirstDayOfCurrentWeek(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
// 如果是星期天,则设置为上周
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
cal.add(Calendar.WEEK_OF_YEAR, -1);
} else {
// 如果不是星期天,则设置为本周
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
}
return cal.getTimeInMillis();
}
/**
* 将时间设置位当年第一天,并且将时分秒全部置0
*
* @param millis long
* @return long
*/
public static long setToFirstDayOfCurrentYear(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.set(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
/**
* 将时间设置为下一年的第一天
*
* @param millis long
* @return long
*/
public static long setToFirstDayOfNextYear(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.set(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.YEAR, 1);
return cal.getTimeInMillis();
}
public static long setToFirstDayOfLastMonth(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
/**
* 将时间重置为时间当前月的第一天,并且将时分秒全置0
*
* @param millis long
* @return long
*/
public static long setToFirstDayOfCurrentMonth(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
/**
* 将时间重置为下月的第一天,并将时分秒全置0
*
* @param millis long
* @return long
*/
public static long setToFirstDayOfNextMonth(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
/**
* 根据时间获取下一年的同一天
*
* @param millis long
* @return long
*/
public static long setToNextYearCommonDay(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
return cal.getTimeInMillis();
}
/**
* 根据时间获取所属周的最后一天(中国习惯)
*
* @param stamp java.sql.Timestamp
* @return long
*/
public static long getLastDayOfCurrentWeek(Timestamp stamp) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(stamp.getTime());
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.add(Calendar.WEEK_OF_YEAR, 1);
return cal.getTimeInMillis();
}
/**
* 根据时间的得到所对应季度的第一天(0H0M0S)
*
* @param ms 毫秒数
* @return long
*/
public static long getFirstDayOfCurrentQuarter(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
int currentMonth = cal.get(Calendar.MONTH) + 1;
if (currentMonth >= 1 && currentMonth <= 3) {
cal.set(Calendar.MONTH, 0);
} else if (currentMonth >= 4 && currentMonth <= 6) {
cal.set(Calendar.MONTH, 3);
} else if (currentMonth >= 7 && currentMonth <= 9) {
cal.set(Calendar.MONTH, 6);
} else if (currentMonth >= 10 && currentMonth <= 12) {
cal.set(Calendar.MONTH, 9);
}
cal.set(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
/**
* 根据时间获取下一个季度的第一天(0H0M0S)
*
* @param ms 毫秒数
* @return long
*/
public static long getFirstDayOfNextQuarter(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
int currentMonth = cal.get(Calendar.MONTH) + 1;
if (currentMonth >= 1 && currentMonth <= 3) {
cal.set(Calendar.MONTH, 2);
cal.set(Calendar.DATE, 31);
} else if (currentMonth >= 4 && currentMonth <= 6) {
cal.set(Calendar.MONTH, 5);
cal.set(Calendar.DATE, 30);
} else if (currentMonth >= 7 && currentMonth <= 9) {
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DATE, 30);
} else if (currentMonth >= 10 && currentMonth <= 12) {
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DATE, 31);
}
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis() + 86400000L;
}
/**
* 根据时间获取是周几(中国化)
*
* @param ms long
* @return int
*/
public static int getDayOfWeek(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
int a = cal.get(Calendar.DAY_OF_WEEK);
if (a >= 2) {
return a - 1;
} else {
return 7;
}
}
/**
* 创建一个时间并将时分秒都置0
*
* @return long
*/
public static long create0H0M0STime() {
return setTimeTo0H0M0S(System.currentTimeMillis());
}
/**
* 判断是否是今天
*
* @param ms 毫秒数
* @return boolean
*/
public static boolean isToday(long ms) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(ms);
return !isDifferentDay(cal1, cal2);
}
/**
* 将时间戳转换称友好的时间显示
*
* @param ms long
* @return String
*/
public static String friendlyTime(long ms) {
String ftime = "";
Calendar cal = Calendar.getInstance();
if (isDifferentDay(System.currentTimeMillis(), ms)) {
int hour = (int) ((cal.getTimeInMillis() - ms) / 3600000);
if (hour == 0) {
ftime = Math.max((cal.getTimeInMillis() - ms) / 60000, 1)
+ "分钟前";
} else {
ftime = hour + "小时前";
}
}
long lt = ms / 86400000;
long ct = cal.getTimeInMillis() / 86400000;
int days = (int) (ct - lt);
if (days == 0) {
int hour = (int) ((cal.getTimeInMillis() - ms) / 3600000);
if (hour == 0) {
ftime = Math.max((cal.getTimeInMillis() - ms) / 60000, 1)
+ "分钟前";
} else {
ftime = hour + "小时前";
}
} else if (days == 1) {
ftime = "昨天";
} else if (days == 2) {
ftime = "前天";
} else if (days > 2 && days <= 10) {
ftime = days + "天前";
} else if (days > 10) {
ftime = long2Str(ms);
}
return ftime;
}
public static int getWeeks(long startTime, long endTime) {
int temp = 0;
try {
temp = (int) ((endTime - startTime) / 86400000 / 7);
} catch (Exception ee) {
ee.printStackTrace();
}
return temp;
}
public static String getDateWithWeek(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
int a = cal.get(Calendar.DAY_OF_WEEK);
String[] weekARR = {"(周日)", "(周一)", "(周二)", "(周三)", "(周四)", "(周五)", "(周六)"};
return long2Str(ms, "MM月dd日" + weekARR[a - 1]);
}
public static String getDateWithWeekAndTime(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
int a = cal.get(Calendar.DAY_OF_WEEK);
return long2Str(ms, "yyyy年MM月dd日 " + WEEK_ARR[a - 1] + " HH:mm");
}
/**
* calc age
*
* @param ms long
* @return int
*/
public static int getAge(long ms) {
int age;
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
born.setTimeInMillis(ms);
if (born.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
age -= 1;
}
return age;
}
public static void main(String[] args) {
Date date = parseDate("yyyy-MM-dd", "2016-05-03");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.YEAR, -1);
String str = long2Str(calendar.getTimeInMillis(), "");
}
}
|
/*******************************************************************************
* Open Behavioral Health Information Technology Architecture (OBHITA.org)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package gov.samhsa.consent2share.pixclient.util;
public class PixManagerConstants {
public static final String PIX_ADD = "Add";
public static final String PIX_UPDATE = "Update";
public static final String PIX_QUERY = "Query";
public static final String ENCODE_STRING = "UTF-8";
public static String GLOBAL_DOMAIN_ID;
public static String GLOBAL_DOMAIN_NAME;
public PixManagerConstants(String globalDomainId, String globalDomainName)
{
PixManagerConstants.GLOBAL_DOMAIN_ID = globalDomainId;
PixManagerConstants.GLOBAL_DOMAIN_NAME = globalDomainName;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: common/common.proto
package ai.sensorycloud.api.common;
public interface CpuSummaryOrBuilder extends
// @@protoc_insertion_point(interface_extends:sensory.api.common.CpuSummary)
com.google.protobuf.MessageLiteOrBuilder {
/**
* <pre>
* normal processes executing in user mode
* </pre>
*
* <code>uint64 user = 1;</code>
* @return The user.
*/
long getUser();
/**
* <pre>
* niced processes executing in user mode
* </pre>
*
* <code>uint64 nice = 2;</code>
* @return The nice.
*/
long getNice();
/**
* <pre>
* processes executing in kernel mode
* </pre>
*
* <code>uint64 system = 3;</code>
* @return The system.
*/
long getSystem();
/**
* <pre>
* idle cpu
* </pre>
*
* <code>uint64 idle = 4;</code>
* @return The idle.
*/
long getIdle();
/**
* <pre>
* waiting for I/O to complete
* </pre>
*
* <code>uint64 ioWait = 5;</code>
* @return The ioWait.
*/
long getIoWait();
/**
* <pre>
* servicing interrupts
* </pre>
*
* <code>uint64 irq = 6;</code>
* @return The irq.
*/
long getIrq();
/**
* <pre>
* servicing softirqs
* </pre>
*
* <code>uint64 softIrq = 7;</code>
* @return The softIrq.
*/
long getSoftIrq();
/**
* <pre>
* counts the ticks spent executing other virtual hosts
* </pre>
*
* <code>uint64 steal = 8;</code>
* @return The steal.
*/
long getSteal();
/**
* <pre>
* counts the time spent running a virtual CPU for guest operating systems under the control of the Linux kernel
* </pre>
*
* <code>uint64 guest = 9;</code>
* @return The guest.
*/
long getGuest();
/**
* <pre>
* time spent running a niced guest
* </pre>
*
* <code>uint64 guestNice = 10;</code>
* @return The guestNice.
*/
long getGuestNice();
}
|
/*
*
* 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.qpid.server.exchange.topic;
import static org.apache.qpid.server.model.Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.apache.qpid.server.exchange.AbstractExchange;
import org.apache.qpid.server.filter.FilterManager;
import org.apache.qpid.server.filter.Filterable;
import org.apache.qpid.server.message.MessageDestination;
public class TopicExchangeResultTest
{
@Test
public void processMessageForUnfilteredDestinations()
{
final TopicExchangeResult result = new TopicExchangeResult();
final MessageDestination unfilteredDestination1 = mock(MessageDestination.class);
result.addUnfilteredDestination(unfilteredDestination1);
result.addBinding(new AbstractExchange.BindingIdentifier("key1", unfilteredDestination1),
Collections.emptyMap());
final MessageDestination unfilteredDestination2 = mock(MessageDestination.class);
result.addUnfilteredDestination(unfilteredDestination2);
result.addBinding(new AbstractExchange.BindingIdentifier("key2", unfilteredDestination2),
Collections.singletonMap(BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "replacement"));
final Filterable msg = mock(Filterable.class);
final Map<MessageDestination, Set<String>> matches = new HashMap<>();
result.processMessage(msg, matches, "test");
assertTrue("Unfiltered destination is not found ", matches.containsKey(unfilteredDestination1));
assertEquals(Collections.singleton("test"), matches.get(unfilteredDestination1));
assertTrue("Replacement key destination is not found ", matches.containsKey(unfilteredDestination2));
assertEquals(Collections.singleton("replacement"), matches.get(unfilteredDestination2));
}
@Test
public void processMessageForFilteredDestinations()
{
final TopicExchangeResult result = new TopicExchangeResult();
final MessageDestination matchingFilteredDestination = mock(MessageDestination.class);
final FilterManager matchingFilter = mock(FilterManager.class);
result.addFilteredDestination(matchingFilteredDestination, matchingFilter);
result.addBinding(new AbstractExchange.BindingIdentifier("key1", matchingFilteredDestination),
Collections.emptyMap());
result.addBinding(new AbstractExchange.BindingIdentifier("key3", matchingFilteredDestination),
Collections.singletonMap(BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "replacement"));
final MessageDestination notMatchingFilteredDestination = mock(MessageDestination.class);
final FilterManager nonMatchingFilter = mock(FilterManager.class);
result.addFilteredDestination(notMatchingFilteredDestination, nonMatchingFilter);
result.addBinding(new AbstractExchange.BindingIdentifier("key2", notMatchingFilteredDestination),
Collections.emptyMap());
final Filterable msg = mock(Filterable.class);
when(matchingFilter.allAllow(msg)).thenReturn(true);
when(nonMatchingFilter.allAllow(msg)).thenReturn(false);
final Map<MessageDestination, Set<String>> matches = new HashMap<>();
result.processMessage(msg, matches, "test");
assertTrue("Matched destination is not found ", matches.containsKey(matchingFilteredDestination));
assertEquals(Collections.singleton("replacement"), matches.get(matchingFilteredDestination));
assertFalse("Unfiltered destination is not found ", matches.containsKey(notMatchingFilteredDestination));
}
}
|
/**
* Copyright (c) 2012, University of Konstanz, Distributed Systems Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Konstanz nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.perfidix.perclipse.views;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.eclipse.swt.graphics.Point;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.perfidix.perclipse.launcher.PerclipseActivator;
import org.perfidix.perclipse.util.TestUtilClass;
/**
* This class tests the java class
* {@link org.perfidix.Perclipse.view.PerfidixProgressBar}.
*
* @author Lewandowski Lukas, DiSy, University of Konstanz
*/
public class PerfidixProgressBarTest {
private transient PerfidixProgressBar progressBar;
private transient TestUtilClass utilClass;
/**
* Simple setUp - method.
*
* @throws java.lang.Exception
* The Exception occurred.
*/
@Before
public void setUp() throws Exception {
utilClass = new TestUtilClass();
utilClass.setViewForTesting();
final BenchView view = PerclipseActivator.getDefault().getBenchView();
progressBar = view.getProgressBar();
}
/**
* Simple tearDown - method.
*
* @throws java.lang.Exception
* The Exception occurred.
*/
@After
public void tearDown() throws Exception {
utilClass.setViewNull();
// utilClass = null;
// progressBar = null;
// view = null;
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#PerfidixProgressBar(org.eclipse.swt.widgets.Composite)}
* .
*/
@Test
public void testPerfidixProgressBar() {
assertNotNull("Test if progress bar is not null", progressBar);
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#setMaximum(int)}.
*/
@Test
public void testSetMaximum() { // NOPMD by lewandow on 8/31/09 4:24 PM
progressBar.setMaximum(2555);
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#reset()}.
*/
@Test
public void testReset() { // NOPMD by lewandow on 8/31/09 4:24 PM
progressBar.reset();
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#reset(boolean, boolean, int, int)}
* .
*/
@Test
public void testResetBooleanBooleanIntInt() { // NOPMD by lewandow on
// 8/31/09 4:24 PM
progressBar.reset(true, false, 50, 100);
progressBar.reset(false, false, 33, 12);
progressBar.reset(false, true, 99, 99);
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#stopped()}.
*/
@Test
public void testStopped() { // NOPMD by lewandow on 8/31/09 4:24 PM
progressBar.stopped();
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#computeSize(int, int, boolean)}
* .
*/
@Test
public void testComputeSizeIntIntBoolean() {
final Point point = new Point(22, 55);
assertEquals(
"Test if a created point is equals to the progress bar point",
point, progressBar.computeSize(22, 55, true));
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#step(int)}.
*/
@Test
public void testStep() { // NOPMD by lewandow on 8/31/09 4:24 PM
progressBar.step(22);
progressBar.reset(true, true, 55, 55);
progressBar.step(22);
progressBar.reset(true, true, 54, 55);
progressBar.step(22);
}
/**
* Test method for
* {@link org.perfidix.perclipse.views.PerfidixProgressBar#refresh(boolean)}
* .
*/
@Test
public void testRefresh() { // NOPMD by lewandow on 8/31/09 4:24 PM
progressBar.refresh(true);
progressBar.refresh(false);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.binary;
import org.apache.ignite.binary.BinaryBasicIdMapper;
import org.apache.ignite.binary.BinaryBasicNameMapper;
import org.apache.ignite.configuration.BinaryConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
/**
* Binary builder test.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public class BinaryObjectBuilderSimpleNameLowerCaseMappersSelfTest extends BinaryObjectBuilderDefaultMappersSelfTest {
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
BinaryConfiguration bCfg = cfg.getBinaryConfiguration();
bCfg.setIdMapper(new BinaryBasicIdMapper(true));
bCfg.setNameMapper(new BinaryBasicNameMapper(true));
return cfg;
}
}
|
/*
* 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.dao.mapper;
import org.apache.dolphinscheduler.common.enums.FailureStrategy;
import org.apache.dolphinscheduler.common.enums.ReleaseState;
import org.apache.dolphinscheduler.common.enums.WarningType;
import org.apache.dolphinscheduler.dao.entity.ProcessDefinition;
import org.apache.dolphinscheduler.dao.entity.Project;
import org.apache.dolphinscheduler.dao.entity.Schedule;
import org.apache.dolphinscheduler.dao.entity.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@Rollback(true)
public class ScheduleMapperTest {
@Autowired
ScheduleMapper scheduleMapper;
@Autowired
UserMapper userMapper;
@Autowired
ProjectMapper projectMapper;
@Autowired
ProcessDefinitionMapper processDefinitionMapper;
/**
* insert
* @return Schedule
*/
private Schedule insertOne(){
//insertOne
Schedule schedule = new Schedule();
schedule.setStartTime(new Date());
schedule.setEndTime(new Date());
schedule.setCrontab("");
schedule.setFailureStrategy(FailureStrategy.CONTINUE);
schedule.setReleaseState(ReleaseState.OFFLINE);
schedule.setWarningType(WarningType.NONE);
schedule.setCreateTime(new Date());
schedule.setUpdateTime(new Date());
scheduleMapper.insert(schedule);
return schedule;
}
/**
* test update
*/
@Test
public void testUpdate(){
//insertOne
Schedule schedule = insertOne();
schedule.setCreateTime(new Date());
//update
int update = scheduleMapper.updateById(schedule);
Assert.assertEquals(update, 1);
scheduleMapper.deleteById(schedule.getId());
}
/**
* test delete
*/
@Test
public void testDelete(){
Schedule schedule = insertOne();
int delete = scheduleMapper.deleteById(schedule.getId());
Assert.assertEquals(delete, 1);
}
/**
* test query
*/
@Test
public void testQuery() {
Schedule schedule = insertOne();
//query
List<Schedule> schedules = scheduleMapper.selectList(null);
Assert.assertNotEquals(schedules.size(), 0);
scheduleMapper.deleteById(schedule.getId());
}
/**
* test page
*/
@Test
public void testQueryByProcessDefineIdPaging() {
User user = new User();
user.setUserName("ut name");
userMapper.insert(user);
Project project = new Project();
project.setName("ut project");
project.setUserId(user.getId());
projectMapper.insert(project);
ProcessDefinition processDefinition = new ProcessDefinition();
processDefinition.setProjectId(project.getId());
processDefinition.setUserId(user.getId());
processDefinition.setLocations("");
processDefinitionMapper.insert(processDefinition);
Schedule schedule= insertOne();
schedule.setUserId(user.getId());
schedule.setProcessDefinitionId(processDefinition.getId());
scheduleMapper.insert(schedule);
Page<Schedule> page = new Page(1,3);
IPage<Schedule> scheduleIPage = scheduleMapper.queryByProcessDefineIdPaging(page,
processDefinition.getId(), ""
);
Assert.assertNotEquals(scheduleIPage.getSize(), 0);
projectMapper.deleteById(project.getId());
processDefinitionMapper.deleteById(processDefinition.getId());
userMapper.deleteById(user.getId());
scheduleMapper.deleteById(schedule.getId());
}
/**
* test query schedule list by project name
*/
@Test
public void testQuerySchedulerListByProjectName() {
User user = new User();
user.setUserName("ut name");
userMapper.insert(user);
Project project = new Project();
project.setName("ut project");
project.setUserId(user.getId());
projectMapper.insert(project);
ProcessDefinition processDefinition = new ProcessDefinition();
processDefinition.setProjectId(project.getId());
processDefinition.setUserId(user.getId());
processDefinition.setLocations("");
processDefinitionMapper.insert(processDefinition);
Schedule schedule= insertOne();
schedule.setUserId(user.getId());
schedule.setProcessDefinitionId(processDefinition.getId());
scheduleMapper.insert(schedule);
Page<Schedule> page = new Page(1,3);
List<Schedule> schedules = scheduleMapper.querySchedulerListByProjectName(
project.getName()
);
projectMapper.deleteById(project.getId());
processDefinitionMapper.deleteById(processDefinition.getId());
userMapper.deleteById(user.getId());
scheduleMapper.deleteById(schedule.getId());
Assert.assertNotEquals(schedules.size(), 0);
}
/**
* test query by process definition ids
*/
@Test
public void testSelectAllByProcessDefineArray() {
Schedule schedule = insertOne();
schedule.setProcessDefinitionId(12345);
schedule.setReleaseState(ReleaseState.ONLINE);
scheduleMapper.updateById(schedule);
List<Schedule> schedules= scheduleMapper.selectAllByProcessDefineArray(new int[] {schedule.getProcessDefinitionId()});
scheduleMapper.deleteById(schedule.getId());
Assert.assertNotEquals(schedules.size(), 0);
}
/**
* test query by process definition id
*/
@Test
public void queryByProcessDefinitionId() {
Schedule schedule = insertOne();
schedule.setProcessDefinitionId(12345);
scheduleMapper.updateById(schedule);
List<Schedule> schedules= scheduleMapper.queryByProcessDefinitionId(schedule.getProcessDefinitionId());
scheduleMapper.deleteById(schedule.getId());
Assert.assertNotEquals(schedules.size(), 0);
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
/**
* Package containing the inner data models for SearchManagementClient. Client that can be used to manage Azure
* Cognitive Search services and API keys.
*/
package com.azure.resourcemanager.search.fluent.models;
|
package com.github.neuralnetworks.samples.server.cifar;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.amd.aparapi.Kernel.EXECUTION_MODE;
import com.github.neuralnetworks.architecture.WeightsConnections;
import com.github.neuralnetworks.builder.NeuralNetworkBuilder;
import com.github.neuralnetworks.builder.activation.ActivationType;
import com.github.neuralnetworks.builder.activation.TransferFunctionType;
import com.github.neuralnetworks.builder.layer.ConvolutionalLayerBuilder;
import com.github.neuralnetworks.builder.layer.FullyConnectedLayerBuilder;
import com.github.neuralnetworks.builder.layer.InputLayerBuilder;
import com.github.neuralnetworks.builder.layer.PoolingLayerBuilder;
import com.github.neuralnetworks.events.TrainingEvent;
import com.github.neuralnetworks.input.SimpleFileInputProvider;
import com.github.neuralnetworks.samples.server.JUnitOnServerStarter;
import com.github.neuralnetworks.training.Hyperparameters;
import com.github.neuralnetworks.training.Trainer;
import com.github.neuralnetworks.training.TrainingInputProvider;
import com.github.neuralnetworks.training.backpropagation.BackPropagationTrainer;
import com.github.neuralnetworks.training.events.EpochFinishedEvent;
import com.github.neuralnetworks.training.events.LogTrainingListener;
import com.github.neuralnetworks.training.events.ValidationListener;
import com.github.neuralnetworks.training.random.GaussianRandomInitializerImpl;
import com.github.neuralnetworks.training.random.RandomInitializerImpl;
import com.github.neuralnetworks.util.RuntimeConfiguration;
import com.github.neuralnetworks.util.RuntimeConfiguration.CalculationProvider;
/**
* @author Urko
*/
public class CifarCaffeConf2 extends JUnitOnServerStarter {
@Override
public List<RuntimeConfiguration[]> runtimeConfigurations() {
List<RuntimeConfiguration[]> configurations = new ArrayList<>();
// RuntimeConfiguration conf1 = new RuntimeConfiguration();
// conf1.getAparapiConfiguration().setExecutionMode(EXECUTION_MODE.CPU);
// conf1.setUseDataSharedMemory(false);
// conf1.setUseWeightsSharedMemory(false);
// configurations.add(new RuntimeConfiguration[] { conf1 });
RuntimeConfiguration conf3 = new RuntimeConfiguration();
conf3.setCalculationProvider(CalculationProvider.OPENCL);
conf3.setUseDataSharedMemory(false);
conf3.setUseWeightsSharedMemory(false);
conf3.getOpenCLConfiguration().setAggregateOperations(true);
conf3.getOpenCLConfiguration().setSynchronizeAfterOpertation(false);
conf3.getOpenCLConfiguration().setPushToDeviceBeforeOperation(false);
conf3.getOpenCLConfiguration().setFinalyzeDeviceAfterPhase(true);
conf3.getAparapiConfiguration().setExecutionMode(EXECUTION_MODE.SEQ);
configurations.add(new RuntimeConfiguration[] { conf3 });
return configurations;
}
@Override
public void jUnitTest(int epochs, String folder) {
NeuralNetworkBuilder builder = new NeuralNetworkBuilder();
Random r = new Random();
long seed = r.nextLong();
// network
{
builder.addLayerBuilder(new InputLayerBuilder("inputLayer", 32, 32, 3));
// conv
{
ConvolutionalLayerBuilder convolutionalLayerBuilder = new ConvolutionalLayerBuilder(5, 32);
convolutionalLayerBuilder.setPaddingSize(2);
convolutionalLayerBuilder.setStrideSize(1);
// convolutionalLayerBuilder.setWeightInitializer(new RandomInitializerImpl(r,
// 0f, 0.0001f));
convolutionalLayerBuilder.setWeightInitializer(new GaussianRandomInitializerImpl(r, seed, 0, 0.01f,
1 / Math.sqrt(6 * (3 * 5 * 5 + 32 * 5 * 5))));
convolutionalLayerBuilder.setLearningRate(0.01f);
convolutionalLayerBuilder.setMomentum(0.9f);
// convolutionalLayerBuilder.setL1weightDecay(0.01f);
convolutionalLayerBuilder.setBiasLearningRate(0.01f);
convolutionalLayerBuilder.setBiasMomentum(0.9f);
convolutionalLayerBuilder.setActivationType(ActivationType.Nothing);
builder.addLayerBuilder(convolutionalLayerBuilder);
PoolingLayerBuilder poolingLayerBuilder = new PoolingLayerBuilder(3);
poolingLayerBuilder.setTransferFunctionType(TransferFunctionType.Max_Polling2D);
poolingLayerBuilder.setActivationType(ActivationType.ReLU);
poolingLayerBuilder.setStrideSize(2);
builder.addLayerBuilder(poolingLayerBuilder);
}
// conv
{
ConvolutionalLayerBuilder convolutionalLayerBuilder = new ConvolutionalLayerBuilder(5, 32);
convolutionalLayerBuilder.setPaddingSize(2);
convolutionalLayerBuilder.setStrideSize(1);
// convolutionalLayerBuilder.setWeightInitializer(new RandomInitializerImpl(r,
// 0f, 0.01f));
convolutionalLayerBuilder.setWeightInitializer(new GaussianRandomInitializerImpl(r, seed, 0, 0.01f,
1 / Math.sqrt(6 * (32 * 5 * 5 + 32 * 5 * 5))));
convolutionalLayerBuilder.setLearningRate(0.01f);
convolutionalLayerBuilder.setMomentum(0.9f);
// convolutionalLayerBuilder.setL1weightDecay(0.01f);
convolutionalLayerBuilder.setBiasLearningRate(0.01f);
convolutionalLayerBuilder.setBiasMomentum(0.9f);
convolutionalLayerBuilder.setActivationType(ActivationType.ReLU);
builder.addLayerBuilder(convolutionalLayerBuilder);
PoolingLayerBuilder poolingLayerBuilder = new PoolingLayerBuilder(3);
poolingLayerBuilder.setTransferFunctionType(TransferFunctionType.Max_Polling2D);
poolingLayerBuilder.setActivationType(ActivationType.Nothing);
poolingLayerBuilder.setStrideSize(2);
builder.addLayerBuilder(poolingLayerBuilder);
}
// conv
{
ConvolutionalLayerBuilder convolutionalLayerBuilder = new ConvolutionalLayerBuilder(5, 64);
convolutionalLayerBuilder.setPaddingSize(2);
convolutionalLayerBuilder.setStrideSize(1);
// convolutionalLayerBuilder.setWeightInitializer(new RandomInitializerImpl(r,
// 0f, 0.01f));
convolutionalLayerBuilder.setWeightInitializer(new GaussianRandomInitializerImpl(r, seed, 0, 0.01f,
1 / Math.sqrt(6 * (32 * 5 * 5 + 64 * 5 * 5))));
convolutionalLayerBuilder.setLearningRate(0.01f);
convolutionalLayerBuilder.setMomentum(0.9f);
convolutionalLayerBuilder.setBiasLearningRate(0.01f);
convolutionalLayerBuilder.setBiasMomentum(0.9f);
convolutionalLayerBuilder.setActivationType(ActivationType.ReLU);
builder.addLayerBuilder(convolutionalLayerBuilder);
PoolingLayerBuilder poolingLayerBuilder = new PoolingLayerBuilder(3);
poolingLayerBuilder.setTransferFunctionType(TransferFunctionType.Max_Polling2D);
poolingLayerBuilder.setActivationType(ActivationType.Nothing);
poolingLayerBuilder.setStrideSize(2);
builder.addLayerBuilder(poolingLayerBuilder);
}
// fc
{
FullyConnectedLayerBuilder fullyConnectedLayerBuilder = new FullyConnectedLayerBuilder(64);
// fullyConnectedLayerBuilder.setWeightInitializer(new RandomInitializerImpl(r,
// 0f, 0.0001f));
fullyConnectedLayerBuilder.setWeightInitializer(
new GaussianRandomInitializerImpl(r, seed, 0, 0.01f, 1 / Math.sqrt(6 * (64 * 5 * 5 + 64))));
fullyConnectedLayerBuilder.setLearningRate(0.05f);
fullyConnectedLayerBuilder.setMomentum(0.9f);
fullyConnectedLayerBuilder.setBiasLearningRate(0.05f);
fullyConnectedLayerBuilder.setBiasMomentum(0.9f);
fullyConnectedLayerBuilder.setActivationType(ActivationType.Nothing);
builder.addLayerBuilder(fullyConnectedLayerBuilder);
}
// fc
{
FullyConnectedLayerBuilder fullyConnectedLayerBuilder = new FullyConnectedLayerBuilder(10);
fullyConnectedLayerBuilder.setWeightInitializer(new RandomInitializerImpl(r, 0f, 0.0001f));
fullyConnectedLayerBuilder.setWeightInitializer(
new GaussianRandomInitializerImpl(r, seed, 0, 0.01f, 1 / Math.sqrt(6 * (64 + 10))));
// fullyConnectedLayerBuilder.setLearningRate(0.05f);
fullyConnectedLayerBuilder.setMomentum(0.9f);
fullyConnectedLayerBuilder.setBiasLearningRate(0.05f);
fullyConnectedLayerBuilder.setBiasMomentum(0.9f);
fullyConnectedLayerBuilder.setActivationType(ActivationType.SoftMax);
builder.addLayerBuilder(fullyConnectedLayerBuilder);
}
// trainer
{
TrainingInputProvider trainInputProvider = new SimpleFileInputProvider(
"cifar-10-batches-bin/train-data.float", "cifar-10-batches-bin/train-labels.float", 32 * 32, 10,
50000);
TrainingInputProvider testInputProvider = new SimpleFileInputProvider(
"cifar-10-batches-bin/test-data.float", "cifar-10-batches-bin/test-labels.float", 32 * 32, 10,
10000);
builder.setTrainingSet(trainInputProvider);
builder.setTestingSet(testInputProvider);
builder.setEpochs(epochs);
builder.setTrainingBatchSize(100);
builder.setTestBatchSize(100);
}
}
BackPropagationTrainer<?> bpt = (BackPropagationTrainer<?>) builder.buildWithTrainer().getRight();
// log data
LogTrainingListener ls = new LogTrainingListener(Thread.currentThread().getStackTrace()[1].getMethodName(),
false, true);
ls.setLogBatchLoss(true);
// ls.setLogWeightUpdates(true);
ls.setLogInterval(5000);
bpt.addEventListener(ls);
bpt.addEventListener(new ValidationListener(new SimpleFileInputProvider("cifar-10-batches-bin/train-data.float",
"cifar-10-batches-bin/train-labels.float", 32 * 32, 10, 10000)) {
private static final long serialVersionUID = 1L;
private int epoch;
@Override
public void handleEvent(TrainingEvent event) {
super.handleEvent(event);
if (event instanceof EpochFinishedEvent) {
epoch++;
// if (prevPrevError != 0 && prevPrevError - prevError < 0.003)
if (epoch % 8 == 0) {
System.out.println("Change hyperparameters");
Trainer<?> t = (Trainer<?>) event.getSource();
Hyperparameters hp = t.getHyperparameters();
t.getNeuralNetwork().getConnections().stream()
.filter(c -> c instanceof WeightsConnections && hp.getLearningRate(c) > 0.00001f)
.forEach(c -> {
hp.setLearningRate(c, hp.getLearningRate(c) / 10);
});
}
}
}
});
// training
bpt.train();
// testing
bpt.test();
if (bpt.getOutputError().getTotalNetworkError() > 0.1) {
throw new IllegalStateException(
"error was to high! " + bpt.getOutputError().getTotalNetworkError() + " > 0.1");
}
}
public static void main(String[] args) {
JUnitOnServerStarter jUnitOnServerStarter = new CifarCaffeConf2();
jUnitOnServerStarter.startTestFromCommandLine(args);
}
}
|
/**
* Copyright 2019 Anthony Trinh
*
* 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 ch.qos.logback.classic.pattern;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import ch.qos.logback.core.testUtil.RandomUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.MDC;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
public class MDCConverterTest {
LoggerContext lc;
MDCConverter converter;
int diff = RandomUtil.getPositiveInt();
@Before
public void setUp() throws Exception {
lc = new LoggerContext();
converter = new MDCConverter();
converter.start();
MDC.clear();
}
@After
public void tearDown() throws Exception {
lc = null;
converter.stop();
converter = null;
MDC.clear();
}
@Test
public void testConvertWithOneEntry() {
String k = "MDCConverterTest_k"+diff;
String v = "MDCConverterTest_v"+diff;
MDC.put(k, v);
ILoggingEvent le = createLoggingEvent();
String result = converter.convert(le);
assertEquals(k+"="+v, result);
}
@Test
public void testConvertWithMultipleEntries() {
MDC.put("testKey", "testValue");
MDC.put("testKey2", "testValue2");
ILoggingEvent le = createLoggingEvent();
String result = converter.convert(le);
boolean isConform = result.matches("testKey2?=testValue2?, testKey2?=testValue2?");
assertTrue(result + " is not conform", isConform);
}
private ILoggingEvent createLoggingEvent() {
return new LoggingEvent(this.getClass().getName(), lc
.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", null,
null);
}
}
|
package org.jutility.events;
/*
* #%L
* jutility-incubation
* %%
* Copyright (C) 2013 - 2014 jutility.org
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.EventObject;
/**
* The <CODE>CollectionChangeEvent</CODE> class provides a reference
* implementation of the <CODE>ICollectionChangeEvent</CODE> interface.
*
* @author Peter J. Radics
* @version 1.0
*
* @see ICollectionChangeEvent
* @see EventObject
*/
public class CollectionChangeEvent
extends EventObject
implements ICollectionChangeEvent {
private static final long serialVersionUID = 1L;
private final String collectionName;
private final Object causeOfChange;
private final CollectionChangeOperation operation;
@Override
public String getCollectionName() {
return this.collectionName;
}
@Override
public Object getCauseOfChange() {
return this.causeOfChange;
}
@Override
public CollectionChangeOperation getOperation() {
return this.operation;
}
/**
* Constructs a new <CODE>CollectionChangeEvent</CODE> with the provided
* collection name, source, and cause of change. The operation, however, is
* unknown.
*
* @param collectionName
* The collection name.
* @param source
* The source of the change.
* @param causeOfChange
* The cause of the change.
*/
public CollectionChangeEvent(Object source, String collectionName,
Object causeOfChange) {
this(source, collectionName, causeOfChange,
CollectionChangeOperation.UNKNOWN);
}
/**
* Constructs a new <CODE>CollectionChangeEvent</CODE> with the provided
* collection name, source,cause of change, and operation.
*
* @param source
* The source of the change.
* @param collectionName
* The collection name.
* @param causeOfChange
* The cause of the change.
* @param operation
* The operation.
*/
public CollectionChangeEvent(Object source, String collectionName,
Object causeOfChange, CollectionChangeOperation operation) {
super(source);
this.collectionName = collectionName;
this.causeOfChange = causeOfChange;
this.operation = operation;
}
/**
* Provides a String representation of the event.
*
* @return a string representation of the event.
*/
@Override
public String toString() {
String returnValue = super.toString();
if (this.source != null) {
returnValue = "From: <" + this.source.toString() + ">\n";
if (this.collectionName != null) {
returnValue += "\tTo: " + this.collectionName + "\n";
}
if (this.operation != null) {
returnValue += "\tOperation: " + this.operation.toString()
+ "\n";
}
if (this.causeOfChange != null) {
returnValue += "\tElement: " + this.causeOfChange.toString()
+ "\n";
}
}
return returnValue;
}
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2021 iText Group NV
Authors: iText Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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 <https://www.gnu.org/licenses/>.
*/
package com.itextpdf.styledxmlparser.jsoup.parser;
import com.itextpdf.commons.utils.MessageFormatUtil;
import com.itextpdf.styledxmlparser.jsoup.Jsoup;
import com.itextpdf.styledxmlparser.jsoup.TextUtil;
import com.itextpdf.styledxmlparser.jsoup.nodes.Comment;
import com.itextpdf.styledxmlparser.jsoup.nodes.Document;
import com.itextpdf.styledxmlparser.jsoup.nodes.Element;
import com.itextpdf.styledxmlparser.jsoup.nodes.TextNode;
import com.itextpdf.styledxmlparser.jsoup.select.Elements;
import com.itextpdf.test.ExtendedITextTest;
import com.itextpdf.test.annotations.type.UnitTest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Arrays;
@Category(UnitTest.class)
public class TokeniserStateTest extends ExtendedITextTest {
final char[] whiteSpace = { '\t', '\n', '\r', '\f', ' ' };
final char[] quote = { '\'', '"' };
@Test
public void ensureSearchArraysAreSorted() {
char[][] arrays = {
TokeniserState.attributeNameCharsSorted,
TokeniserState.attributeValueUnquoted
};
for (char[] array : arrays) {
char[] copy = Arrays.copyOf(array, array.length);
Arrays.sort(array);
Assert.assertArrayEquals(array, copy);
}
}
@Test
public void testCharacterReferenceInRcdata() {
String body = "<textarea>You&I</textarea>";
Document doc = Jsoup.parse(body);
Elements els = doc.select("textarea");
Assert.assertEquals("You&I", els.text());
}
@Test
public void testBeforeTagName() {
for (char c : whiteSpace) {
String body = MessageFormatUtil.format("<div{0}>test</div>", c);
Document doc = Jsoup.parse(body);
Elements els = doc.select("div");
Assert.assertEquals("test", els.text());
}
}
@Test
public void testEndTagOpen() {
String body;
Document doc;
Elements els;
body = "<div>hello world</";
doc = Jsoup.parse(body);
els = doc.select("div");
Assert.assertEquals("hello world</", els.text());
body = "<div>hello world</div>";
doc = Jsoup.parse(body);
els = doc.select("div");
Assert.assertEquals("hello world", els.text());
body = "<div>fake</></div>";
doc = Jsoup.parse(body);
els = doc.select("div");
Assert.assertEquals("fake", els.text());
body = "<div>fake</?</div>";
doc = Jsoup.parse(body);
els = doc.select("div");
Assert.assertEquals("fake", els.text());
}
@Test
public void testRcdataLessthanSign() {
String body;
Document doc;
Elements els;
body = "<textarea><fake></textarea>";
doc = Jsoup.parse(body);
els = doc.select("textarea");
Assert.assertEquals("<fake>", els.text());
body = "<textarea><open";
doc = Jsoup.parse(body);
els = doc.select("textarea");
Assert.assertEquals("", els.text());
body = "<textarea>hello world</?fake</textarea>";
doc = Jsoup.parse(body);
els = doc.select("textarea");
Assert.assertEquals("hello world</?fake", els.text());
}
@Test
public void testRCDATAEndTagName() {
for (char c : whiteSpace) {
String body = MessageFormatUtil.format("<textarea>data</textarea{0}>", c);
Document doc = Jsoup.parse(body);
Elements els = doc.select("textarea");
Assert.assertEquals("data", els.text());
}
}
@Test
public void testCommentEndCoverage() {
String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --! --- --><p>Hello</p></body></html>";
Document doc = Jsoup.parse(html);
Element body = doc.body();
Comment comment = (Comment) body.childNode(1);
Assert.assertEquals(" <table><tr><td></table> --! --- ", comment.getData());
Element p = body.child(1);
TextNode text = (TextNode) p.childNode(0);
Assert.assertEquals("Hello", text.getWholeText());
}
@Test
public void testCommentEndBangCoverage() {
String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --!---!>--><p>Hello</p></body></html>";
Document doc = Jsoup.parse(html);
Element body = doc.body();
Comment comment = (Comment) body.childNode(1);
Assert.assertEquals(" <table><tr><td></table> --!-", comment.getData());
Element p = body.child(1);
TextNode text = (TextNode) p.childNode(0);
Assert.assertEquals("Hello", text.getWholeText());
}
@Test
public void testPublicIdentifiersWithWhitespace() {
String expectedOutput = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0//EN\">";
for (char q : quote) {
for (char ws : whiteSpace) {
String[] htmls = {
MessageFormatUtil.format("<!DOCTYPE html{0}PUBLIC {1}-//W3C//DTD HTML 4.0//EN{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html {0}PUBLIC {1}-//W3C//DTD HTML 4.0//EN{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html PUBLIC{0}{1}-//W3C//DTD HTML 4.0//EN{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html PUBLIC {0}{1}-//W3C//DTD HTML 4.0//EN{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html PUBLIC {0}-//W3C//DTD HTML 4.0//EN{1}{2}>", q, q, ws),
MessageFormatUtil.format("<!DOCTYPE html PUBLIC{0}-//W3C//DTD HTML 4.0//EN{1}{2}>", q, q, ws)
};
for (String html : htmls) {
Document doc = Jsoup.parse(html);
Assert.assertEquals(expectedOutput, doc.childNode(0).outerHtml());
}
}
}
}
@Test
public void testSystemIdentifiersWithWhitespace() {
String expectedOutput = "<!DOCTYPE html SYSTEM \"http://www.w3.org/TR/REC-html40/strict.dtd\">";
for (char q : quote) {
for (char ws : whiteSpace) {
String[] htmls = {
MessageFormatUtil.format("<!DOCTYPE html{0}SYSTEM {1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html {0}SYSTEM {1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html SYSTEM{0}{1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html SYSTEM {0}{1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>", ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html SYSTEM {0}http://www.w3.org/TR/REC-html40/strict.dtd{1}{2}>", q, q, ws),
MessageFormatUtil.format("<!DOCTYPE html SYSTEM{0}http://www.w3.org/TR/REC-html40/strict.dtd{1}{2}>", q, q, ws)
};
for (String html : htmls) {
Document doc = Jsoup.parse(html);
Assert.assertEquals(expectedOutput, doc.childNode(0).outerHtml());
}
}
}
}
@Test
public void testPublicAndSystemIdentifiersWithWhitespace() {
String expectedOutput = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0//EN\""
+ " \"http://www.w3.org/TR/REC-html40/strict.dtd\">";
for (char q : quote) {
for (char ws : whiteSpace) {
String[] htmls = {
MessageFormatUtil.format("<!DOCTYPE html PUBLIC {0}-//W3C//DTD HTML 4.0//EN{1}"
+ "{2}{3}http://www.w3.org/TR/REC-html40/strict.dtd{4}>", q, q, ws, q, q),
MessageFormatUtil.format("<!DOCTYPE html PUBLIC {0}-//W3C//DTD HTML 4.0//EN{1}"
+ "{2}http://www.w3.org/TR/REC-html40/strict.dtd{3}>", q, q, q, q)
};
for (String html : htmls) {
Document doc = Jsoup.parse(html);
Assert.assertEquals(expectedOutput, doc.childNode(0).outerHtml());
}
}
}
}
@Test public void handlesLessInTagThanAsNewTag() {
// out of spec, but clear author intent
String html = "<p\n<p<div id=one <span>Two";
Document doc = Jsoup.parse(html);
Assert.assertEquals("<p></p><p></p><div id=\"one\"><span>Two</span></div>", TextUtil.stripNewlines(doc.body().html()));
}
@Test
public void testUnconsumeAtBufferBoundary() {
String triggeringSnippet = "<a href=\"\"foo";
char[] padding = new char[CharacterReader.readAheadLimit - triggeringSnippet.length() + 2]; // The "foo" part must be just at the limit.
Arrays.fill(padding, ' ');
String paddedSnippet = String.valueOf(padding) + triggeringSnippet;
ParseErrorList errorList = ParseErrorList.tracking(1);
Parser.parseFragment(paddedSnippet, null, "", errorList);
Assert.assertEquals(CharacterReader.readAheadLimit - 1, errorList.get(0).getPosition());
}
@Test
public void testUnconsumeAfterBufferUp() {
// test for after consume() a bufferUp occurs (look-forward) but then attempts to unconsume. Would throw a "No buffer left to unconsume"
String triggeringSnippet = "<title>One <span>Two";
char[] padding = new char[CharacterReader.readAheadLimit - triggeringSnippet.length() + 8]; // The "<span" part must be just at the limit. The "containsIgnoreCase" scan does a bufferUp, losing the unconsume
Arrays.fill(padding, ' ');
String paddedSnippet = String.valueOf(padding) + triggeringSnippet;
ParseErrorList errorList = ParseErrorList.tracking(1);
Parser.parseFragment(paddedSnippet, null, "", errorList);
}
@Test
public void testOpeningAngleBracketInsteadOfAttribute() {
String triggeringSnippet = "<html <";
ParseErrorList errorList = ParseErrorList.tracking(1);
Parser.parseFragment(triggeringSnippet, null, "", errorList);
Assert.assertEquals(6, errorList.get(0).getPosition());
}
@Test
public void testMalformedSelfClosingTag() {
String triggeringSnippet = "<html /ouch";
ParseErrorList errorList = ParseErrorList.tracking(1);
Parser.parseFragment(triggeringSnippet, null, "", errorList);
Assert.assertEquals(7, errorList.get(0).getPosition());
}
@Test
public void testOpeningAngleBracketInTagName() {
String triggeringSnippet = "<html<";
ParseErrorList errorList = ParseErrorList.tracking(1);
Parser.parseFragment(triggeringSnippet, null, "", errorList);
Assert.assertEquals(5, errorList.get(0).getPosition());
}
@Test
public void rcData() {
Document doc = Jsoup.parse("<title>One \0Two</title>");
Assert.assertEquals("One �Two", doc.title());
}
@Test
public void plaintext() {
Document doc = Jsoup.parse("<div>One<plaintext><div>Two</plaintext>\0no < Return");
Assert.assertEquals("<html><head></head><body><div>One<plaintext><div>Two</plaintext>�no < Return</plaintext></div></body></html>", TextUtil.stripNewlines(doc.html()));
}
@Test
public void nullInTag() {
Document doc = Jsoup.parse("<di\0v>One</di\0v>Two");
Assert.assertEquals("<di�v>\n One\n</di�v>Two", doc.body().html());
}
@Test
public void attributeValUnquoted() {
Document doc = Jsoup.parse("<p name=foo<bar>");
Element p = doc.selectFirst("p");
Assert.assertEquals("foo<bar", p.attr("name"));
doc = Jsoup.parse("<p foo=");
Assert.assertEquals("<p foo></p>", doc.body().html());
}
}
|
package pt.ulisboa.tecnico.muc.shopist.firebase;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.GeoPoint;
import java.util.List;
import java.util.Map;
public final class FireContract {
private FireContract() {}
protected static final class UserContract {
public String ShoppingId;
public String Email;
public Map<String, Integer> CrowdItemRatings;
}
protected static final class PantryContract {
public String Name;
public GeoPoint Location;
public String LocationName;
public Map<String, Map<String, Integer>> PantryItems;
public Map<String, Map<String, Integer>> PantryCarts;
public Timestamp Timestamp;
public List<String> Users;
}
protected static final class ItemContract {
public String Name;
public DocumentReference CrowdItem;
public Timestamp Timestamp;
}
protected static final class CrowdItemContract {
public String Barcode;
public List<String> Pictures;
public Map<String, Float> Prices;
public List<Integer> Ratings;
}
protected static final class ShoppingContract {
public String Name;
public DocumentReference CrowdShopping;
public Timestamp Timestamp;
}
protected static final class CrowdShoppingContract {
public GeoPoint Location;
public String LocationName;
public Long QueueTime;
public Map<String, Map<String, Integer>> SmartSort;
}
}
|
package com.southwind.repository;
import com.southwind.entity.Menu;
import java.util.List;
public interface MenuRepository {
public List<Menu> findAll(int index,int limit);
public int count();
public void save(Menu menu);
public Menu findById(long id);
public void update(Menu menu);
public void deleteById(long id);
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.workflow.componentmodel.serialization;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.Attribute;
/**
* The base .NET class managing System.Workflow.ComponentModel.Serialization.ConstructorArgumentAttribute, System.Workflow.ComponentModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Workflow.ComponentModel.Serialization.ConstructorArgumentAttribute" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Workflow.ComponentModel.Serialization.ConstructorArgumentAttribute</a>
*/
public class ConstructorArgumentAttribute extends Attribute {
/**
* Fully assembly qualified name: System.Workflow.ComponentModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
*/
public static final String assemblyFullName = "System.Workflow.ComponentModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
/**
* Assembly name: System.Workflow.ComponentModel
*/
public static final String assemblyShortName = "System.Workflow.ComponentModel";
/**
* Qualified class name: System.Workflow.ComponentModel.Serialization.ConstructorArgumentAttribute
*/
public static final String className = "System.Workflow.ComponentModel.Serialization.ConstructorArgumentAttribute";
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);
}
}
public ConstructorArgumentAttribute(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 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 ConstructorArgumentAttribute}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link ConstructorArgumentAttribute} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static ConstructorArgumentAttribute cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new ConstructorArgumentAttribute(from.getJCOInstance());
}
// Constructors section
public ConstructorArgumentAttribute() throws Throwable {
}
public ConstructorArgumentAttribute(java.lang.String argumentName) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(argumentName));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
// Properties section
public java.lang.String getArgumentName() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("ArgumentName");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
/*
* 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.serverlessapplicationrepository.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.serverlessapplicationrepository.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* UpdateApplicationResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateApplicationResultJsonUnmarshaller implements Unmarshaller<UpdateApplicationResult, JsonUnmarshallerContext> {
public UpdateApplicationResult unmarshall(JsonUnmarshallerContext context) throws Exception {
UpdateApplicationResult updateApplicationResult = new UpdateApplicationResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return updateApplicationResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("applicationId", targetDepth)) {
context.nextToken();
updateApplicationResult.setApplicationId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("author", targetDepth)) {
context.nextToken();
updateApplicationResult.setAuthor(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("creationTime", targetDepth)) {
context.nextToken();
updateApplicationResult.setCreationTime(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("description", targetDepth)) {
context.nextToken();
updateApplicationResult.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("homePageUrl", targetDepth)) {
context.nextToken();
updateApplicationResult.setHomePageUrl(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("isVerifiedAuthor", targetDepth)) {
context.nextToken();
updateApplicationResult.setIsVerifiedAuthor(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("labels", targetDepth)) {
context.nextToken();
updateApplicationResult.setLabels(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)).unmarshall(context));
}
if (context.testExpression("licenseUrl", targetDepth)) {
context.nextToken();
updateApplicationResult.setLicenseUrl(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("name", targetDepth)) {
context.nextToken();
updateApplicationResult.setName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("readmeUrl", targetDepth)) {
context.nextToken();
updateApplicationResult.setReadmeUrl(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("spdxLicenseId", targetDepth)) {
context.nextToken();
updateApplicationResult.setSpdxLicenseId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("verifiedAuthorUrl", targetDepth)) {
context.nextToken();
updateApplicationResult.setVerifiedAuthorUrl(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("version", targetDepth)) {
context.nextToken();
updateApplicationResult.setVersion(VersionJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return updateApplicationResult;
}
private static UpdateApplicationResultJsonUnmarshaller instance;
public static UpdateApplicationResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new UpdateApplicationResultJsonUnmarshaller();
return instance;
}
}
|
/*
* Copyright (c) 2018, Tim Lehner <Timothy.Lehner.2011@live.rhul.ac.uk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.raidsthieving.BatSolver;
// There are three distinct Thieving rooms, distinguished by the position of the entrance relative to the exit
// e.g. If you enter the room and must turn left to get to the exit and trough, this is a LEFT_TURN
import net.runelite.client.plugins.raidsthieving.InstancePoint;
public enum ThievingRoomType
{
LEFT_TURN(3271, 5389),
RIGHT_TURN(3350, 5399),
STRAIGHT(3317, 5397);
private final int x;
private final int y;
ThievingRoomType(int x, int y)
{
this.x = x;
this.y = y;
}
public static ThievingRoomType IdentifyByInstancePoint(InstancePoint point)
{
for (ThievingRoomType type : ThievingRoomType.values())
{
if (Math.abs(type.x - point.getX()) <= 1 &&
Math.abs(type.y - point.getY()) <= 1)
{
return type;
}
}
return null;
}
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.cluster.metadata;
import org.opensearch.cluster.Diff;
import org.opensearch.common.compress.CompressedXContent;
import org.opensearch.common.io.stream.Writeable;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentParser;
import org.opensearch.test.AbstractDiffableSerializationTestCase;
import org.opensearch.test.OpenSearchTestCase;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class ComposableIndexTemplateTests extends AbstractDiffableSerializationTestCase<ComposableIndexTemplate> {
@Override
protected ComposableIndexTemplate makeTestChanges(ComposableIndexTemplate testInstance) {
try {
return mutateInstance(testInstance);
} catch (IOException e) {
logger.error(e);
fail("mutating should not throw an exception, but got: " + e);
return null;
}
}
@Override
protected Writeable.Reader<Diff<ComposableIndexTemplate>> diffReader() {
return ComposableIndexTemplate::readITV2DiffFrom;
}
@Override
protected ComposableIndexTemplate doParseInstance(XContentParser parser) throws IOException {
return ComposableIndexTemplate.parse(parser);
}
@Override
protected Writeable.Reader<ComposableIndexTemplate> instanceReader() {
return ComposableIndexTemplate::new;
}
@Override
protected ComposableIndexTemplate createTestInstance() {
return randomInstance();
}
public static ComposableIndexTemplate randomInstance() {
Settings settings = null;
CompressedXContent mappings = null;
Map<String, AliasMetadata> aliases = null;
Template template = null;
ComposableIndexTemplate.DataStreamTemplate dataStreamTemplate = randomDataStreamTemplate();
if (dataStreamTemplate != null || randomBoolean()) {
if (randomBoolean()) {
settings = randomSettings();
}
if (dataStreamTemplate != null || randomBoolean()) {
mappings = randomMappings(dataStreamTemplate);
}
if (randomBoolean()) {
aliases = randomAliases();
}
template = new Template(settings, mappings, aliases);
}
Map<String, Object> meta = null;
if (randomBoolean()) {
meta = randomMeta();
}
List<String> indexPatterns = randomList(1, 4, () -> randomAlphaOfLength(4));
List<String> componentTemplates = randomList(0, 10, () -> randomAlphaOfLength(5));
return new ComposableIndexTemplate(
indexPatterns,
template,
componentTemplates,
randomBoolean() ? null : randomNonNegativeLong(),
randomBoolean() ? null : randomNonNegativeLong(),
meta,
dataStreamTemplate
);
}
private static Map<String, AliasMetadata> randomAliases() {
String aliasName = randomAlphaOfLength(5);
AliasMetadata aliasMeta = AliasMetadata.builder(aliasName)
.filter("{\"term\":{\"year\":" + randomIntBetween(1, 3000) + "}}")
.routing(randomBoolean() ? null : randomAlphaOfLength(3))
.isHidden(randomBoolean() ? null : randomBoolean())
.writeIndex(randomBoolean() ? null : randomBoolean())
.build();
return Collections.singletonMap(aliasName, aliasMeta);
}
private static CompressedXContent randomMappings(ComposableIndexTemplate.DataStreamTemplate dataStreamTemplate) {
try {
if (dataStreamTemplate != null) {
return new CompressedXContent("{\"properties\":{\"" + dataStreamTemplate.getTimestampField() + "\":{\"type\":\"date\"}}}");
} else {
return new CompressedXContent("{\"properties\":{\"" + randomAlphaOfLength(5) + "\":{\"type\":\"keyword\"}}}");
}
} catch (IOException e) {
fail("got an IO exception creating fake mappings: " + e);
return null;
}
}
private static Settings randomSettings() {
return Settings.builder()
.put(IndexMetadata.SETTING_BLOCKS_READ, randomBoolean())
.put(IndexMetadata.SETTING_BLOCKS_WRITE, randomBoolean())
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 10))
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, randomIntBetween(0, 5))
.put(IndexMetadata.SETTING_BLOCKS_WRITE, randomBoolean())
.put(IndexMetadata.SETTING_PRIORITY, randomIntBetween(0, 100000))
.build();
}
private static Map<String, Object> randomMeta() {
if (randomBoolean()) {
return Collections.singletonMap(randomAlphaOfLength(4), randomAlphaOfLength(4));
} else {
return Collections.singletonMap(
randomAlphaOfLength(5),
Collections.singletonMap(randomAlphaOfLength(4), randomAlphaOfLength(4))
);
}
}
private static ComposableIndexTemplate.DataStreamTemplate randomDataStreamTemplate() {
if (randomBoolean()) {
return null;
} else {
return new ComposableIndexTemplate.DataStreamTemplate();
}
}
@Override
protected ComposableIndexTemplate mutateInstance(ComposableIndexTemplate orig) throws IOException {
return mutateTemplate(orig);
}
public static ComposableIndexTemplate mutateTemplate(ComposableIndexTemplate orig) {
switch (randomIntBetween(0, 6)) {
case 0:
List<String> newIndexPatterns = randomValueOtherThan(
orig.indexPatterns(),
() -> randomList(1, 4, () -> randomAlphaOfLength(4))
);
return new ComposableIndexTemplate(
newIndexPatterns,
orig.template(),
orig.composedOf(),
orig.priority(),
orig.version(),
orig.metadata(),
orig.getDataStreamTemplate()
);
case 1:
return new ComposableIndexTemplate(
orig.indexPatterns(),
randomValueOtherThan(
orig.template(),
() -> new Template(randomSettings(), randomMappings(orig.getDataStreamTemplate()), randomAliases())
),
orig.composedOf(),
orig.priority(),
orig.version(),
orig.metadata(),
orig.getDataStreamTemplate()
);
case 2:
List<String> newComposedOf = randomValueOtherThan(orig.composedOf(), () -> randomList(0, 10, () -> randomAlphaOfLength(5)));
return new ComposableIndexTemplate(
orig.indexPatterns(),
orig.template(),
newComposedOf,
orig.priority(),
orig.version(),
orig.metadata(),
orig.getDataStreamTemplate()
);
case 3:
return new ComposableIndexTemplate(
orig.indexPatterns(),
orig.template(),
orig.composedOf(),
randomValueOtherThan(orig.priority(), OpenSearchTestCase::randomNonNegativeLong),
orig.version(),
orig.metadata(),
orig.getDataStreamTemplate()
);
case 4:
return new ComposableIndexTemplate(
orig.indexPatterns(),
orig.template(),
orig.composedOf(),
orig.priority(),
randomValueOtherThan(orig.version(), OpenSearchTestCase::randomNonNegativeLong),
orig.metadata(),
orig.getDataStreamTemplate()
);
case 5:
return new ComposableIndexTemplate(
orig.indexPatterns(),
orig.template(),
orig.composedOf(),
orig.priority(),
orig.version(),
randomValueOtherThan(orig.metadata(), ComposableIndexTemplateTests::randomMeta),
orig.getDataStreamTemplate()
);
case 6:
return new ComposableIndexTemplate(
orig.indexPatterns(),
orig.template(),
orig.composedOf(),
orig.priority(),
orig.version(),
orig.metadata(),
randomValueOtherThan(orig.getDataStreamTemplate(), ComposableIndexTemplateTests::randomDataStreamTemplate)
);
default:
throw new IllegalStateException("illegal randomization branch");
}
}
}
|
package ru.otus.l0151.websocket;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
/**
* This class represents a servlet starting a webSocket application
*/
public class WebSocketLoginServlet extends WebSocketServlet {
private final static int LOGOUT_TIME = 10 * 60 * 1000;
@Override
public void configure(WebSocketServletFactory factory) {
factory.getPolicy().setIdleTimeout(LOGOUT_TIME);
factory.setCreator(new LoginWebSocketCreator());
// factory.getExtensionFactory().unregister("permessage-deflate");
}
}
|
/*
* Copyright 2020 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.decibeltx.studytracker.model;
import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedSubgraph;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name = "assays")
@EntityListeners(AuditingEntityListener.class)
@TypeDef(name = "json", typeClass = JsonBinaryType.class)
@NamedEntityGraphs({
@NamedEntityGraph(name = "assay-summary", attributeNodes = {
@NamedAttributeNode("assayType"),
@NamedAttributeNode("notebookFolder"),
@NamedAttributeNode("storageFolder"),
@NamedAttributeNode("owner"),
@NamedAttributeNode("users")
}),
@NamedEntityGraph(name = "assay-with-attributes", attributeNodes = {
@NamedAttributeNode(value = "assayType", subgraph = "assay-type-details"),
@NamedAttributeNode("notebookFolder"),
@NamedAttributeNode("storageFolder"),
@NamedAttributeNode("owner"),
@NamedAttributeNode("createdBy"),
@NamedAttributeNode("lastModifiedBy"),
@NamedAttributeNode(value = "tasks", subgraph = "assay-task-details"),
@NamedAttributeNode("users")
}, subgraphs = {
@NamedSubgraph(name = "assay-type-details", attributeNodes = {
@NamedAttributeNode("fields"),
@NamedAttributeNode("tasks")
}),
@NamedSubgraph(name = "assay-task-details", attributeNodes = {
@NamedAttributeNode("createdBy"),
@NamedAttributeNode("lastModifiedBy"),
@NamedAttributeNode("assignedTo")
})
}),
@NamedEntityGraph(name = "assay-with-parents", attributeNodes = {
@NamedAttributeNode("assayType"),
@NamedAttributeNode("owner"),
@NamedAttributeNode("notebookFolder"),
@NamedAttributeNode("storageFolder"),
@NamedAttributeNode(value = "study", subgraph = "study-summary")
}, subgraphs = {
@NamedSubgraph(name = "study-summary", attributeNodes = {
@NamedAttributeNode("program"),
@NamedAttributeNode("collaborator")
})
})
})
public class Assay {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "status", nullable = false)
@Enumerated(EnumType.STRING)
private Status status;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "assay_type_id", nullable = false)
private AssayType assayType;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "study_id", nullable = false)
private Study study;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "code", nullable = false, unique = true)
private String code;
@Column(name = "description", nullable = false, columnDefinition = "TEXT")
private String description;
@CreatedBy
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "created_by", nullable = false)
private User createdBy;
@LastModifiedBy
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "last_modified_by", nullable = false)
private User lastModifiedBy;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "owner", nullable = false)
private User owner;
@Column(name = "start_date", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date startDate;
@Column(name = "end_date")
@Temporal(TemporalType.TIMESTAMP)
private Date endDate;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "notebook_folder_id")
private ELNFolder notebookFolder;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "storage_folder_id")
private FileStoreFolder storageFolder;
@Column(name = "active", nullable = false)
private boolean active;
@Column(name = "created_at", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(name = "updated_at", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "assay_users",
joinColumns = @JoinColumn(name = "assay_id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "user_id", nullable = false))
private Set<User> users = new HashSet<>();
@Type(type = "json")
@Column(name = "fields", columnDefinition = "json")
private Map<String, Object> fields = new LinkedHashMap<>();
@Type(type = "json")
@Column(name = "attributes", columnDefinition = "json")
private Map<String, String> attributes = new LinkedHashMap<>();
@OneToMany(mappedBy = "assay", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<AssayTask> tasks = new HashSet<>();
public void addTask(AssayTask task) {
task.setAssay(this);
this.tasks.add(task);
}
public void removeTask(AssayTask task) {
this.tasks.remove(task);
}
public void removeTask(Long id) {
this.tasks.removeIf(t -> t.getId().equals(id));
}
public void addField(String key, Object value) {
this.fields.put(key, value);
}
public void removeField(String key) {
this.fields.remove(key);
}
public void addAttribute(String key, String value) {
this.attributes.put(key, value);
}
public void removeAttribute(String key) {
this.attributes.remove(key);
}
public void addUser(User user) {
this.users.add(user);
}
public void removeUser(User user) {
this.users.remove(user);
}
public void removeUser(Long id) {
this.users.removeIf(u -> u.getId().equals(id));
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public AssayType getAssayType() {
return assayType;
}
public void setAssayType(AssayType assayType) {
this.assayType = assayType;
}
public Study getStudy() {
return study;
}
public void setStudy(Study study) {
this.study = study;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public User getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(User lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public ELNFolder getNotebookFolder() {
return notebookFolder;
}
public void setNotebookFolder(ELNFolder notebookFolder) {
this.notebookFolder = notebookFolder;
}
public FileStoreFolder getStorageFolder() {
return storageFolder;
}
public void setStorageFolder(FileStoreFolder storageFolder) {
this.storageFolder = storageFolder;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Map<String, Object> getFields() {
return fields;
}
public void setFields(Map<String, Object> fields) {
this.fields = fields;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public Set<AssayTask> getTasks() {
return tasks;
}
public void setTasks(Set<AssayTask> tasks) {
for (AssayTask task: tasks) {
task.setAssay(this);
}
this.tasks = tasks;
}
}
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.themes;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.ide.ui.UIThemeMetadata;
import com.intellij.json.psi.JsonFile;
import com.intellij.json.psi.JsonProperty;
import com.intellij.json.psi.JsonReferenceExpression;
import com.intellij.json.psi.JsonStringLiteral;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PairProcessor;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.devkit.themes.metadata.UIThemeMetadataService;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Completion in IntelliJ theme files.
*/
public class ThemeJsonCompletionContributor extends CompletionContributor {
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
PsiElement position = parameters.getPosition();
if (!(position instanceof LeafPsiElement)) return;
if (!isThemeJsonFile(parameters.getOriginalFile())) return;
PsiElement parent = position.getParent();
if (parent instanceof JsonStringLiteral || parent instanceof JsonReferenceExpression) {
PsiElement parentParent = parent.getParent();
if (!(parentParent instanceof JsonProperty)) return;
handleJsonProperty(position, (JsonProperty)parentParent, parameters, result);
}
else if (parent instanceof JsonProperty) {
handleJsonProperty(position, (JsonProperty)parent, parameters, result);
}
}
private static boolean isThemeJsonFile(@Nullable PsiFile file) {
return file instanceof JsonFile && ThemeJsonUtil.isThemeFilename(file.getName());
}
private static void handleJsonProperty(@NotNull PsiElement element,
@NotNull JsonProperty property,
@NotNull CompletionParameters parameters,
@NotNull CompletionResultSet result) {
if (parameters.getCompletionType() != CompletionType.BASIC) return;
if (!ThemeJsonUtil.isInsideUiProperty(property)) return;
if (!isPropertyKey(element)) return;
String presentNamePart = ThemeJsonUtil.getParentNames(property);
boolean shouldSurroundWithQuotes = !element.getText().startsWith("\"");
Iterable<LookupElement> lookupElements = getLookupElements(presentNamePart, shouldSurroundWithQuotes);
result.addAllElements(lookupElements);
}
private static boolean isPropertyKey(@NotNull PsiElement element) {
PsiElement sibling = element.getParent(); // element is leaf, parent is reference expression
while ((sibling = sibling.getPrevSibling()) != null) {
if (":".equals(sibling.getText())) return false; // no completion for values
}
return true;
}
private static Iterable<LookupElement> getLookupElements(@NotNull String presentNamePart,
boolean shouldSurroundWithQuotes) {
Predicate<String> conditionFilter;
Function<String, String> mapFunction;
if (presentNamePart.startsWith("*")) {
//TODO darcula etc. should be proposed after *?
String tail = presentNamePart.substring(1);
conditionFilter = key -> key.endsWith(tail);
mapFunction = key -> key.substring(presentNamePart.length() - 1); // + 1 for dot, - 2 for '*.'
}
else if (presentNamePart.isEmpty()) {
conditionFilter = key -> true;
mapFunction = key -> key;
}
else {
conditionFilter = key -> StringUtil.startsWithConcatenation(key, presentNamePart, ".");
mapFunction = key -> key.substring(presentNamePart.length() + 1); // + 1 for dot
}
List<LookupElement> variants = new SmartList<>();
PairProcessor<UIThemeMetadata, UIThemeMetadata.UIKeyMetadata> processor = (themeMetadata, uiKeyMetadata) -> {
String key = uiKeyMetadata.getKey();
if (!conditionFilter.test(key)) return true;
final String completionKey = mapFunction.apply(key);
final String description = uiKeyMetadata.getDescription();
final boolean deprecated = uiKeyMetadata.isDeprecated();
final String source = uiKeyMetadata.getSource();
final String since = uiKeyMetadata.getSince();
final LookupElementBuilder builder =
LookupElementBuilder.create(completionKey)
.withPresentableText(key)
.withStrikeoutness(deprecated)
.appendTailText(StringUtil.isEmpty(since) ? "" : " [" + since + "]", true)
.appendTailText(StringUtil.isEmpty(description) ? "" : " (" + description + ")", true)
.appendTailText(StringUtil.isEmpty(source) ? "" : " " + source, true)
.withTypeText("[" + ObjectUtils.chooseNotNull(themeMetadata.getName(), themeMetadata.getPluginId()) + "]")
.withInsertHandler(shouldSurroundWithQuotes ? MyInsertHandler.SURROUND_WITH_QUOTES : MyInsertHandler.INSTANCE);
variants.add(deprecated ? PrioritizedLookupElement.withPriority(builder, -100) : builder);
return true;
};
UIThemeMetadataService.getInstance().processAllKeys(processor);
return variants;
}
//TODO insert ': ' if necessary
private static final class MyInsertHandler implements InsertHandler<LookupElement> {
private static final MyInsertHandler INSTANCE = new MyInsertHandler(false);
private static final MyInsertHandler SURROUND_WITH_QUOTES = new MyInsertHandler(true);
private final boolean mySurroundWithQuotes;
private MyInsertHandler(boolean surroundWithQuotes) {
mySurroundWithQuotes = surroundWithQuotes;
}
@Override
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement item) {
if (mySurroundWithQuotes) {
String quoted = "\"" + item.getLookupString() + "\"";
context.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), quoted);
}
}
}
}
|
/*
* Copyright 2020, 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 anthos.samples.financedemo.ledgerwriter;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
@RestController
public final class LedgerWriterController {
private static final Logger LOGGER =
Logger.getLogger(LedgerWriterController.class.getName());
@Autowired
private TransactionRepository transactionRepository;
private JWTVerifier verifier;
private String localRoutingNum;
private String balancesApiUri;
private String version;
public static final String READINESS_CODE = "ok";
// account ids should be 10 digits between 0 and 9
private static final Pattern ACCT_REGEX = Pattern.compile("^[0-9]{10}$");
// route numbers should be 9 digits between 0 and 9
private static final Pattern ROUTE_REGEX = Pattern.compile("^[0-9]{9}$");
/**
* Constructor.
*
* Initializes JWT verifier.
*/
public LedgerWriterController(
JWTVerifier verifier,
@Value("${LOCAL_ROUTING_NUM}") String localRoutingNum,
@Value("http://${BALANCES_API_ADDR}/balances")
String balancesApiUri,
@Value("${VERSION}") String version) {
this.verifier = verifier;
this.localRoutingNum = localRoutingNum;
this.balancesApiUri = balancesApiUri;
this.version = version;
}
/**
* Version endpoint.
*
* @return service version string
*/
@GetMapping("/version")
public ResponseEntity version() {
return new ResponseEntity<String>(version, HttpStatus.OK);
}
/**
* Readiness probe endpoint.
*
* @return HTTP Status 200 if server is ready to receive requests.
*/
@GetMapping("/ready")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> readiness() {
return new ResponseEntity<String>(READINESS_CODE, HttpStatus.OK);
}
/**
* Submit a new transaction to the ledger.
*
* @param bearerToken HTTP request 'Authorization' header
* @param transaction transaction to submit
*
* @return HTTP Status 200 if transaction was successfully submitted
*/
@PostMapping(value = "/transactions", consumes = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> addTransaction(
@RequestHeader("Authorization") String bearerToken,
@RequestBody Transaction transaction) {
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
bearerToken = bearerToken.split("Bearer ")[1];
}
try {
final DecodedJWT jwt = this.verifier.verify(bearerToken);
// validate transaction
validateTransaction(jwt.getClaim("acct").asString(), transaction);
if (transaction.getFromRoutingNum().equals(localRoutingNum)) {
checkAvailableBalance(bearerToken, transaction);
}
// No exceptions thrown. Add to ledger.
submitTransaction(transaction);
return new ResponseEntity<String>("ok", HttpStatus.CREATED);
} catch (JWTVerificationException e) {
return new ResponseEntity<String>("not authorized",
HttpStatus.UNAUTHORIZED);
} catch (IllegalArgumentException | IllegalStateException e) {
return new ResponseEntity<String>(e.toString(),
HttpStatus.BAD_REQUEST);
} catch (ResourceAccessException
| CannotCreateTransactionException
| HttpServerErrorException e) {
return new ResponseEntity<String>(e.toString(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Authenticate transaction details before adding to the ledger.
*
* - Ensure sender is the same user authenticated by auth token
* - Ensure account and routing numbers are in the correct format
* - Ensure sender and receiver are different accounts
* - Ensure amount is positive, and sender has proper balance
*
* @param authedAccount the currently authenticated user account
* @param transaction the transaction object
* @param bearerToken the token used to authenticate request
*
* @throws IllegalArgumentException on validation error
*/
private void validateTransaction(String authedAcct, Transaction transaction)
throws IllegalArgumentException {
final String fromAcct = transaction.getFromAccountNum();
final String fromRoute = transaction.getFromRoutingNum();
final String toAcct = transaction.getToAccountNum();
final String toRoute = transaction.getToRoutingNum();
final Integer amount = transaction.getAmount();
// If this is an internal transaction,
// ensure it originated from the authenticated user.
if (fromRoute.equals(localRoutingNum) && !fromAcct.equals(authedAcct)) {
throw new IllegalArgumentException("sender not authenticated");
}
// Validate account and routing numbers.
if (!ACCT_REGEX.matcher(fromAcct).matches()
|| !ACCT_REGEX.matcher(toAcct).matches()
|| !ROUTE_REGEX.matcher(fromRoute).matches()
|| !ROUTE_REGEX.matcher(toRoute).matches()) {
throw new IllegalArgumentException("invalid account details");
}
// Ensure sender isn't receiver.
if (fromAcct.equals(toAcct) && fromRoute.equals(toRoute)) {
throw new IllegalArgumentException("can't send to self");
}
// Ensure amount is valid value.
if (amount <= 0) {
throw new IllegalArgumentException("invalid amount");
}
}
/**
* Check there is available funds for this transaction.
*
* @param token the token used to authenticate request
* @param transaction the transaction object
*
* @throws IllegalStateException if insufficient funds
* @throws HttpServerErrorException if balance service returns 500
*/
private void checkAvailableBalance(String token, Transaction transaction)
throws IllegalStateException, HttpServerErrorException {
final String fromAcct = transaction.getFromAccountNum();
final Integer amount = transaction.getAmount();
// Ensure sender balance can cover transaction.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
HttpEntity entity = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();
String uri = balancesApiUri + "/" + fromAcct;
ResponseEntity<Integer> response = restTemplate.exchange(
uri, HttpMethod.GET, entity, Integer.class);
Integer senderBalance = response.getBody();
if (senderBalance < amount) {
throw new IllegalStateException("insufficient balance");
}
}
private void submitTransaction(Transaction transaction) {
LOGGER.fine("Submitting transaction " + transaction.toString());
transactionRepository.save(transaction);
}
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.preferences;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.preference.PreferenceGroup;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.chrome.R;
import java.util.Locale;
/**
* A preference category that accepts clicks for toggling on/off.
*/
public class ExpandablePreferenceGroup extends PreferenceGroup {
private Drawable mDrawable;
private ImageView mImageView;
// Whether the PreferenceGroup is in an expanded or collapsed state.
private boolean mExpanded;
public ExpandablePreferenceGroup(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.preferenceStyle);
setWidgetLayoutResource(R.layout.site_list_expandable_header);
}
/**
* Set the title for the preference group.
* @param resourceId The resource id of the text to use.
* @param count The number of entries the preference group contains.
*/
public void setGroupTitle(int resourceId, int count) {
SpannableStringBuilder spannable =
new SpannableStringBuilder(getContext().getResources().getString(resourceId));
String prefCount = String.format(Locale.getDefault(), " - %d", count);
spannable.append(prefCount);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
spannable.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
0,
spannable.length() - prefCount.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
spannable.setSpan(new TypefaceSpan("sans-serif-medium"),
0,
spannable.length() - prefCount.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
// Color the first part of the title blue.
ForegroundColorSpan blueSpan = new ForegroundColorSpan(
ApiCompatibilityUtils.getColor(getContext().getResources(),
R.color.pref_accent_color));
spannable.setSpan(blueSpan, 0, spannable.length() - prefCount.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Gray out the total count of items.
int gray = ApiCompatibilityUtils.getColor(getContext().getResources(),
R.color.expandable_group_dark_gray);
spannable.setSpan(new ForegroundColorSpan(gray),
spannable.length() - prefCount.length(),
spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setTitle(spannable);
}
public void setExpanded(boolean expanded) {
mExpanded = expanded;
}
@Override
public void setIcon(Drawable drawable) {
mDrawable = drawable;
if (mImageView != null) mImageView.setImageDrawable(mDrawable);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mImageView = (ImageView) view.findViewById(R.id.expando);
if (mDrawable != null) mImageView.setImageDrawable(mDrawable);
// For accessibility, read out the whole title and whether the group is collapsed/expanded.
String description = getTitle() + getContext().getResources().getString(mExpanded
? R.string.accessibility_expanded_group
: R.string.accessibility_collapsed_group);
view.setContentDescription(description);
}
}
|
/*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.poly;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import fuzzm.lustre.SignalName;
import fuzzm.lustre.evaluation.PolyFunctionMap;
import fuzzm.solver.SolverResults;
import fuzzm.util.FuzzMInterval;
import fuzzm.util.ID;
import fuzzm.util.IntervalVector;
import fuzzm.util.Rat;
import fuzzm.util.RatSignal;
import fuzzm.util.RatVect;
import fuzzm.util.TypedName;
import fuzzm.value.instance.RationalValue;
import fuzzm.value.poly.GlobalState;
import jkind.lustre.NamedType;
import jkind.util.BigFraction;
public class VariableList extends LinkedList<Variable> {
private static final long serialVersionUID = 7983100382771154597L;
public VariableList() {
super();
}
public VariableList(VariableList arg) {
super(arg);
}
public VariableList(Variable c) {
super();
addLast(c);
}
// public VariableList not() {
// VariableList res = new VariableList();
// for (Variable vc: this) {
// res.addLast(vc.not());
// }
// return res;
// }
@Override
public boolean add(Variable b) {
throw new IllegalArgumentException();
}
public static void printAddFirst(String alt, Variable b, Variable first) {
System.out.println("addFirst"+alt+"("+b.vid+":"+b.vid.level()+","+first.vid+":"+first.vid.level() + ",...)");
}
public static void printAddLast(String alt, Variable last, Variable b) {
System.out.println("addLast"+alt+"(...,"+last.vid+":"+last.vid.level()+","+b.vid+":"+b.vid.level()+")");
}
@Override
public void addFirst(Variable b) {
// Maintain the ordering invariant ..
if (! isEmpty()) {
if (b.vid.compareTo(this.peekFirst().vid) >= 0) {
printAddFirst("",b,this.peekFirst());
throw new IllegalArgumentException();
}
}
super.addFirst(b);
}
@Override
public void addLast(Variable b) {
// Maintain the ordering invariant ..
if (! isEmpty()) {
if (this.peekLast().vid.compareTo(b.vid) >= 0) {
printAddLast("",this.peekLast(),b);
throw new IllegalArgumentException();
}
}
super.addLast(b);
}
public void addFirstRev(Variable b) {
// Maintain the ordering invariant ..
if (! isEmpty()) {
if (b.vid.compareTo(this.peekFirst().vid) <= 0) {
printAddFirst("Rev",b,this.peekFirst());
throw new IllegalArgumentException();
}
}
super.addFirst(b);
}
public void addLastRev(Variable b) {
// Maintain the ordering invariant ..
if (! isEmpty()) {
if (this.peekLast().vid.compareTo(b.vid) <= 0) {
printAddLast("Rev",this.peekLast(),b);
throw new IllegalArgumentException();
}
}
super.addLast(b);
}
public static VariableList andTF(VariableList x, VariableList y) {
// andTF: Here T and F refer to the polarity of the associated
// polyBool. y is, therefore, an implicitly negated 'or'
// expression. We will be discarding all of x.
if (x.isEmpty()) return y;
if (y.isEmpty()) return y;
VariableList res = new VariableList();
Iterator<Variable> xit = x.iterator();
Iterator<Variable> yit = y.iterator();
Variable xv = xit.next();
Variable yv = yit.next();
while (true) {
int cmp = xv.vid.compareTo(yv.vid);
if (cmp > 0) {
res.addLast(yv);
if (! yit.hasNext()) {
res.addLast(new VariablePhantom(xv));
break;
}
yv = yit.next();
} else if (cmp < 0){
res.addLast(new VariablePhantom(xv));
if (! xit.hasNext()) {
res.addLast(yv);
break;
}
xv = xit.next();
} else {
Variable z = Variable.target(yv,false,xv,true);
res.addLast(z);
if (! (xit.hasNext() && yit.hasNext())) break;
xv = xit.next();
yv = yit.next();
}
}
while (yit.hasNext()) {
res.addLast(yit.next());
}
return res;
}
public static VariableList andFF(VariableList x, VariableList y) {
// andFF: So we have the option of choosing one or the other
// or of conjoining both. One might argue that, to keep the
// solution space as large as possible, one should simply
// discard one list or the other. However, when we consider
// sampling, the false space gives us information about which
// constraints to TARGET.
if (x.isEmpty()) return y;
if (y.isEmpty()) return x;
VariableList res = new VariableList();
Iterator<Variable> xit = x.iterator();
Iterator<Variable> yit = y.iterator();
Variable xv = xit.next();
Variable yv = yit.next();
while (true) {
int cmp = xv.vid.compareTo(yv.vid);
if (cmp > 0) {
res.addLast(yv);
if (! yit.hasNext()) {
res.addLast(xv);
break;
}
yv = yit.next();
} else if (cmp < 0){
res.addLast(xv);
if (! xit.hasNext()) {
res.addLast(yv);
break;
}
xv = xit.next();
} else {
Variable z = Variable.minSet(xv,yv);
res.addLast(z);
if (! (xit.hasNext() && yit.hasNext())) break;
xv = xit.next();
yv = yit.next();
}
}
while (xit.hasNext()) {
res.addLast(xit.next());
}
while (yit.hasNext()) {
res.addLast(yit.next());
}
return res;
}
public static VariableList andTT(VariableList x, VariableList y) {
if (x.isEmpty()) return y;
if (y.isEmpty()) return x;
VariableList ctx = new VariableList();
Iterator<Variable> xit = x.iterator();
Iterator<Variable> yit = y.iterator();
Variable xv = xit.next();
Variable yv = yit.next();
//System.out.println("and() ..");
while (true) {
//System.out.println("xv:" + xv.vid + ":" + xv.vid.level());
//System.out.println("yv:" + yv.vid + ":" + yv.vid.level());
int cmp = xv.vid.compareTo(yv.vid);
// Normal list is ordered from smallest to largest.
if (cmp > 0) {
// x is greater than y ..
//if (Debug.isEnabled()) System.out.println(ID.location() + "(T and " + yv + ") = " + yv);
ctx.addFirstRev(yv);
if (! yit.hasNext()) {
ctx.addFirstRev(xv);
break;
}
yv = yit.next();
} else if (cmp < 0){
ctx.addFirstRev(xv);
//if (Debug.isEnabled()) System.out.println(ID.location() + "(" + xv + " and T) = " + xv);
if (! xit.hasNext()) {
ctx.addFirstRev(yv);
break;
}
xv = xit.next();
} else {
RestrictionResult rr = Variable.andTrue(xv,yv);
//if (Debug.isEnabled()) System.out.println(ID.location() + "(" + xv + " and " + yv + ") = " + rr.newConstraint);
for (Variable r: rr.restrictionList) {
ctx = restrict(r,ctx.iterator());
}
ctx.addFirstRev(rr.newConstraint);
if (! (xit.hasNext() && yit.hasNext())) break;
xv = xit.next();
yv = yit.next();
}
}
while (xit.hasNext()) {
ctx.addFirstRev(xit.next());
}
while (yit.hasNext()) {
ctx.addFirstRev(yit.next());
}
Collections.reverse(ctx);
//System.out.println("and().");
return ctx;
}
public static VariableList restrict(Variable c, Iterator<Variable> xit) {
//System.out.println("Push " + c.vid + ":" + c.vid.level() + " ..");
//if (Debug.isEnabled()) System.out.println(ID.location() + "Restriction : " + c);
VariableList res = new VariableList();
while (xit.hasNext()) {
// Reversed list is ordered from largest to smallest
Variable xv = xit.next();
//System.out.println("Restriction : " + c.vid+":"+c.vid.level());
//System.out.println("Location : " + xv.vid+":"+xv.vid.level());
int cmp = xv.vid.compareTo(c.vid);
if (cmp > 0) {
res.addLastRev(xv);
} else {
if (cmp < 0) {
res.addLastRev(c);
c = xv;
} else {
RestrictionResult rr = Variable.andTrue(xv,c);
//if (Debug.isEnabled()) System.out.println(ID.location() + "("+xv+" ^ "+c+") = " + rr.newConstraint);
for (Variable vc: rr.restrictionList) {
VariableList pres = restrict(vc,xit);
xit = pres.iterator();
}
c = rr.newConstraint;
}
while (xit.hasNext()) {
res.addLastRev(c);
c = xit.next();
}
}
}
res.addLastRev(c);
//System.out.println("Pop.");
return res;
}
public VariableList applyRewrites() {
Map<VariableID,AbstractPoly> rewrite = new HashMap<>();
VariableList res = new VariableList();
for (Variable v: this) {
v = v.rewrite(rewrite);
boolean keep = true;
if (v instanceof VariableEquality) {
VariableEquality veq = (VariableEquality) v;
if (veq.relation == RelationType.INCLUSIVE) {
rewrite.put(veq.vid, veq.poly);
keep = (veq.vid.role != VariableRole.AUXILIARY);
}
}
if (keep) res.addLast(v);
}
return res;
}
public VariableList normalize() {
VariableList x = this.applyRewrites();
boolean changed;
do {
changed = false;
x = new VariableList(x);
Collections.reverse(x);
VariableList res = new VariableList();
while (! x.isEmpty()) {
//System.out.println(ID.location() + "Generalization size : " + x.size());
//System.out.println(ID.location() + x);
Variable v = x.poll();
if (v instanceof VariablePhantom) {
continue;
}
if (v.implicitEquality()) {
//System.out.println(ID.location() + "Implicit Equality : " + v);
v = v.toEquality();
changed = true;
}
if (v.slackIntegerBounds()) {
//System.out.println(ID.location() + "Slack Bounds : " + v);
v = v.tightenIntegerBounds();
changed = true;
}
if (v.reducableIntegerInterval()) {
//System.out.println(ID.location() + "reducableIntegerInterval : " + v);
RestrictionResult er = v.reducedInterval();
//System.out.println(ID.location() + "reducedInterval : " + er);
v = er.newConstraint;
for (Variable r: er.restrictionList) {
x = restrict(r,x.iterator());
}
changed = true;
}
if (v.requiresRestriction()) {
RestrictionResult rr = v.restriction();
v = rr.newConstraint;
for (Variable r: rr.restrictionList) {
x = restrict(r,x.iterator());
}
}
res.addFirst(v);
}
x = res.applyRewrites();
} while (changed);
return x;
}
// public VariableList chooseAndNegateOne() {
// Variable one = null;
// int max = 0;
// for (Variable v : this) {
// if (v.countFeatures() >= max) {
// one = v;
// max = v.countFeatures();
// }
// }
// assert(one != null);
// return new VariableList(one.not());
// }
public RatSignal randomVector(boolean biased, BigFraction Smin, BigFraction Smax, IntervalVector span, Map<VariableID,BigFraction> ctx) {
//int tries = 100;
@SuppressWarnings("unused")
int bools = 0;
while (true) {
try {
RatSignal res = new RatSignal();
for (Variable c: this) {
RegionBounds r;
try {
r = c.constraintBounds(ctx);
} catch (EmptyIntervalException e) {
System.out.println(ID.location() + "Constraint : " + c);
System.out.println(ID.location() + "Context : " + ctx);
throw new IllegalArgumentException();
}
VariableID vid = c.vid;
SignalName sn = vid.name;
TypedName name = sn.name;
NamedType type = c.vid.name.name.type;
FuzzMInterval bounds;
try {
bounds = span.containsKey(name) ? r.fuzzInterval(span.get(name)) : r.fuzzInterval(type, Smin, Smax);
} catch (EmptyIntervalException e) {
System.out.println(ID.location() + "Constraint : " + c);
System.out.println(ID.location() + "Context : " + ctx);
System.out.println(ID.location() + "RegionBounds : " + r);
throw new IllegalArgumentException();
}
BigFraction value;
if (r.rangeType == RelationType.INCLUSIVE) {
try {
value = Rat.biasedRandom(type, biased, 0, bounds.min, bounds.max);
} catch (EmptyIntervalException e) {
System.out.println(ID.location() + "Constraint : " + c);
System.out.println(ID.location() + "CEX String : " + c.cexString());
System.out.println(ID.location() + "Context : " + ctx);
System.out.println(ID.location() + "RegionBounds : " + r);
System.out.println(ID.location() + "FuzzMBounds : " + bounds);
throw new IllegalArgumentException();
}
} else {
BigFraction upper = ((RationalValue) r.upper).value();
BigFraction lower = ((RationalValue) r.lower).value();
BigFraction one = type == NamedType.INT ? BigFraction.ONE : BigFraction.ZERO;
BigFraction max = bounds.max.add(lower.subtract(bounds.min)).add(one);
value = Rat.biasedRandom(type, biased, 0, upper, max);
}
if (sn.time >= 0) res.put(sn.time, sn.name, value);
ctx.put(vid, value);
if (! c.evalCEX(ctx)) {
System.out.println(ID.location() + "Constraint : " + c);
System.out.println(ID.location() + "Context : " + ctx);
System.out.println(ID.location() + "RegionBounds : " + r);
System.out.println(ID.location() + "FuzzMBounds : " + bounds);
assert(false);
}
}
// We should probably do this for all the variable types ..
for (TypedName z : span.keySet()) {
for (RatVect rv: res) {
if (! rv.containsKey(z)) {
if (z.type == NamedType.BOOL) {
rv.put(z, GlobalState.oracle().nextBoolean() ? BigFraction.ONE : BigFraction.ZERO);
} else {
rv.put(z, Rat.biasedRandom(z.type, biased, 0, span.get(z).min, span.get(z).max));
}
}
}
}
//System.out.println(ID.location() + "Vector : "+ res);
return res;
} catch (EmptyIntervalException e) {
throw new IllegalArgumentException(e);
// tries--;
// if (tries <= 0) throw e;
// continue;
}
}
}
public Collection<VariableID> unboundVariables() {
Set<VariableID> bound = new HashSet<>();
Set<VariableID> used = new HashSet<>();
for (Variable v: this) {
bound.add(v.vid);
}
for (Variable v: this) {
used = v.updateVariableSet(used);
}
used.removeAll(bound);
return used;
}
public Map<VariableID,RegionBounds> intervalBounds() {
Map<VariableID,RegionBounds> res = new HashMap<>();
for (Variable v: this) {
RegionBounds b = v.intervalBounds(res);
res.put(v.vid, b);
}
return res;
}
public SolverResults optimize(SolverResults sln, PolyFunctionMap fmap, RatSignal target) {
RatSignal res = new RatSignal(sln.cex);
RatVect tempVars = new RatVect();
VariableList z = new VariableList(this);
// We need to do this top to bottom.
Collections.reverse(z);
while (! z.isEmpty()) {
Variable v = z.poll();
RegionBounds interval;
BigFraction value;
if (v instanceof VariablePhantom) continue;
if (v instanceof VariableBoolean) {
value = v.vid.cex;
int time = v.vid.name.time;
TypedName tname = v.vid.name.name;
if (time >= 0) {
res.put(v.vid.name.time,v.vid.name.name,value);
} else {
tempVars.put(tname, value);
}
} else {
try {
interval = v.constraintBounds().fix(v.vid.name.name.type);
} catch (EmptyIntervalException e) {
System.out.println(ID.location() + "Interval Bound Violation on " + v);
throw e;
}
int time = v.vid.name.time;
TypedName tname = v.vid.name.name;
NamedType type = v.vid.name.name.type;
// TODO: Using only variable type I think we want to differentiate between
// variables that map back into the model and those that do not. Here,
// especially, we want to know the variables used in UF generalization.
if (time >= 0) {
value = interval.optimize(type,target.get(time).get(tname));
res.put(v.vid.name.time,v.vid.name.name,value);
} else {
// You could use a random value here .. because what we are doing is kinda silly.
// Or just leave it unconstrained.
value = interval.optimize(type, v.vid.getCex());
tempVars.put(tname, value);
}
// Now restrict the remaining constraints so that
// they always at least contain "value"
RestrictionResult rr = v.mustContain(new PolyBase(value));
v = rr.newConstraint;
for (Variable r: rr.restrictionList) {
z = restrict(r,z.iterator());
}
}
// assert(v.evalCEX(ctx)) : "Failure to preserve " + v + " with " + value + " under " + ctx;
}
fmap.updateFunctions(tempVars, sln.fns);
return new SolverResults(sln.time,res,sln.fns);
}
public int[] gradiantToDirectionMatrix(AbstractPoly gradiant) {
int direction[] = new int[this.size()];
Iterator<Variable> it = this.descendingIterator();
int index = this.size();
while (it.hasNext()) {
index--;
Variable v = it.next();
int sign = gradiant.getCoefficient(v.vid).signum();
direction[index] = sign;
AbstractPoly bound = v.maxBound(sign);
gradiant = gradiant.remove(v.vid);
BigFraction N = gradiant.dot(bound);
BigFraction D = bound.dot(bound);
gradiant = gradiant.subtract(bound.divide(N.divide(D)));
if (gradiant.isConstant()) break;
}
while (it.hasNext()) {
index--;
it.next();
direction[index] = 1;
}
assert(index == 0);
return direction;
}
public Map<VariableID,BigFraction> maximize(int direction[]) {
int index = 0;
Map<VariableID,BigFraction> ctx = new HashMap<>();
for (Variable v: this) {
BigFraction value = v.maxValue(direction[index], ctx);
ctx.put(v.vid, value);
index++;
}
return ctx;
}
public List<Variable> getTargets() {
List<Variable> res = new ArrayList<>();
for (Variable v: this) {
if (v instanceof VariableInterval) {
VariableInterval vi = (VariableInterval) v;
if (vi.gt.isTarget()) res.add(vi.gt);
if (vi.lt.isTarget()) res.add(vi.lt);
} else if (v.isTarget()) {
res.add(v);
}
}
return res;
}
public List<Variable> getArtifacts() {
List<Variable> res = new ArrayList<>();
for (Variable v: this) {
if (v instanceof VariableInterval) {
VariableInterval vi = (VariableInterval) v;
if (vi.gt.isArtifact()) res.add(vi.gt);
if (vi.lt.isArtifact()) res.add(vi.lt);
} else if (v.isArtifact()) {
res.add(v);
}
}
return res;
}
}
|
package strings;
public class p226g30b {
public static void main(String[] args)
{
String str="ABCDEFGHIJKLMNO";
int i,j,x=0;
int len=str.length();
for(i=0;i<len;i++)
{
for(j=0;j<=i;j++)
{
System.out.print(str.charAt(x)+" ");
x++;
}
System.out.println();
}//what man???why????
}
}
|
package dev.morphia.query.experimental.updates;
import dev.morphia.internal.PathTarget;
import dev.morphia.query.OperationTarget;
import org.bson.Document;
/**
* Defines the $currentDate operator
*
* @since 2.0
*/
public class CurrentDateOperator extends UpdateOperator {
private TypeSpecification typeSpec = TypeSpecification.DATE;
/**
* Creates an operator for a field
*
* @param field the field to update
*/
protected CurrentDateOperator(final String field) {
super("$currentDate", field, field);
}
@Override
public OperationTarget toTarget(final PathTarget pathTarget) {
return new OperationTarget(pathTarget, typeSpec.toTarget());
}
/**
* Sets the type of value to set when updating the field
*
* @param type the type to use
* @return this
*/
public CurrentDateOperator type(final TypeSpecification type) {
this.typeSpec = type;
return this;
}
/**
* Type type options when setting the current date
*/
public enum TypeSpecification {
DATE {
@Override
Object toTarget() {
return true;
}
},
TIMESTAMP {
@Override
Object toTarget() {
return new Document("$type", "timestamp");
}
};
abstract Object toTarget();
}
}
|
package com.kanghanbin.wanandroid.http;
import com.blankj.utilcode.util.NetworkUtils;
import com.kanghanbin.wanandroid.BuildConfig;
import com.kanghanbin.wanandroid.util.Constant;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* 创建时间:2018/10/19
* 编写人:kanghb
* 功能描述:
*/
public class RetrofitHelper {
private static RetrofitHelper mRetrofitHelper;
private Retrofit mRetrofit;
private long CONNECT_TIME = 60L;
private long READ_TIME = 30L;
private long WRITE_TIME = 30L;
private RetrofitHelper() {
initRetrofit();
}
private void initRetrofit() {
mRetrofit = new Retrofit.Builder().baseUrl(Constant.BaseUrl)
.client(getOkHttpClient())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private OkHttpClient getOkHttpClient() {
File file = new File(Constant.PATH_CACHE);
Cache cache = new Cache(file, 1024 * 1024 * 50);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(CONNECT_TIME, TimeUnit.SECONDS)
.readTimeout(READ_TIME, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIME, TimeUnit.SECONDS)
.addInterceptor(new CacheInterceptor())
.addInterceptor(new ReadCookiesInterceptor())
.addInterceptor(new SaveCookiesInterceptor())
.cache(cache);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
}
return builder.build();
}
public static RetrofitHelper getInstance() {
if (mRetrofitHelper == null) {
synchronized (RetrofitHelper.class) {
if (mRetrofitHelper == null) {
mRetrofitHelper = new RetrofitHelper();
}
}
}
return mRetrofitHelper;
}
class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
int maxAge = 60 * 60;
int maxStale = 60 * 60 * 24 * 28;
Request request = chain.request();
if (!NetworkUtils.isConnected()) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
Response response = chain.proceed(request);
if (NetworkUtils.isConnected()) {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return response;
}
}
public ApiService getApiService() {
return mRetrofit.create(ApiService.class);
}
}
|
package deltix.qsrv.hf.tickdb.pub.topic.exception;
/**
* Internal marker interface for topic-related exceptions that are part of topic API.
*
* @author Alexei Osipov
*/
public interface TopicApiException {
}
|
package com.zf.plugins.param.init.holder.viewmodel.type;
import com.zf.plugins.param.init.AnnotationEnv;
import com.zf.plugins.param.init.holder.viewmodel.ViewModelParamHolder;
import com.zf.plugins.param.init.holder.action.ViewModelCreationHolder;
import javax.lang.model.element.Element;
public class ViewModelParamArrayListStringHolder extends ViewModelParamHolder {
private ViewModelParamArrayListStringHolder(AnnotationEnv annotationEnv, Element element,boolean isSupportV4, boolean isAndroidX) {
super(annotationEnv, element,isSupportV4,isAndroidX);
}
public static class CreationHolder extends ViewModelCreationHolder<ViewModelParamArrayListStringHolder> {
public CreationHolder(AnnotationEnv annotationEnv, Element element,boolean isSupportV4, boolean isAndroidX) {
super(annotationEnv, element,isSupportV4,isAndroidX);
}
public ViewModelParamArrayListStringHolder getHolder() {
return new ViewModelParamArrayListStringHolder(this.annotationEnv, this.element,isSupportV4,isAndroidX);
}
}
}
|
package lrg.dude.duplication;
public class PropertyDTO {
public PropertyDTO(String file, String name, String category, int value) {
this.file = file;
this.name = name;
this.category = category;
this.value = value;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
private String file;
private String name;
private String category;
private int value;
}
|
package com.company.abstractfactory.iterator;
import java.util.Collection;
import java.util.Map;
//具体工厂
public class IteratorFactory<T> implements IIteratorFactory<T>{
@Override
public IteratorMap<T> iteratorMap(Map<T,Object> m) {
return new IteratorMap<T>(m);
}
@Override
public IteratorCollection<T> iteratorCollection(Collection<T> c) {
return new IteratorCollection<T>(c);
}
}
|
package com.indeed.proctor.common;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.indeed.proctor.common.el.MulticontextReadOnlyVariableMapper;
import com.indeed.proctor.common.model.Allocation;
import com.indeed.proctor.common.model.Audit;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import com.indeed.proctor.common.model.Payload;
import com.indeed.proctor.common.model.Range;
import com.indeed.proctor.common.model.TestBucket;
import com.indeed.proctor.common.model.TestDefinition;
import com.indeed.proctor.common.model.TestMatrixArtifact;
import com.indeed.proctor.common.model.TestMatrixDefinition;
import com.indeed.proctor.common.model.TestMatrixVersion;
import com.indeed.proctor.common.model.TestType;
import org.apache.commons.lang3.StringUtils;
import org.apache.el.ExpressionFactoryImpl;
import org.apache.log4j.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.FunctionMapper;
import javax.el.ValueExpression;
import javax.el.VariableMapper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
/**
* Helper functions mostly to verify TestMatrix instances.
*/
public abstract class ProctorUtils {
private static final ObjectMapper OBJECT_MAPPER_NON_AUTOCLOSE = Serializers
.lenient()
.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
private static final ObjectWriter OBJECT_WRITER = OBJECT_MAPPER_NON_AUTOCLOSE.writerWithDefaultPrettyPrinter();
private static final ObjectMapper OBJECT_MAPPER = Serializers.lenient();
private static final Logger LOGGER = Logger.getLogger(ProctorUtils.class);
private static final SpecificationGenerator SPECIFICATION_GENERATOR = new SpecificationGenerator();
public static MessageDigest createMessageDigest() {
try {
return MessageDigest.getInstance("MD5");
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException("Impossible no MD5", e);
}
}
@Nonnull
public static Map<String, ValueExpression> convertToValueExpressionMap(
@Nonnull final ExpressionFactory expressionFactory,
@Nonnull final Map<String, Object> values
) {
final Map<String, ValueExpression> context = new HashMap<>(values.size());
for (final Entry<String, Object> entry : values.entrySet()) {
final ValueExpression ve = expressionFactory.createValueExpression(entry.getValue(), Object.class);
context.put(entry.getKey(), ve);
}
return context;
}
@SuppressWarnings("UnusedDeclaration") // TODO Remove?
public static String convertToArtifact(@Nonnull final TestMatrixVersion testMatrix) throws IOException {
try (final StringWriter sw = new StringWriter()) {
final TestMatrixArtifact artifact = convertToConsumableArtifact(testMatrix);
serializeArtifact(sw, artifact);
return sw.toString();
}
}
/**
* @deprecated Use serialization library like jackson
*/
@Deprecated
public static void serializeArtifact(final Writer writer, final TestMatrixArtifact artifact) throws IOException {
serializeObject(writer, artifact);
}
/**
* @deprecated Use serialization library like jackson
*/
@Deprecated
public static void serializeArtifact(final JsonGenerator jsonGenerator, final Proctor proctor) throws IOException {
jsonGenerator.writeObject(proctor.getArtifact());
}
/**
* @deprecated Use serialization library like jackson
*/
@Deprecated
@SuppressWarnings("UnusedDeclaration") // TODO Remove?
public static void serializeTestDefinition(final Writer writer, final TestDefinition definition) throws IOException {
serializeObject(writer, definition);
}
/**
* @deprecated Use serialization library like jackson
*/
@Deprecated
@SuppressWarnings("UnusedDeclaration")
public static JsonNode readJsonFromFile(final File input) throws IOException {
return OBJECT_MAPPER.readValue(input, JsonNode.class);
}
/**
* @deprecated Use serialization library like jackson
*/
@Deprecated
public static void serializeTestSpecification(final Writer writer, final TestSpecification specification) throws IOException {
serializeObject(writer, specification);
}
private static <T> void serializeObject(final Writer writer, final T artifact) throws IOException {
OBJECT_WRITER.writeValue(writer, artifact);
}
@Nonnull
public static TestMatrixArtifact convertToConsumableArtifact(@Nonnull final TestMatrixVersion testMatrix) {
final Audit audit = new Audit();
final Date published = Preconditions.checkNotNull(testMatrix.getPublished(), "Missing publication date");
audit.setUpdated(published.getTime());
audit.setVersion(testMatrix.getVersion());
audit.setUpdatedBy(testMatrix.getAuthor());
final TestMatrixArtifact artifact = new TestMatrixArtifact();
artifact.setAudit(audit);
final TestMatrixDefinition testMatrixDefinition = Preconditions.checkNotNull(testMatrix.getTestMatrixDefinition(), "Missing test matrix definition");
final Map<String, TestDefinition> testDefinitions = testMatrixDefinition.getTests();
final Map<String, ConsumableTestDefinition> consumableTestDefinitions = Maps.newLinkedHashMap();
for (final Entry<String, TestDefinition> entry : testDefinitions.entrySet()) {
final TestDefinition td = entry.getValue();
final ConsumableTestDefinition ctd = convertToConsumableTestDefinition(td);
consumableTestDefinitions.put(entry.getKey(), ctd);
}
artifact.setTests(consumableTestDefinitions);
return artifact;
}
@Nonnull
public static ConsumableTestDefinition convertToConsumableTestDefinition(@Nonnull final TestDefinition td) {
final Map<String, Object> specialConstants = td.getSpecialConstants();
final List<String> ruleComponents = Lists.newArrayList();
//noinspection unchecked
final List<String> countries = (List<String>) specialConstants.get("__COUNTRIES");
if (countries != null) {
ruleComponents.add("proctor:contains(__COUNTRIES, country)");
}
final String rawRule = removeElExpressionBraces(td.getRule());
if (!StringUtils.isBlank(rawRule)) {
ruleComponents.add(rawRule);
}
final String rule;
if (ruleComponents.isEmpty()) {
rule = null;
} else {
rule = "${" + String.join(" && ", ruleComponents) + '}';
}
final List<Allocation> allocations = td.getAllocations();
for (final Allocation alloc : allocations) {
final String rawAllocRule = removeElExpressionBraces(alloc.getRule());
if (StringUtils.isBlank(rawAllocRule)) {
alloc.setRule(null);
} else {
// ensure that all rules in the generated test-matrix are wrapped in "${" ... "}"
if (!(rawAllocRule.startsWith("${") && rawAllocRule.endsWith("}"))) {
final String newAllocRule = "${" + rawAllocRule + "}";
alloc.setRule(newAllocRule);
}
}
}
final Map<String, Object> constants = Maps.newLinkedHashMap();
constants.putAll(td.getConstants());
constants.putAll(specialConstants);
return new ConsumableTestDefinition(td.getVersion(), rule, td.getTestType(), td.getSalt(), td.getBuckets(),
allocations, td.getSilent(), constants, td.getDescription(), td.getMetaTags());
}
public static ProctorSpecification readSpecification(final File inputFile) {
final ProctorSpecification spec;
InputStream stream = null;
try {
stream = new BufferedInputStream(new FileInputStream(inputFile));
spec = readSpecification(stream);
} catch (final IOException e) {
throw new RuntimeException("Unable to read test set from " + inputFile, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (final IOException e) {
LOGGER.error("Suppressing throwable thrown when closing " + inputFile, e);
}
}
}
return spec;
}
public static ProctorSpecification readSpecification(final InputStream inputFile) {
final ProctorSpecification spec;
try {
spec = OBJECT_MAPPER_NON_AUTOCLOSE.readValue(inputFile, ProctorSpecification.class);
} catch (final IOException e) {
throw new RuntimeException("Unable to read test set from " + inputFile, e);
}
return spec;
}
/**
* Verifies that the TestMatrix is compatible with all the required tests.
* Removes non-required tests from the TestMatrix
* Replaces invalid or missing tests (buckets are not compatible) with
* default implementation returning the fallback value see defaultFor
*
* @param testMatrix the {@link TestMatrixArtifact} to be verified.
* @param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
* @param requiredTests a {@link Map} of required test. The {@link TestSpecification} would be verified
* @param functionMapper a given el {@link FunctionMapper}
* @return a {@link ProctorLoadResult} to describe the result of verification. It contains errors of verification and a list of missing test.
*/
public static ProctorLoadResult verifyAndConsolidate(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final FunctionMapper functionMapper
) {
return verifyAndConsolidate(
testMatrix,
matrixSource,
requiredTests,
functionMapper,
ProvidedContext.nonEvaluableContext(),
Collections.emptySet()
);
}
public static ProctorLoadResult verifyAndConsolidate(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext
) {
return verifyAndConsolidate(
testMatrix,
matrixSource,
requiredTests,
functionMapper,
providedContext,
Collections.emptySet()
);
}
public static ProctorLoadResult verifyAndConsolidate(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext,
@Nonnull final Set<String> dynamicTests
) {
final ProctorLoadResult result = verify(testMatrix, matrixSource, requiredTests, functionMapper, providedContext, dynamicTests);
final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();
// Remove any invalid tests so that any required ones will be replaced with default values during the
// consolidation below (just like missing tests). Any non-required tests can safely be ignored.
for (final String invalidTest : result.getTestsWithErrors()) {
// TODO - mjs - gross that this depends on the mutability of the returned map, but then so does the
// consolidate method below.
definedTests.remove(invalidTest);
}
// Remove any invalid dynamic tests. This ones won't be replaced with default values
// because they are not required tests.
for (final String invalidDynamicTest : result.getDynamicTestWithErrors()) {
definedTests.remove(invalidDynamicTest);
}
consolidate(testMatrix, requiredTests, dynamicTests);
return result;
}
/**
* Verifies that the TestMatrix is correct and sane without using a specification.
* The Proctor API doesn't use a test specification so that it can serve all tests in the matrix
* without restriction.
* Does a limited set of sanity checks that are applicable when there is no specification,
* and thus no required tests or provided context.
*
* @param testMatrix the {@link TestMatrixArtifact} to be verified.
* @param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
* @return a {@link ProctorLoadResult} to describe the result of verification. It contains errors of verification and a list of missing test.
*/
public static ProctorLoadResult verifyWithoutSpecification(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource
) {
final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();
for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {
final String testName = entry.getKey();
final ConsumableTestDefinition testDefinition = entry.getValue();
try {
verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);
} catch (final IncompatibleTestMatrixException e) {
LOGGER.info(String.format("Unable to load test matrix for %s", testName), e);
resultBuilder.recordError(testName, e);
}
}
return resultBuilder.build();
}
/**
* verify with default function mapper and empty context and no dynamic tests
*/
public static ProctorLoadResult verify(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests
) {
return verify(
testMatrix,
matrixSource,
requiredTests,
RuleEvaluator.FUNCTION_MAPPER,
ProvidedContext.nonEvaluableContext(), // use default function mapper
Collections.emptySet()
);
}
/**
* verify with default function mapper and empty context
*/
public static ProctorLoadResult verify(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final Set<String> dynamicTests
) {
return verify(
testMatrix,
matrixSource,
requiredTests,
RuleEvaluator.FUNCTION_MAPPER,
ProvidedContext.nonEvaluableContext(), // use default function mapper
dynamicTests
);
}
/**
* verify with default function mapper and no dynamic tests
*/
public static ProctorLoadResult verify(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext
) {
return verify(
testMatrix,
matrixSource,
requiredTests,
functionMapper,
providedContext,
Collections.emptySet()
);
}
/**
* Does not mutate the TestMatrix.
* Verifies that the test matrix contains all the required tests and that
* each required test is valid.
*
* @param testMatrix the {@link TestMatrixArtifact} to be verified.
* @param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
* @param requiredTests a {@link Map} of required test. The {@link TestSpecification} would be verified
* @param functionMapper a given el {@link FunctionMapper}
* @param providedContext a {@link Map} containing variables describing the context in which the request is executing. These will be supplied to verifying all rules.
* @param dynamicTests a {@link Set} of dynamic tests determined by filters.
* @return a {@link ProctorLoadResult} to describe the result of verification. It contains errors of verification and a list of missing test.
*/
public static ProctorLoadResult verify(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext,
@Nonnull final Set<String> dynamicTests
) {
final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();
final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();
for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {
final String testName = entry.getKey();
if (requiredTests.containsKey(testName)) {
// required in specification
try {
verifyRequiredTest(
testName,
definedTests.get(testName),
requiredTests.get(testName),
matrixSource,
functionMapper,
providedContext
);
} catch (final IncompatibleTestMatrixException e) {
resultBuilder.recordError(testName, e);
}
} else if (dynamicTests.contains(testName)) {
// resolved by dynamic filter
try {
verifyDynamicTest(
testName,
definedTests.get(testName),
matrixSource,
functionMapper,
providedContext
);
} catch (final IncompatibleTestMatrixException e) {
resultBuilder.recordIncompatibleDynamicTest(testName, e);
}
}
}
final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());
resultBuilder.recordAllMissing(missingTests);
resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());
return resultBuilder.build();
}
/**
* Verifies that a single required test is valid against {@link TestSpecification}
* and {@link FunctionMapper} and {@link ProvidedContext}.
*
* @param testName the name of the test
* @param testDefinition {@link ConsumableTestDefinition} of the test
* @param testSpecification {@link TestSpecification} defined in an application for the test
* @param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
* @param functionMapper a given el {@link FunctionMapper}
* @param providedContext a {@link Map} containing variables describing the context in which the request is executing.
* These will be supplied to verifying all rules.
* @throws IncompatibleTestMatrixException if validation is failed.
*/
private static void verifyRequiredTest(
@Nonnull final String testName,
@Nonnull final ConsumableTestDefinition testDefinition,
@Nonnull final TestSpecification testSpecification,
@Nonnull final String matrixSource,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext
) throws IncompatibleTestMatrixException {
final Set<Integer> knownBucketValues = new HashSet<>();
for (final Integer bucketValue : testSpecification.getBuckets().values()) {
if (bucketValue == null) {
throw new IncompatibleTestMatrixException("Test specification of " + testName + " has null in buckets");
}
if (!knownBucketValues.add(bucketValue)) {
throw new IncompatibleTestMatrixException(
"Test specification of " + testName + " has duplicated buckets for value " + bucketValue
);
}
}
verifyTest(
testName,
testDefinition,
testSpecification,
knownBucketValues,
matrixSource,
functionMapper,
providedContext
);
}
/**
* Verifies that a single dynamic test is valid against {@link FunctionMapper} and {@link ProvidedContext}.
*
* @param testName the name of the test
* @param testDefinition {@link ConsumableTestDefinition} of the test
* @param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
* @param functionMapper a given el {@link FunctionMapper}
* @param providedContext a {@link Map} containing variables describing the context in which the request is executing.
* These will be supplied to verifying all rules.
* @throws IncompatibleTestMatrixException if validation is failed.
*/
private static void verifyDynamicTest(
@Nonnull final String testName,
@Nonnull final ConsumableTestDefinition testDefinition,
@Nonnull final String matrixSource,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext
) throws IncompatibleTestMatrixException {
verifyTest(
testName,
testDefinition,
// hack: use empty test spec to not verify buckets and payloads
new TestSpecification(),
// this parameter is ignored
Collections.emptySet(),
matrixSource,
functionMapper,
providedContext
);
}
private static void verifyTest(
@Nonnull final String testName,
@Nonnull final ConsumableTestDefinition testDefinition,
@Nonnull final TestSpecification testSpecification,
@Nonnull final Set<Integer> knownBuckets,
@Nonnull final String matrixSource,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext
) throws IncompatibleTestMatrixException {
final List<Allocation> allocations = testDefinition.getAllocations();
final TestType declaredType = testDefinition.getTestType();
if (!TestType.all().contains(declaredType)) {
throw new IncompatibleTestMatrixException(String.format(
"Test '%s' is included in the application specification but refers to unknown id type '%s'.",
testName, declaredType));
}
verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition, functionMapper, providedContext);
if (!testSpecification.getBuckets().isEmpty()) {
/*
* test the matrix for adherence to this application's requirements, if buckets were specified
*/
final Set<Integer> unknownBuckets = Sets.newHashSet();
for (final Allocation allocation : allocations) {
final List<Range> ranges = allocation.getRanges();
// ensure that each range refers to a known bucket
for (final Range range : ranges) {
// Externally consistent (application's requirements)
if (!knownBuckets.contains(range.getBucketValue())) {
// If the bucket has a positive allocation, add it to the list of unknownBuckets
if (range.getLength() > 0) {
unknownBuckets.add(range.getBucketValue());
}
}
}
}
if (!unknownBuckets.isEmpty()) {
throw new IncompatibleTestMatrixException("Allocation range in " + testName + " from " + matrixSource + " refers to unknown bucket value(s) " + unknownBuckets + " with length > 0");
}
}
final PayloadSpecification payloadSpec = testSpecification.getPayload();
if (payloadSpec != null) {
final String specifiedPayloadTypeName = Preconditions.checkNotNull(payloadSpec.getType(), "Missing payload spec type");
final PayloadType specifiedPayloadType = PayloadType.payloadTypeForName(specifiedPayloadTypeName);
final Map<String, String> specificationPayloadTypes = payloadSpec.getSchema();
if (specifiedPayloadType == PayloadType.MAP) {
if (specificationPayloadTypes.isEmpty()
|| specificationPayloadTypes == null) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected non empty payload");
}
}
if (specifiedPayloadType == null) {
// This is probably redundant vs. TestGroupsGenerator.
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " test specification payload type unknown: " + specifiedPayloadTypeName);
}
final String payloadValidatorRule = payloadSpec.getValidator();
// TODO(pwp): add some test constants?
final RuleEvaluator ruleEvaluator = makeRuleEvaluator(RuleEvaluator.EXPRESSION_FACTORY, functionMapper);
for (final TestBucket bucket : testDefinition.getBuckets()) {
final Payload payload = bucket.getPayload();
if (payload != null) {
if (!Payload.hasType(payload, specifiedPayloadType)) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong type: " + bucket);
}
if (specifiedPayloadType == PayloadType.MAP) {
checkMapPayloadTypes(payload, specificationPayloadTypes, matrixSource, testName, specifiedPayloadType, payloadValidatorRule, bucket, functionMapper);
} else if (payloadValidatorRule != null) {
final boolean payloadIsValid = evaluatePayloadValidator(ruleEvaluator, payloadValidatorRule, payload);
if (!payloadIsValid) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " payload validation rule " + payloadValidatorRule + " failed for test bucket: " + bucket);
}
}
}
}
}
}
private static void checkMapPayloadTypes(final Payload payload,
final Map<String, String> specificationPayloadTypes,
final String matrixSource,
final String testName,
final PayloadType specifiedPayloadType,
final String payloadValidatorRule,
final TestBucket bucket,
final FunctionMapper functionMapper) throws IncompatibleTestMatrixException {
final RuleEvaluator ruleEvaluator = makeRuleEvaluator(RuleEvaluator.EXPRESSION_FACTORY, functionMapper);
if (payload.getMap() == null) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong type: " + bucket);
}
if (specificationPayloadTypes.size() > payload.getMap().size()) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of equal size to specification " + specifiedPayloadType + " but matrix has a test bucket payload with wrong type size: " + bucket);
}
final Map<String, Object> bucketPayloadMap = payload.getMap();
for (final Entry<String, String> specificationPayloadEntry : specificationPayloadTypes.entrySet()) {
if (!bucketPayloadMap.containsKey(specificationPayloadEntry.getKey())) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of same order and variable names as specificied in " + specifiedPayloadType + " but matrix has a test bucket payload with wrong type: " + bucket);
}
final PayloadType expectedPayloadType;
try {
expectedPayloadType = PayloadType.payloadTypeForName(specificationPayloadEntry.getValue());
} catch (final IllegalArgumentException e) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " specification payload type unknown in: " + specifiedPayloadType.payloadTypeName);
}
if (expectedPayloadType == PayloadType.MAP) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " specification payload type has unallowed nested map types: " + specifiedPayloadType.payloadTypeName);
}
final Object actualPayload = bucketPayloadMap.get(specificationPayloadEntry.getKey());
if (actualPayload instanceof ArrayList) {
for (final Object actualPayloadEntry : (ArrayList) actualPayload) {
final Class actualClazz = actualPayloadEntry.getClass();
if (PayloadType.STRING_ARRAY == expectedPayloadType) {
if (!String.class.isAssignableFrom(actualClazz)) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong nested type: " + bucket);
}
} else if (PayloadType.LONG_ARRAY == expectedPayloadType
|| PayloadType.DOUBLE_ARRAY == expectedPayloadType) {
if (!Number.class.isAssignableFrom(actualClazz)) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong nested type: " + bucket);
}
} else {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong nested type: " + bucket);
}
}
} else if (PayloadType.DOUBLE_ARRAY == expectedPayloadType
|| PayloadType.STRING_ARRAY == expectedPayloadType
|| PayloadType.LONG_ARRAY == expectedPayloadType) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong nested type: " + bucket);
} else if (PayloadType.DOUBLE_VALUE == expectedPayloadType
|| PayloadType.LONG_VALUE == expectedPayloadType) {
final Class actualClazz = actualPayload.getClass();
if (!Number.class.isAssignableFrom(actualClazz)) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong nested type: " + bucket);
}
} else {
try {
if (!Class.forName("java.lang." + expectedPayloadType.javaClassName).isInstance(actualPayload)) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " expected payload of type " + specifiedPayloadType.payloadTypeName + " but matrix has a test bucket payload with wrong nested type: " + bucket);
}
} catch (final ClassNotFoundException e) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " incompatible payload type?");
}
}
}
if (payloadValidatorRule != null) {
final boolean payloadIsValid = evaluatePayloadMapValidator(ruleEvaluator, payloadValidatorRule, payload);
if (!payloadIsValid) {
throw new IncompatibleTestMatrixException("For test " + testName + " from " + matrixSource + " payload validation rule " + payloadValidatorRule + " failed for test bucket: " + bucket);
}
}
}
/**
* minimizes TestMatrix by removing non-required test definitions, also add definitions from missing tests
*/
private static void consolidate(
@Nonnull final TestMatrixArtifact testMatrix,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final Set<String> dynamicTests
) {
final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();
// Sets.difference returns a "view" on the original set, which would require concurrent modification while iterating (copying the set will prevent this)
final Set<String> toRemove = ImmutableSet.copyOf(
Sets.difference(
definedTests.keySet(),
Sets.union(
requiredTests.keySet(),
dynamicTests
)
)
);
for (final String testInMatrixNotRequired : toRemove) {
// we don't care about this test
definedTests.remove(testInMatrixNotRequired);
}
// Next, for any required tests that are missing, ensure that
// there is a nonnull test definition in the matrix
final Set<String> missing =
ImmutableSet.copyOf(Sets.difference(requiredTests.keySet(), definedTests.keySet()));
for (final String testNotInMatrix : missing) {
definedTests.put(testNotInMatrix, defaultFor(testNotInMatrix, requiredTests.get(testNotInMatrix)));
}
// Now go through definedTests: for each test, if the test spec
// didn't ask for a payload, then remove any payload that is in
// the test matrix. If buckets exist in the specification that
// do not in the matrix, add buckets with null payloads to allow
// forcing buckets that aren't in the matrix but are in the spec.
for (final Entry<String, ConsumableTestDefinition> next : definedTests.entrySet()) {
final String testName = next.getKey();
final ConsumableTestDefinition testDefinition = next.getValue();
if (!requiredTests.containsKey(testName)) {
// We don't care here about dynamically resolved tests
continue;
}
final TestSpecification testSpec = requiredTests.get(testName);
final boolean noPayloads = (testSpec.getPayload() == null);
final Set<Integer> bucketValues = Sets.newHashSet();
List<TestBucket> buckets = testDefinition.getBuckets();
for (final TestBucket bucket : buckets) {
// Note bucket values that exist in matrix.
bucketValues.add(bucket.getValue());
}
if (noPayloads) {
testDefinition.setBuckets(
buckets.stream()
.map(bucket ->
TestBucket.builder()
.from(bucket)
.payload(null) // stomp the unexpected payload if exists.
.build()
)
.collect(Collectors.toList())
);
}
boolean replaceBuckets = false;
final Map<String, Integer> specBuckets = testSpec.getBuckets();
for (final Entry<String, Integer> bucketSpec : specBuckets.entrySet()) {
if (!bucketValues.contains(bucketSpec.getValue())) {
if (!replaceBuckets) {
buckets = Lists.newArrayList(buckets);
replaceBuckets = true;
}
buckets.add(new TestBucket(bucketSpec.getKey(), bucketSpec.getValue(), null, null));
}
}
if (replaceBuckets) {
testDefinition.setBuckets(buckets);
}
}
}
@Nonnull
private static ConsumableTestDefinition defaultFor(
final String testName,
@Nonnull final TestSpecification testSpecification
) {
final String missingTestSoleBucketName = "inactive";
final String missingTestSoleBucketDescription = "fallback because missing in matrix";
final int fallbackValue = testSpecification.getFallbackValue();
final Allocation allocation = new Allocation(
null,
Collections.singletonList(new Range(fallbackValue, 1.0)));
return new ConsumableTestDefinition(
"default",
null,
TestType.RANDOM,
testName,
ImmutableList.of(new TestBucket(
missingTestSoleBucketName,
fallbackValue,
missingTestSoleBucketDescription)),
// Force a nonnull allocation just in case something somewhere assumes 1.0 total allocation
Collections.singletonList(allocation),
// non-silent, though typically fallbackValue -1 has same effect
false,
Collections.emptyMap(),
testName,
emptyList());
}
public static ProvidedContext convertContextToTestableMap(final Map<String, String> providedContext) {
return convertContextToTestableMap(providedContext, Collections.emptyMap());
}
public static ProvidedContext convertContextToTestableMap(
final Map<String, String> providedContext,
final Map<String, Object> ruleVerificationContext
) {
final ExpressionFactory expressionFactory = new ExpressionFactoryImpl();
final Map<String, Object> primitiveVals = new HashMap<>();
primitiveVals.put("int", 0);
primitiveVals.put("integer", 0);
primitiveVals.put("long", (long) 0);
primitiveVals.put("bool", true);
primitiveVals.put("boolean", true);
primitiveVals.put("short", (short) 0);
primitiveVals.put("string", "");
primitiveVals.put("double", (double) 0);
primitiveVals.put("char", "");
primitiveVals.put("character", "");
primitiveVals.put("byte", (byte) 0);
if (providedContext != null) {
final Map<String, Object> newProvidedContext = new HashMap<>();
final Set<String> uninstantiatedIdentifiers = Sets.newHashSet();
for (final Entry<String, String> entry : providedContext.entrySet()) {
final String identifier = entry.getKey();
Object toAdd = null;
if (ruleVerificationContext.containsKey(identifier)) {
toAdd = ruleVerificationContext.get(identifier);
LOGGER.debug(String.format("Use instance for identifier {%s} provided by user %s", identifier, toAdd));
} else {
LOGGER.debug(String.format("Identifier {%s} is not provided, instantiate it via default constructor", identifier));
final String iobjName = entry.getValue();
final String objName = iobjName;
if (primitiveVals.get(objName.toLowerCase()) != null) {
toAdd = primitiveVals.get(objName.toLowerCase());
} else {
try {
final Class clazz = Class.forName(objName);
if (clazz.isEnum()) { //If it is a user defined enum
toAdd = clazz.getEnumConstants()[0];
} else { //If it is a user defined non enum class
toAdd = clazz.newInstance();
}
} catch (final IllegalAccessException e) {
uninstantiatedIdentifiers.add(identifier);
LOGGER.debug("Couldn't access default constructor of " + iobjName + " in providedContext. Rule verification will skip this identifier - " + identifier);
} catch (final InstantiationException e) {
uninstantiatedIdentifiers.add(identifier);
//if a default constructor is not defined, use this flag to not set context and not evaluate rules
LOGGER.debug("Couldn't find default constructor for " + iobjName + " in providedContext. Rule verification will skip this identifier - " + identifier);
} catch (final ClassNotFoundException e) {
uninstantiatedIdentifiers.add(identifier);
LOGGER.error("Class not found for " + iobjName + " in providedContext");
}
}
}
newProvidedContext.put(identifier, toAdd);
}
/* evaluate the rule even if defaultConstructor method does not exist, */
return ProvidedContext.forValueExpressionMap(ProctorUtils.convertToValueExpressionMap(expressionFactory, newProvidedContext),
uninstantiatedIdentifiers);
}
return ProvidedContext.nonEvaluableContext();
}
/**
* verifyInternallyConsistentDefinition with default functionMapper, but do not evaluate rule against any context
*/
public static void verifyInternallyConsistentDefinition(
final String testName,
final String matrixSource,
@Nonnull final ConsumableTestDefinition testDefinition
) throws IncompatibleTestMatrixException {
verifyInternallyConsistentDefinition(
testName,
matrixSource,
testDefinition,
ProvidedContext.nonEvaluableContext()
);
}
/**
* verifyInternallyConsistentDefinition with default functionMapper and evaluate against context
*/
public static void verifyInternallyConsistentDefinition(
final String testName,
final String matrixSource,
@Nonnull final ConsumableTestDefinition testDefinition,
final ProvidedContext providedContext
) throws IncompatibleTestMatrixException {
verifyInternallyConsistentDefinition(
testName,
matrixSource,
testDefinition,
RuleEvaluator.FUNCTION_MAPPER,
providedContext
);
}
/**
* verify:
* - test/allocation rules has valid syntax
* - if providedContext.shouldEvaluate, also verifies that rule contains only identifiers from context
* - if providedContext.shouldEvaluate, also verifies test/allocation rule evaluates to boolean
* - buckets have same payload type
*
* @throws IncompatibleTestMatrixException on violations
*/
private static void verifyInternallyConsistentDefinition(
final String testName,
final String matrixSource,
@Nonnull final ConsumableTestDefinition testDefinition,
final FunctionMapper functionMapper,
final ProvidedContext providedContext
) throws IncompatibleTestMatrixException {
final List<Allocation> allocations = testDefinition.getAllocations();
final ExpressionFactory expressionFactory = new ExpressionFactoryImpl();
//verify test rule is valid EL
final String testRule = testDefinition.getRule();
final Map<String, ValueExpression> testConstants = ProctorUtils.convertToValueExpressionMap(expressionFactory, testDefinition.getConstants());
final VariableMapper variableMapper = new MulticontextReadOnlyVariableMapper(testConstants, providedContext.getContext());
final RuleEvaluator ruleEvaluator = new RuleEvaluator(expressionFactory, functionMapper, testDefinition.getConstants());
final ELContext elContext = ruleEvaluator.createELContext(variableMapper);
try {
RuleVerifyUtils.verifyRule(testRule, providedContext.shouldEvaluate(), expressionFactory, elContext, providedContext.getUninstantiatedIdentifiers());
} catch (final InvalidRuleException e) {
throw new IncompatibleTestMatrixException(
String.format("Invalid rule %s in %s: %s", testRule, testName, e.getMessage()), e);
}
if (allocations.isEmpty()) {
throw new IncompatibleTestMatrixException("No allocations specified in test " + testName);
}
final List<TestBucket> buckets = testDefinition.getBuckets();
/*
* test the definition for consistency with itself
*/
final Set<Integer> definedBuckets = Sets.newHashSet();
for (final TestBucket bucket : buckets) {
definedBuckets.add(bucket.getValue());
}
for (int i = 0; i < allocations.size(); i++) {
final Allocation allocation = allocations.get(i);
final List<Range> ranges = allocation.getRanges();
if ((ranges == null) || ranges.isEmpty()) {
throw new IncompatibleTestMatrixException("Allocation range has no buckets, needs to add up to 1.");
}
// ensure that each range refers to a known bucket
double bucketTotal = 0;
for (final Range range : ranges) {
bucketTotal += range.getLength();
// Internally consistent
if (!definedBuckets.contains(range.getBucketValue())) {
throw new IncompatibleTestMatrixException("Allocation range in " + testName + " from " + matrixSource + " refers to unknown bucket value " + range.getBucketValue());
}
}
// I hate floating points. TODO: extract a required precision constant/parameter?
if (bucketTotal < 0.9999 || bucketTotal > 1.0001) { // compensate for FP imprecision. TODO: determine what these bounds really should be by testing stuff
throw new IncompatibleTestMatrixException(
testName + " range with rule " + allocation.getRule() + " does not add up to 1 : "
+ ranges.stream().map(r -> Double.toString(r.getLength())).collect(joining(" + "))
+ " = " + bucketTotal
);
}
final String rule = allocation.getRule();
final boolean lastAllocation = i == (allocations.size() - 1);
final String bareRule = removeElExpressionBraces(rule);
if (!lastAllocation && StringUtils.isBlank(bareRule)) {
throw new IncompatibleTestMatrixException("Allocation[" + i + "] for test " + testName + " from " + matrixSource + " has empty rule: " + allocation.getRule());
}
try {
RuleVerifyUtils.verifyRule(rule, providedContext.shouldEvaluate(), expressionFactory, elContext, providedContext.getUninstantiatedIdentifiers());
} catch (final InvalidRuleException e) {
throw new IncompatibleTestMatrixException(
String.format("Invalid allocation rule %s in %s: %s", rule, testName, e.getMessage()), e);
}
}
/*
* When defined, within a single test, all test bucket payloads
* should be supplied; they should all have just one type each,
* and they should all be the same type.
*/
Payload nonEmptyPayload = null;
final List<TestBucket> bucketsWithoutPayloads = Lists.newArrayList();
for (final TestBucket bucket : buckets) {
final Payload p = bucket.getPayload();
if (p != null) {
if (p.numFieldsDefined() != 1) {
throw new IncompatibleTestMatrixException("Test " + testName + " from " + matrixSource + " has a test bucket payload with multiple types: " + bucket);
}
if (nonEmptyPayload == null) {
nonEmptyPayload = p;
} else if (!nonEmptyPayload.sameType(p)) {
throw new IncompatibleTestMatrixException("Test " + testName + " from " + matrixSource + " has test bucket: " + bucket + " incompatible with type of payload: " + nonEmptyPayload);
}
} else {
bucketsWithoutPayloads.add(bucket);
}
}
if ((nonEmptyPayload != null) && (!bucketsWithoutPayloads.isEmpty())) {
throw new IncompatibleTestMatrixException("Test " + testName + " from " + matrixSource + " has some test buckets without payloads: " + bucketsWithoutPayloads);
}
}
/**
* Returns flag whose value indicates if the string is null, empty or
* only contains whitespace characters
*
* @param s a string
* @return true if the string is null, empty or only contains whitespace characters
* @deprecated Use StringUtils.isBlank
*/
@Deprecated
static boolean isEmptyWhitespace(@Nullable final String s) {
return StringUtils.isBlank(s);
}
/**
* Generates a usable test specification for a given test definition
* Uses the bucket with smallest value as the fallback value
*
* @param testDefinition a {@link TestDefinition}
* @return a {@link TestSpecification} which corresponding to given test definition.
* @deprecated use SpecificationGenerator
*/
@Deprecated
public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {
return SPECIFICATION_GENERATOR.generateSpecification(testDefinition);
}
/**
* Removes the expression braces "${ ... }" surrounding the rule.
*
* @param rule a given rule String.
* @return the given rule with the most outside braces stripped
*/
@CheckForNull
static String removeElExpressionBraces(@Nullable final String rule) {
if (StringUtils.isBlank(rule)) {
return null;
}
int startchar = 0; // inclusive
int endchar = rule.length() - 1; // inclusive
// garbage free trim()
while (startchar < rule.length() && Character.isWhitespace(rule.charAt(startchar))) {
++startchar;
}
while (endchar > startchar && Character.isWhitespace(rule.charAt(endchar))) {
--endchar;
}
if (rule.regionMatches(startchar, "${", 0, 2) && rule.charAt(endchar) == '}') {
startchar += 2; // skip "${"
--endchar; // skip '}'
}
// garbage free trim()
while (startchar < rule.length() && Character.isWhitespace(rule.charAt(startchar))) {
++startchar;
}
while (endchar > startchar && Character.isWhitespace(rule.charAt(endchar))) {
--endchar;
}
if (endchar < startchar) {
// null instead of empty string for consistency with 'isEmptyWhitespace' check at the beginning
return null;
}
return rule.substring(startchar, endchar + 1);
}
// Make a new RuleEvaluator that captures the test constants.
// TODO(pwp): add some test constants?
@Nonnull
private static RuleEvaluator makeRuleEvaluator(final ExpressionFactory expressionFactory, final FunctionMapper functionMapper) {
// Make the expression evaluation context.
final Map<String, Object> testConstants = Collections.emptyMap();
return new RuleEvaluator(expressionFactory, functionMapper, testConstants);
}
private static boolean evaluatePayloadMapValidator(@Nonnull final RuleEvaluator ruleEvaluator, final String rule, @Nonnull final Payload payload) throws IncompatibleTestMatrixException {
try {
return ruleEvaluator.evaluateBooleanRule(rule, payload.getMap());
} catch (final IllegalArgumentException e) {
LOGGER.error("Unable to evaluate rule ${" + rule + "} with payload " + payload, e);
}
return true;
}
private static boolean evaluatePayloadValidator(@Nonnull final RuleEvaluator ruleEvaluator, final String rule, @Nonnull final Payload payload) throws IncompatibleTestMatrixException {
final Map<String, Object> values = Collections.singletonMap("value", payload.fetchAValue());
try {
return ruleEvaluator.evaluateBooleanRule(rule, values);
} catch (final IllegalArgumentException e) {
LOGGER.error("Unable to evaluate rule ${" + rule + "} with payload " + payload, e);
}
return false;
}
}
|
package online.qiqiang.qim.client.service;
import online.qiqiang.qim.common.vo.FriendAddVO;
import online.qiqiang.qim.common.vo.QimResponse;
import online.qiqiang.qim.common.vo.QimUserVO;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import java.util.List;
/**
* @author qiqiang
*/
public interface FriendService {
@GET("friend/{userId}")
Call<QimResponse<List<QimUserVO>>> allFriends(@Path("userId") Long userId);
@POST("friend/add")
Call<QimResponse<Void>> add(@Body FriendAddVO friendAddVO);
}
|
/**
* This class is generated by jOOQ
*/
package org.labkey.apikey.model.jooq.tables.records;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
import org.labkey.apikey.model.jooq.tables.AllowedServices;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class AllowedServicesRecord extends UpdatableRecordImpl<AllowedServicesRecord> implements Record3<String, String, String> {
private static final long serialVersionUID = 1275932371;
/**
* Setter for <code>apikey.allowed_services.apikey</code>.
*/
public void setApikey(String value) {
set(0, value);
}
/**
* Getter for <code>apikey.allowed_services.apikey</code>.
*/
public String getApikey() {
return (String) get(0);
}
/**
* Setter for <code>apikey.allowed_services.modulename</code>.
*/
public void setModulename(String value) {
set(1, value);
}
/**
* Getter for <code>apikey.allowed_services.modulename</code>.
*/
public String getModulename() {
return (String) get(1);
}
/**
* Setter for <code>apikey.allowed_services.servicename</code>.
*/
public void setServicename(String value) {
set(2, value);
}
/**
* Getter for <code>apikey.allowed_services.servicename</code>.
*/
public String getServicename() {
return (String) get(2);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record3<String, String, String> key() {
return (Record3) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<String, String, String> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<String, String, String> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field1() {
return AllowedServices.ALLOWED_SERVICES.APIKEY;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return AllowedServices.ALLOWED_SERVICES.MODULENAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return AllowedServices.ALLOWED_SERVICES.SERVICENAME;
}
/**
* {@inheritDoc}
*/
@Override
public String value1() {
return getApikey();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getModulename();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getServicename();
}
/**
* {@inheritDoc}
*/
@Override
public AllowedServicesRecord value1(String value) {
setApikey(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public AllowedServicesRecord value2(String value) {
setModulename(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public AllowedServicesRecord value3(String value) {
setServicename(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public AllowedServicesRecord values(String value1, String value2, String value3) {
value1(value1);
value2(value2);
value3(value3);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached AllowedServicesRecord
*/
public AllowedServicesRecord() {
super(AllowedServices.ALLOWED_SERVICES);
}
/**
* Create a detached, initialised AllowedServicesRecord
*/
public AllowedServicesRecord(String apikey, String modulename, String servicename) {
super(AllowedServices.ALLOWED_SERVICES);
set(0, apikey);
set(1, modulename);
set(2, servicename);
}
}
|
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.internal.executor.api;
/**
* Possible statuses of the request
*
*/
public enum STATUS {
QUEUED, DONE, CANCELLED, ERROR, RETRYING, RUNNING;
}
|
/*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.concurrent;
import io.netty.util.internal.UnstableApi;
/**
* Factory that creates new {@link EventExecutorChooser}s.
* EventExecutorChooser的工厂类,具体实现为DefaultEventExecutorChooserFactory
*/
@UnstableApi
public interface EventExecutorChooserFactory {
/**
* Returns a new {@link EventExecutorChooser}.
*/
EventExecutorChooser newChooser(EventExecutor[] executors);
/**
* Chooses the next {@link EventExecutor} to use.
*/
@UnstableApi
interface EventExecutorChooser {
/**
* Returns the new {@link EventExecutor} to use.
*/
EventExecutor next();
}
}
|
package com.weinyc.sa.app.engine.controller;
import com.weinyc.sa.core.engine.AbstractController;
import com.weinyc.sa.core.engine.AbstractServicer;
import com.weinyc.sa.core.annotation.ServicerType;
import com.weinyc.sa.common.util.JSONUtils;
import com.weinyc.sa.app.engine.servicer.MerchantServicer;
import com.weinyc.sa.app.model.Merchant;
public class MerchantController extends AbstractController{
@ServicerType(value="com.weinyc.sa.app.engine.servicer.MerchantServicer", spring="")
private MerchantServicer servicer;
@Override
public String getFORM_NAME () {
return "MerchantForm";
}
@Override
public String getJSP_TOGO_PERIX () {
return "Merchant";
}
@Override
public AbstractServicer getServicer () {
return servicer;
}
public void setServicer (MerchantServicer servicer) {
this.servicer = servicer;
}
@Override
public void submitAction(){
}
public Object getColumnsAction(){
return this.getColumns();
}
public String getColumns(){
return JSONUtils.toString(Merchant.COLUMNS, 36);
}
}
|
package voss.model;
public interface EthernetProtectionPort extends LogicalEthernetPort {
EthernetPort getWorkingPort();
void setWorkingPort(EthernetPort port);
}
|
/*
* Copyright 2002-2021 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.security.oauth2.core;
import java.net.URL;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.util.Assert;
/**
* An "accessor" for a set of claims that may be used for assertions.
*
* @author Joe Grandja
* @since 5.0
*/
public interface ClaimAccessor {
/**
* Returns a set of claims that may be used for assertions.
* @return a {@code Map} of claims
*/
Map<String, Object> getClaims();
/**
* Returns the claim value as a {@code T} type. The claim value is expected to be of
* type {@code T}.
*
* @since 5.2
* @param claim the name of the claim
* @param <T> the type of the claim value
* @return the claim value
*/
@SuppressWarnings("unchecked")
default <T> T getClaim(String claim) {
return !hasClaim(claim) ? null : (T) getClaims().get(claim);
}
/**
* Returns {@code true} if the claim exists in {@link #getClaims()}, otherwise
* {@code false}.
* @param claim the name of the claim
* @return {@code true} if the claim exists, otherwise {@code false}
* @since 5.5
*/
default boolean hasClaim(String claim) {
Assert.notNull(claim, "claim cannot be null");
return getClaims().containsKey(claim);
}
/**
* Returns {@code true} if the claim exists in {@link #getClaims()}, otherwise
* {@code false}.
* @param claim the name of the claim
* @return {@code true} if the claim exists, otherwise {@code false}
* @deprecated Use
* {@link org.springframework.security.oauth2.core.ClaimAccessor#hasClaim} instead.
*/
@Deprecated
default Boolean containsClaim(String claim) {
return hasClaim(claim);
}
/**
* Returns the claim value as a {@code String} or {@code null} if it does not exist or
* is equal to {@code null}.
* @param claim the name of the claim
* @return the claim value or {@code null} if it does not exist or is equal to
* {@code null}
*/
default String getClaimAsString(String claim) {
return !hasClaim(claim) ? null
: ClaimConversionService.getSharedInstance().convert(getClaims().get(claim), String.class);
}
/**
* Returns the claim value as a {@code Boolean} or {@code null} if it does not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if it does not exist
*/
default Boolean getClaimAsBoolean(String claim) {
return !hasClaim(claim) ? null
: ClaimConversionService.getSharedInstance().convert(getClaims().get(claim), Boolean.class);
}
/**
* Returns the claim value as an {@code Instant} or {@code null} if it does not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if it does not exist
*/
default Instant getClaimAsInstant(String claim) {
if (!hasClaim(claim)) {
return null;
}
Object claimValue = getClaims().get(claim);
Instant convertedValue = ClaimConversionService.getSharedInstance().convert(claimValue, Instant.class);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to Instant.");
return convertedValue;
}
/**
* Returns the claim value as an {@code URL} or {@code null} if it does not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if it does not exist
*/
default URL getClaimAsURL(String claim) {
if (!hasClaim(claim)) {
return null;
}
Object claimValue = getClaims().get(claim);
URL convertedValue = ClaimConversionService.getSharedInstance().convert(claimValue, URL.class);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to URL.");
return convertedValue;
}
/**
* Returns the claim value as a {@code Map<String, Object>} or {@code null} if the
* claim does not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if the claim does not exist
* @throws IllegalArgumentException if the claim value cannot be converted to a
* {@code List}
* @throws NullPointerException if the claim value is {@code null}
*/
@SuppressWarnings("unchecked")
default Map<String, Object> getClaimAsMap(String claim) {
if (!hasClaim(claim)) {
return null;
}
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
final TypeDescriptor targetDescriptor = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(Object.class));
Object claimValue = getClaims().get(claim);
Map<String, Object> convertedValue = (Map<String, Object>) ClaimConversionService.getSharedInstance()
.convert(claimValue, sourceDescriptor, targetDescriptor);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to Map.");
return convertedValue;
}
/**
* Returns the claim value as a {@code List<String>} or {@code null} if the claim does
* not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if the claim does not exist
* @throws IllegalArgumentException if the claim value cannot be converted to a
* {@code List}
* @throws NullPointerException if the claim value is {@code null}
*/
@SuppressWarnings("unchecked")
default List<String> getClaimAsStringList(String claim) {
if (!hasClaim(claim)) {
return null;
}
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
final TypeDescriptor targetDescriptor = TypeDescriptor.collection(List.class,
TypeDescriptor.valueOf(String.class));
Object claimValue = getClaims().get(claim);
List<String> convertedValue = (List<String>) ClaimConversionService.getSharedInstance().convert(claimValue,
sourceDescriptor, targetDescriptor);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to List.");
return convertedValue;
}
}
|
/*
* Copyright 2020-2021 Rosemoe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.rosemoe.editor.text;
/**
* Indexer without cache
*
* @author Rose
*/
public final class NoCacheIndexer extends CachedIndexer implements Indexer {
/**
* Create a indexer without cache
*
* @param content Target content
*/
public NoCacheIndexer(Content content) {
super(content);
//Disable dynamic indexing
if (super.getMaxCacheSize() != 0) {
super.setMaxCacheSize(0);
}
if (super.isHandleEvent()) {
super.setHandleEvent(false);
}
}
}
|
// Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: test.fbe
// Version: 1.8.0.0
package com.chronoxor.test.fbe;
// Fast Binary Encoding com.chronoxor.test protocol version
public final class ProtocolVersion
{
// Protocol major version
public static final int Major = 123;
// Protocol minor version
public static final int Minor = 456;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.hop.neo4j.transforms.loginfo;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.pipeline.transform.BaseTransformData;
import org.apache.hop.pipeline.transform.ITransformData;
public class GetLoggingInfoData extends BaseTransformData implements ITransformData {
public boolean readsRows;
public IRowMeta outputRowMeta;
public GetLoggingInfoData() {
super();
}
}
|
package Basic;
import java.util.*;
class fibonacciRecursion{
static int a = 0, b = 1, c;
static void fibonacci(int n){
if(n>=1){
System.out.print(a + " ");
c = a + b;
a = b;
b = c;
fibonacci(n-1);
}
}
public static void main(String[] args){;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms : ");
int n = sc.nextInt();
fibonacci(n);
}
}
|
package com.google.android.gms.internal.firebase-perf;
public final class zzfc extends zzfg {
public static zzfx zzht() {
throw new NoSuchMethodError();
}
public final int hashCode() {
throw new NoSuchMethodError();
}
public final boolean equals(Object obj) {
throw new NoSuchMethodError();
}
public final String toString() {
throw new NoSuchMethodError();
}
}
|
package com.diogonunes.jcdp.color;
import com.diogonunes.jcdp.bw.api.IPrinter;
import com.diogonunes.jcdp.color.api.AbstractColoredPrinter;
import com.diogonunes.jcdp.color.api.Ansi;
import com.diogonunes.jcdp.color.api.Ansi.Attribute;
import com.diogonunes.jcdp.color.api.Ansi.BColor;
import com.diogonunes.jcdp.color.api.Ansi.FColor;
import com.diogonunes.jcdp.color.api.IColoredPrinter;
import com.sun.jna.Function;
import com.sun.jna.platform.win32.WinDef.BOOL;
import com.sun.jna.platform.win32.WinDef.DWORD;
import com.sun.jna.platform.win32.WinDef.DWORDByReference;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import static com.diogonunes.jcdp.Constants.NEWLINE;
/**
* If you want to create a ColoredPrinter this is the class you should use. This class lets
* you define a format once and print all messages using that format.
* Check the {@link IColoredPrinter} for the full API. This class also implements all abstract
* methods inherited from the {@link AbstractColoredPrinter} class.
*/
public class ColoredPrinter extends AbstractColoredPrinter {
/**
* Constructor (using defaults): creates a Colored Printer with no format,
* zero level of debug and timestamping active according to ISO 8601.
*/
public ColoredPrinter() {
this(new Builder(0, false));
}
/**
* Constructor using builder.
*
* @param builder Builder with the desired configurations.
*/
public ColoredPrinter(Builder builder) {
setLevel(builder._level);
setTimestamping(builder._timestampFlag);
setDateFormat(builder._dateFormat);
setAttribute(builder._attribute);
setForegroundColor(builder._foregroundColor);
setBackgroundColor(builder._backgroundColor);
String currentOS = System.getProperty("os.name");
if (currentOS.startsWith("Windows")) {
if (currentOS.endsWith("10"))
enableWindows10AnsiSupport();
else {
String why = "Your version of JCDP (v4.*) requires Windows 10 -- if you cannot upgrade, then use JCDP v3.*";
throw new UnsupportedOperationException(why);
}
}
}
// =========
// BUILDER
// =========
/**
* Builder pattern: allows the caller to specify the attributes that it
* wants to change and keep the default values in the others.
*/
public static class Builder {
// required parameters
private int _level;
private boolean _timestampFlag;
// optional parameters - initialized to default values
private Attribute _attribute = Attribute.NONE;
private FColor _foregroundColor = FColor.NONE;
private BColor _backgroundColor = BColor.NONE;
private DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* The Colored Printer created, by default, has no format. So it's just
* like a usual Printer {@link IPrinter}.
*
* @param level specifies the maximum level of debug this printer can
* print.
* @param tsFlag true, if you want a timestamp before each message.
*/
public Builder(int level, boolean tsFlag) {
_level = level;
_timestampFlag = tsFlag;
}
/**
* @param df the printing format of the timestamp.
* @return the builder.
*/
public Builder withFormat(DateFormat df) {
this._dateFormat = df;
return this;
}
/**
* @param attr specifies the attribute component of the printing format.
* @return the builder.
*/
public Builder attribute(Attribute attr) {
this._attribute = attr;
return this;
}
/**
* @param fg specifies the foreground color of the printing format.
* @return the builder.
*/
public Builder foreground(FColor fg) {
this._foregroundColor = fg;
return this;
}
/**
* @param bg specifies the background color of the printing format.
* @return the builder.
*/
public Builder background(BColor bg) {
this._backgroundColor = bg;
return this;
}
/**
* @return a new instance of ColoredPrinterNIX.
*/
public ColoredPrinter build() {
return new ColoredPrinter(this);
}
}
// =================================
// OTHER METHODS (implementations)
// =================================
/**
* {@inheritDoc}
*/
@Override
public void print(Object msg) {
String code = Ansi.generateCode(getAttribute(), getForegroundColor(), getBackgroundColor());
formattedPrint(msg, code, false, false);
}
/**
* {@inheritDoc}
*/
@Override
public void print(Object msg, Attribute attr, FColor fg, BColor bg) {
String code = Ansi.generateCode(attr, fg, bg);
formattedPrint(msg, code, false, false);
}
/**
* {@inheritDoc}
*/
@Override
public void println(Object msg) {
String code = Ansi.generateCode(getAttribute(), getForegroundColor(), getBackgroundColor());
formattedPrint(msg, code, true, false);
}
/**
* {@inheritDoc}
*/
@Override
public void println(Object msg, Attribute attr, FColor fg, BColor bg) {
String code = Ansi.generateCode(attr, fg, bg);
formattedPrint(msg, code, true, false);
}
/**
* {@inheritDoc}
*/
@Override
public void errorPrint(Object msg) {
String code = Ansi.generateCode(getAttribute(), getForegroundColor(), getBackgroundColor());
formattedPrint(msg, code, false, true);
}
/**
* {@inheritDoc}
*/
@Override
public void errorPrint(Object msg, Attribute attr, FColor fg, BColor bg) {
String code = Ansi.generateCode(attr, fg, bg);
formattedPrint(msg, code, false, true);
}
/**
* {@inheritDoc}
*/
@Override
public void errorPrintln(Object msg) {
String code = Ansi.generateCode(getAttribute(), getForegroundColor(), getBackgroundColor());
formattedPrint(msg, code, true, true);
}
/**
* {@inheritDoc}
*/
@Override
public void errorPrintln(Object msg, Attribute attr, FColor fg, BColor bg) {
String code = Ansi.generateCode(attr, fg, bg);
formattedPrint(msg, code, true, true);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrint(Object msg) {
if (isLoggingDebug())
print(msg);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrint(Object msg, Attribute attr, FColor fg, BColor bg) {
if (isLoggingDebug())
print(msg, attr, fg, bg);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrint(Object msg, int level) {
if (isLoggingDebug() && canPrint(level))
print(msg);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrint(Object msg, int level, Attribute attr, FColor fg, BColor bg) {
if (canPrint(level))
print(msg, attr, fg, bg);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrintln(Object msg) {
println(msg);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrintln(Object msg, Attribute attr, FColor fg, BColor bg) {
println(msg, attr, fg, bg);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrintln(Object msg, int level) {
if (canPrint(level))
println(msg);
}
/**
* {@inheritDoc}
*/
@Override
public void debugPrintln(Object msg, int level, Attribute attr, FColor fg, BColor bg) {
if (canPrint(level))
println(msg, attr, fg, bg);
}
/**
* @return The text representation of the Printer.
*/
@Override
public String toString() {
return getClass().getSimpleName() + " | level: " + getLevel() + " | timestamping: "
+ isLoggingTimestamps() + " | Attribute: " + getAttribute().name()
+ " | Foreground color: " + getForegroundColor().name() + " | Background color: "
+ getBackgroundColor().name();
}
private void formattedPrint(Object msg, String ansiFormatCode, boolean appendNewline, boolean isError) {
StringBuilder output = new StringBuilder();
output.append(isLoggingTimestamps() ? getDateFormatted() + " " : "");
output.append(msg);
output.append(appendNewline ? NEWLINE : "");
String formattedMsg = Ansi.formatMessage(output.toString(), ansiFormatCode);
if (isError)
System.err.print(formattedMsg);
else
System.out.print(formattedMsg);
}
/* Windows 10 supports Ansi codes. However, it's still experimental and not enabled by default.
* This method enables the necessary Windows 10 feature.
*
* More info: https://stackoverflow.com/a/51681675/675577
* Code source: https://stackoverflow.com/a/52767586/675577
* Reported issue: https://github.com/PowerShell/PowerShell/issues/11449#issuecomment-569531747
*/
private void enableWindows10AnsiSupport() {
Function GetStdHandleFunc = Function.getFunction("kernel32", "GetStdHandle");
DWORD STD_OUTPUT_HANDLE = new DWORD(-11);
HANDLE hOut = (HANDLE) GetStdHandleFunc.invoke(HANDLE.class, new Object[]{STD_OUTPUT_HANDLE});
DWORDByReference p_dwMode = new DWORDByReference(new DWORD(0));
Function GetConsoleModeFunc = Function.getFunction("kernel32", "GetConsoleMode");
GetConsoleModeFunc.invoke(BOOL.class, new Object[]{hOut, p_dwMode});
int ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
DWORD dwMode = p_dwMode.getValue();
dwMode.setValue(dwMode.intValue() | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
Function SetConsoleModeFunc = Function.getFunction("kernel32", "SetConsoleMode");
SetConsoleModeFunc.invoke(BOOL.class, new Object[]{hOut, dwMode});
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.broad.igv.sam;
import org.broad.igv.feature.Strand;
import java.util.ArrayList;
import java.util.List;
/**
* A row of alignments, packed to minimize empty space
*
* @author jacob
* @date 2014-Jan-10
*/
public class Row implements Comparable<Row> {
int nextIdx;
private double score = 0;
List<Alignment> alignments;
public double y;
public double h;
public Row() {
nextIdx = 0;
this.alignments = new ArrayList(100);
}
public void addAlignment(Alignment alignment) {
// if (alignment instanceof LinkedAlignment) {
// for (Alignment a : ((LinkedAlignment) alignment).alignments) {
// alignments.add(a);
// }
// } else {
alignments.add(alignment);
// }
}
public void updateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
setScore(calculateScore(option, center, interval, tag));
}
public double calculateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
int adjustedCenter = (int) center;
Alignment centerAlignment = AlignmentInterval.getFeatureContaining(alignments, adjustedCenter);
if (centerAlignment == null) {
return Integer.MAX_VALUE;
} else {
switch (option) {
case START:
return centerAlignment.getAlignmentStart();
case STRAND:
if(centerAlignment instanceof LinkedAlignment) {
return ((LinkedAlignment) centerAlignment).getStrandAtPosition(center) == Strand.NEGATIVE ? 1 : -1;
}
else {
return centerAlignment.isNegativeStrand() ? -1 : 1;
}
case FIRST_OF_PAIR_STRAND:
Strand strand = centerAlignment.getFirstOfPairStrand();
int score = 2;
if (strand != Strand.NONE) {
score = strand == Strand.NEGATIVE ? 1 : -1;
}
return score;
case READ_ORDER:
if(centerAlignment.isPaired() && centerAlignment.isFirstOfPair()) {
score = -1;
} else if(centerAlignment.isPaired() && centerAlignment.isSecondOfPair()) {
score = 1;
}
else {
score = 0;
}
return score;
case NUCLEOTIDE:
byte base = centerAlignment.getBase(adjustedCenter);
byte ref = interval.getReference(adjustedCenter);
// Uppercase
if (base >= 97) base -= 32;
if (ref >= 97) ref -= 32;
// Check insertions
int insertionScore = 0;
AlignmentBlock[] insertions = centerAlignment.getInsertions();
for (AlignmentBlock ins : insertions) {
int s = ins.getStart();
if (s == adjustedCenter || (s - 1) == adjustedCenter) {
insertionScore += ins.getLength();
}
}
float baseScore;
if (base == 'N') {
baseScore = 2;
} else if (base == ref) {
baseScore = 3; // Base is reference
} else {
//If base is 0, base not covered (splice junction) or is deletion.
if (base == 0) {
int delCount = interval.getDelCount(adjustedCenter);
if (delCount > 0) {
baseScore = -delCount;
} else {
//Base not covered, NOT a deletion
baseScore = 1;
}
} else {
int count = interval.getCount(adjustedCenter, base);
byte phred = centerAlignment.getPhred(adjustedCenter);
baseScore = -(count + (phred / 1000.0f)); // The second bit will always be < 1
}
}
return baseScore - insertionScore; // base score is negative, so this is actually a sum of magnitudes
case QUALITY:
return -centerAlignment.getMappingQuality();
case SAMPLE:
String sample = centerAlignment.getSample();
score = sample == null ? 0 : sample.hashCode();
return score;
case READ_GROUP:
String readGroup = centerAlignment.getReadGroup();
score = readGroup == null ? 0 : readGroup.hashCode();
return score;
case INSERT_SIZE:
return -Math.abs(centerAlignment.getInferredInsertSize());
case MATE_CHR:
ReadMate mate = centerAlignment.getMate();
if (mate == null) {
return Integer.MAX_VALUE;
} else {
if (mate.getChr().equals(centerAlignment.getChr())) {
return Integer.MAX_VALUE - 1;
} else {
return mate.getChr().hashCode();
}
}
case SUPPLEMENTARY:
return centerAlignment.isSupplementary() ? 0 : 1;
case TAG:
Object tagValue = centerAlignment.getAttribute(tag);
score = tagValue == null ? 0 : tagValue.hashCode();
return score;
case HAPLOTYPE:
//String hapname = centerAlignment.getHaplotypeName();
//return hapname == null ? 0 : hapname.hashCode();
return centerAlignment.getHapDistance();
case READ_NAME:
String readName = centerAlignment.getReadName();
score = readName == null ? 0 : readName.hashCode();
return score;
default:
return Integer.MAX_VALUE;
}
}
}
public Alignment nextAlignment() {
if (nextIdx < alignments.size()) {
Alignment tmp = alignments.get(nextIdx);
nextIdx++;
return tmp;
} else {
return null;
}
}
public int getNextStartPos() {
if (nextIdx < alignments.size()) {
return alignments.get(nextIdx).getStart();
} else {
return Integer.MAX_VALUE;
}
}
public boolean hasNext() {
return nextIdx < alignments.size();
}
public void resetIdx() {
nextIdx = 0;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public int compareTo(Row o) {
return (int) Math.signum(getScore() - o.getScore());
}
// @Override
// public boolean equals(Object object){
// if(!(object instanceof Row)){
// return false;
// }
// Row other = (Row) object;
// boolean equals = this.getStart() == other.getStart();
// equals &= this.getLastEnd() == other.getLastEnd();
// equals &= this.getScore() == other.getScore();
//
// return equals;
//
// }
//
// @Override
// public int hashCode(){
// int score = (int) getScore();
// score = score != 0 ? score : 1;
// return (getStart() * getLastEnd() * score);
// }
}
|
package org.elasticsearch.mapping;
/**
* Exception throwed when the mapping is not correct.
*
* @author luc boutier
*/
public class MappingException extends RuntimeException {
private static final long serialVersionUID = 1L;
public MappingException(String message) {
super(message);
}
}
|
package com.github.sandor_balazs.nosql_java.service.impl;
import com.github.sandor_balazs.nosql_java.service.ProjectRegionService;
import com.github.sandor_balazs.nosql_java.domain.ProjectRegion;
import com.github.sandor_balazs.nosql_java.repository.ProjectRegionRepository;
import com.github.sandor_balazs.nosql_java.web.rest.dto.ProjectRegionDTO;
import com.github.sandor_balazs.nosql_java.web.rest.mapper.ProjectRegionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Service Implementation for managing ProjectRegion.
*/
@Service
@Transactional
public class ProjectRegionServiceImpl implements ProjectRegionService{
private final Logger log = LoggerFactory.getLogger(ProjectRegionServiceImpl.class);
@Inject
private ProjectRegionRepository projectRegionRepository;
@Inject
private ProjectRegionMapper projectRegionMapper;
/**
* Save a projectRegion.
* @return the persisted entity
*/
public ProjectRegionDTO save(ProjectRegionDTO projectRegionDTO) {
log.debug("Request to save ProjectRegion : {}", projectRegionDTO);
ProjectRegion projectRegion = projectRegionMapper.projectRegionDTOToProjectRegion(projectRegionDTO);
projectRegion = projectRegionRepository.save(projectRegion);
ProjectRegionDTO result = projectRegionMapper.projectRegionToProjectRegionDTO(projectRegion);
return result;
}
/**
* get all the projectRegions.
* @return the list of entities
*/
@Transactional(readOnly = true)
public List<ProjectRegionDTO> findAll() {
log.debug("Request to get all ProjectRegions");
List<ProjectRegionDTO> result = projectRegionRepository.findAll().stream()
.map(projectRegionMapper::projectRegionToProjectRegionDTO)
.collect(Collectors.toCollection(LinkedList::new));
return result;
}
/**
* get one projectRegion by id.
* @return the entity
*/
@Transactional(readOnly = true)
public ProjectRegionDTO findOne(Long id) {
log.debug("Request to get ProjectRegion : {}", id);
ProjectRegion projectRegion = projectRegionRepository.findOne(id);
ProjectRegionDTO projectRegionDTO = projectRegionMapper.projectRegionToProjectRegionDTO(projectRegion);
return projectRegionDTO;
}
/**
* delete the projectRegion by id.
*/
public void delete(Long id) {
log.debug("Request to delete ProjectRegion : {}", id);
projectRegionRepository.delete(id);
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.query;
import org.apache.lucene.search.Filter;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoHashUtils;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.GeoUtils;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.cache.filter.support.CacheKeyFilter;
import org.elasticsearch.index.fielddata.IndexGeoPointFieldData;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.geo.GeoPointFieldMapper;
import org.elasticsearch.index.search.geo.GeoDistanceRangeFilter;
import java.io.IOException;
import static org.elasticsearch.index.query.support.QueryParsers.wrapSmartNameFilter;
/**
* <pre>
* {
* "name.lat" : 1.1,
* "name.lon" : 1.2,
* }
* </pre>
*/
public class GeoDistanceRangeFilterParser implements FilterParser {
public static final String NAME = "geo_distance_range";
@Inject
public GeoDistanceRangeFilterParser() {
}
@Override
public String[] names() {
return new String[]{NAME, "geoDistanceRange"};
}
@Override
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
XContentParser.Token token;
boolean cache = false;
CacheKeyFilter.Key cacheKey = null;
String filterName = null;
String currentFieldName = null;
GeoPoint point = new GeoPoint();
String fieldName = null;
Object vFrom = null;
Object vTo = null;
boolean includeLower = true;
boolean includeUpper = true;
DistanceUnit unit = DistanceUnit.DEFAULT;
GeoDistance geoDistance = GeoDistance.DEFAULT;
String optimizeBbox = "memory";
boolean normalizeLon = true;
boolean normalizeLat = true;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
GeoUtils.parseGeoPoint(parser, point);
fieldName = currentFieldName;
} else if (token == XContentParser.Token.START_OBJECT) {
// the json in the format of -> field : { lat : 30, lon : 12 }
fieldName = currentFieldName;
GeoUtils.parseGeoPoint(parser, point);
} else if (token.isValue()) {
if (currentFieldName.equals("from")) {
if (token == XContentParser.Token.VALUE_NULL) {
} else if (token == XContentParser.Token.VALUE_STRING) {
vFrom = parser.text(); // a String
} else {
vFrom = parser.numberValue(); // a Number
}
} else if (currentFieldName.equals("to")) {
if (token == XContentParser.Token.VALUE_NULL) {
} else if (token == XContentParser.Token.VALUE_STRING) {
vTo = parser.text(); // a String
} else {
vTo = parser.numberValue(); // a Number
}
} else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) {
includeLower = parser.booleanValue();
} else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) {
includeUpper = parser.booleanValue();
} else if ("gt".equals(currentFieldName)) {
if (token == XContentParser.Token.VALUE_NULL) {
} else if (token == XContentParser.Token.VALUE_STRING) {
vFrom = parser.text(); // a String
} else {
vFrom = parser.numberValue(); // a Number
}
includeLower = false;
} else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) {
if (token == XContentParser.Token.VALUE_NULL) {
} else if (token == XContentParser.Token.VALUE_STRING) {
vFrom = parser.text(); // a String
} else {
vFrom = parser.numberValue(); // a Number
}
includeLower = true;
} else if ("lt".equals(currentFieldName)) {
if (token == XContentParser.Token.VALUE_NULL) {
} else if (token == XContentParser.Token.VALUE_STRING) {
vTo = parser.text(); // a String
} else {
vTo = parser.numberValue(); // a Number
}
includeUpper = false;
} else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) {
if (token == XContentParser.Token.VALUE_NULL) {
} else if (token == XContentParser.Token.VALUE_STRING) {
vTo = parser.text(); // a String
} else {
vTo = parser.numberValue(); // a Number
}
includeUpper = true;
} else if (currentFieldName.equals("unit")) {
unit = DistanceUnit.fromString(parser.text());
} else if (currentFieldName.equals("distance_type") || currentFieldName.equals("distanceType")) {
geoDistance = GeoDistance.fromString(parser.text());
} else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LAT_SUFFIX)) {
point.resetLat(parser.doubleValue());
fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.LAT_SUFFIX.length());
} else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LON_SUFFIX)) {
point.resetLon(parser.doubleValue());
fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.LON_SUFFIX.length());
} else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.GEOHASH_SUFFIX)) {
GeoHashUtils.decode(parser.text(), point);
fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.GEOHASH_SUFFIX.length());
} else if ("_name".equals(currentFieldName)) {
filterName = parser.text();
} else if ("_cache".equals(currentFieldName)) {
cache = parser.booleanValue();
} else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
cacheKey = new CacheKeyFilter.Key(parser.text());
} else if ("optimize_bbox".equals(currentFieldName) || "optimizeBbox".equals(currentFieldName)) {
optimizeBbox = parser.textOrNull();
} else if ("normalize".equals(currentFieldName)) {
normalizeLat = parser.booleanValue();
normalizeLon = parser.booleanValue();
} else {
point.resetFromString(parser.text());
fieldName = currentFieldName;
}
}
}
Double from = null;
Double to = null;
if (vFrom != null) {
if (vFrom instanceof Number) {
from = unit.toMeters(((Number) vFrom).doubleValue());
} else {
from = DistanceUnit.parse((String) vFrom, unit, DistanceUnit.DEFAULT);
}
from = geoDistance.normalize(from, DistanceUnit.DEFAULT);
}
if (vTo != null) {
if (vTo instanceof Number) {
to = unit.toMeters(((Number) vTo).doubleValue());
} else {
to = DistanceUnit.parse((String) vTo, unit, DistanceUnit.DEFAULT);
}
to = geoDistance.normalize(to, DistanceUnit.DEFAULT);
}
if (normalizeLat || normalizeLon) {
GeoUtils.normalizePoint(point, normalizeLat, normalizeLon);
}
MapperService.SmartNameFieldMappers smartMappers = parseContext.smartFieldMappers(fieldName);
if (smartMappers == null || !smartMappers.hasMapper()) {
throw new QueryParsingException(parseContext.index(), "failed to find geo_point field [" + fieldName + "]");
}
FieldMapper<?> mapper = smartMappers.mapper();
if (!(mapper instanceof GeoPointFieldMapper)) {
throw new QueryParsingException(parseContext.index(), "field [" + fieldName + "] is not a geo_point field");
}
GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper) mapper);
IndexGeoPointFieldData<?> indexFieldData = parseContext.fieldData().getForField(mapper);
Filter filter = new GeoDistanceRangeFilter(point, from, to, includeLower, includeUpper, geoDistance, geoMapper, indexFieldData, optimizeBbox);
if (cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
filter = wrapSmartNameFilter(filter, smartMappers, parseContext);
if (filterName != null) {
parseContext.addNamedFilter(filterName, filter);
}
return filter;
}
}
|
/*
* Copyright (C) 2020 Dremio
*
* 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.projectnessie.client.api;
import org.projectnessie.error.NessieNotFoundException;
import org.projectnessie.model.EntriesResponse;
/**
* Request builder for "get entries".
*
* @since Nessie API {@link NessieApiVersion#V_1}
*/
public interface GetEntriesBuilder extends PagingBuilder<GetEntriesBuilder> {
GetEntriesBuilder namespaceDepth(Integer namespaceDepth);
EntriesResponse get() throws NessieNotFoundException;
}
|
package com.trend.lazyinject.demo.application;
import android.app.Application;
import com.trend.lazyinject.buildmap.Auto_ComponentBuildMap;
import com.trend.lazyinject.lib.LazyInject;
/**
* Created by swift_gan on 2018/4/17.
*/
public class DemoApplication extends Application {
public static Application application;
@Override
public void onCreate() {
super.onCreate();
application = this;
LazyInject.init(this);
LazyInject.addBuildMap(Auto_ComponentBuildMap.class);
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the FRIL Framework.
*
* The Initial Developers of the Original Code are
* The Department of Math and Computer Science, Emory University and
* The Centers for Disease Control and Prevention.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package cdc.gui.components.progress;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import cdc.gui.Configs;
import cdc.gui.MainFrame;
import cdc.gui.components.statistics.HistogramDialog;
public class ProgressDialog extends JDialog {
private JButton cancel = new JButton("Cancel");
private JButton details = new JButton(Configs.openDetailsIcon);
private JProgressBar progressBar;
private JPanel infoPanel;
private JPanel detailsPanel;
private JPanel mainPanel;
private JPanel firstLevelPanel;
private JDialog statistics;
private Dimension sizeDefaultDetailsOn = new Dimension(600, 400);
private Dimension sizeDefaultDetailsOff = new Dimension(600, 200);
private boolean detailsOn = false;
private boolean detailsActiolListenerSet = false;
private boolean showStatsButton = true;
private int currY = 0;
public ProgressDialog(Window parent, String title, boolean resizable) {
this(parent, title, resizable, true);
}
public ProgressDialog(Window parent, String title, boolean resizable, boolean showStatsButton) {
super(parent);
setModal(true);
setTitle(title);
this.showStatsButton = showStatsButton;
mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
mainPanel.setLayout(new GridBagLayout());
getContentPane().add(mainPanel);
createUI();
updateUI();
}
public ProgressDialog(Window parent, String title) {
this(parent, title, true);
}
private void createUI() {
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
cancel.setPreferredSize(new Dimension(100, 20));
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cancel.setEnabled(false);
}
});
details.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
detailsOn = !detailsOn;
if (detailsOn) {
details.setIcon(Configs.closeDetailsIcon);
} else {
details.setIcon(Configs.openDetailsIcon);
}
updateUI();
}
});
details.setPreferredSize(new Dimension(20, 20));
details.setBorder(BorderFactory.createEmptyBorder());
firstLevelPanel = new JPanel(new BorderLayout());
firstLevelPanel.add(new JLabel("Please wait..."), BorderLayout.WEST);
firstLevelPanel.add(cancel, BorderLayout.EAST);
progressBar = new JProgressBar();
progressBar.setPreferredSize(new Dimension(100, 15));
progressBar.setIndeterminate(true);
}
private GridBagConstraints getDefaultConstraints() {
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = currY ++;
c.weightx = 1.0;
c.fill = GridBagConstraints.BOTH;
return c;
}
public void updateUI() {
mainPanel.removeAll();
mainPanel.add(firstLevelPanel, getDefaultConstraints());
mainPanel.add(Box.createRigidArea(new Dimension(5,5)), getDefaultConstraints());
mainPanel.add(progressBar, getDefaultConstraints());
if (infoPanel != null) {
mainPanel.add(Box.createRigidArea(new Dimension(5,5)), getDefaultConstraints());
mainPanel.add(infoPanel, getDefaultConstraints());
}
Box buttons = Box.createHorizontalBox();
if (detailsPanel != null || detailsActiolListenerSet) {
mainPanel.add(Box.createRigidArea(new Dimension(5,5)), getDefaultConstraints());
//JPanel detailsButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
buttons.add(new JLabel("Details"));
buttons.add(Box.createRigidArea(new Dimension(5,5)));
buttons.add(details);
//mainPanel.add(buttons, getDefaultConstraints());
}
buttons.add(Box.createGlue());
JButton stats = new JButton(Configs.statistics);
stats.setPreferredSize(new Dimension(30, 30));
stats.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (statistics != null) {
statistics.toFront();
} else {
statistics = new HistogramDialog(ProgressDialog.this, "Linkage statistics", MainFrame.main.getConfiguredSystem().getJoin().getJoinStatisticsListener());
statistics.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
statistics = null;
}
});
statistics.setVisible(true);
}
}
});
// JButton linkages = new JButton(Configs.analysisButtonIcon);
// linkages.setPreferredSize(new Dimension(30, 30));
// linkages.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// MainFrame.main.openLinkagesDialog();
// }
// });
//stats.setPreferredSize(new Dimension(160, 20));
buttons.add(Box.createRigidArea(new Dimension(30, 30)));
//buttons.add(linkages);
//buttons.add(Box.createRigidArea(new Dimension(10, 10)));
if (showStatsButton) {
buttons.add(stats);
}
mainPanel.add(buttons, getDefaultConstraints());
if (detailsOn) {
mainPanel.add(Box.createRigidArea(new Dimension(5,5)), getDefaultConstraints());
GridBagConstraints c = getDefaultConstraints();
c.weighty = 1.0;
if (detailsPanel != null) {
mainPanel.add(detailsPanel, c);
} else {
mainPanel.add(new JPanel(), c);
}
setSize(new Dimension(sizeDefaultDetailsOn));
} else {
mainPanel.add(Box.createRigidArea(new Dimension(5,5)), getDefaultConstraints());
JPanel filler = new JPanel();
GridBagConstraints c = getDefaultConstraints();
c.weighty = 1.0;
mainPanel.add(filler, c);
setSize(new Dimension(sizeDefaultDetailsOff));
}
mainPanel.updateUI();
}
public boolean isDetailsOn() {
return detailsOn;
}
public void setInfoPanel(JPanel panel) {
this.infoPanel = panel;
updateUI();
}
public void setDetailsPanel(JPanel panel) {
this.detailsPanel = panel;
updateUI();
}
public JProgressBar getProgressBar() {
return progressBar;
}
public void addCancelListener(ActionListener listener) {
cancel.addActionListener(listener);
}
public void addDetailsActionListener(ActionListener listener) {
detailsActiolListenerSet = true;
details.addActionListener(listener);
updateUI();
}
}
|
package ai.starwhale.mlops.api.protocol.swds;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.validation.annotation.Validated;
@Data
@Validated
public class SWDSVersionRequest {
@JsonProperty("importPath")
private String importPath;
}
|
/******************************************************************************
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
package org.alljoyn.services.android.security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.alljoyn.bus.AuthListener;
import org.alljoyn.bus.BusAttachment;
import org.alljoyn.services.common.DefaultGenericLogger;
import org.alljoyn.services.common.utils.GenericLogger;
/**
* A default implementation of alljoyn AuthListener.
* The application will register this listener with the bus, passing itself as a password handler.
* When the bus requires authentication with a remote device, it will let the password handler (the application) handle it.
* When the bus receives a result of an authentication attempt with a remote device, it will let the password handler (the application) handle it.
* @see AuthPasswordHandler
*/
public class SrpAnonymousKeyListener implements AuthListener
{
private String TAG = "SrpAnonymousKeyListener";
public static String KEY_STORE_FINE_NAME;
public static final char [] DEFAULT_PINCODE = new char[]{'0','0','0','0','0','0'};
AuthPasswordHandler m_passwordHandler;
private GenericLogger m_logger;
/**
* Supported authentication mechanisms
*/
private List<String> authMechanisms;
/**
* Constructor
* @param passwordHandler
* @param logger
*/
public SrpAnonymousKeyListener(AuthPasswordHandler passwordHandler, GenericLogger logger)
{
m_logger = logger;
if (m_logger == null)
{
m_logger = new DefaultGenericLogger();
}
m_passwordHandler = passwordHandler;
authMechanisms = new ArrayList<String>(3);
authMechanisms.add("ALLJOYN_PIN_KEYX");
authMechanisms.add("ALLJOYN_SRP_KEYX");
authMechanisms.add("ALLJOYN_ECDHE_PSK");
}
/**
* Constructor
* @param passwordHandler
* @param logger
* @param authMechanisms Array of authentication mechanisms
*/
public SrpAnonymousKeyListener(AuthPasswordHandler passwordHandler, GenericLogger logger, String[] authMechanisms)
{
this(passwordHandler, logger);
if ( authMechanisms == null ) {
throw new IllegalArgumentException("authMechanisms is undefined");
}
this.authMechanisms = Arrays.asList(authMechanisms);
m_logger.debug(TAG, "Supported authentication mechanisms: '" + this.authMechanisms + "'");
}
@Override
public boolean requested(String mechanism, String peer, int count, String userName, AuthRequest[] requests)
{
m_logger.info(TAG, " ** " + "requested, mechanism = " + mechanism + " peer = " + peer);
if ( !this.authMechanisms.contains(mechanism) )
{
return false;
}
else
{
if (!(requests[0] instanceof PasswordRequest))
{
return false;
}
char [] pinCode = DEFAULT_PINCODE;
// if pincode not set for this peer, the function will return null, at that case, use the default one.
if (m_passwordHandler != null && m_passwordHandler.getPassword(peer)!= null)
{
pinCode = m_passwordHandler.getPassword(peer);
}
((PasswordRequest) requests[0]).setPassword(pinCode);
return true;
}
}
@Override
public void completed(String mechanism, String authPeer, boolean authenticated)
{
/*if (! authenticated)
{
m_logger.info(TAG, " ** " + authPeer + " failed to authenticate");
return;
}
m_logger.info(TAG, " ** " + authPeer + " successfully authenticated");*/
m_passwordHandler.completed(mechanism, authPeer, authenticated);
}
/**
* @return AuthMechanisms used by the class
*/
public String[] getAuthMechanisms() {
return authMechanisms.toArray(new String[authMechanisms.size()]);
}
/**
* @return Returns AuthMechanisms used by the class as a String required by the
* {@link BusAttachment#registerAuthListener(String, AuthListener)}
*/
public String getAuthMechanismsAsString() {
final String separator = " ";
StringBuilder sb = new StringBuilder();
for (String mech : authMechanisms ) {
sb.append(mech).append(separator);
}
int length = sb.length();
if ( length >= 1 ) {
sb.deleteCharAt(length - 1); //remove the last added separator
}
return sb.toString();
}
}
|
package com.pjzhong.dsa.list;
import java.util.Iterator;
import java.util.ListIterator;
public abstract class AbstractList<E> implements List<E> {
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof List)) {
return false;
}
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1 == null ? o2 == null : o1.equals(o2))) {
return false;
}
}
return !(e1.hasNext() || e2.hasNext());
}
@Override
public int hashCode() {
int hasCode = 1;
for (E e : this) {
hasCode = 31 * hasCode + (e == null ? 0 : e.hashCode());
}
return hasCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("{");
Iterator<E> iterator = this.iterator();
while (iterator.hasNext()) {
builder.append(iterator.next());
if (iterator.hasNext()) {
builder.append(", ");
}
}
builder.append("}");
return builder.toString();
}
}
|
package id.brainmaster.iso20022.model;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for DateAndPlaceOfBirth1 complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="DateAndPlaceOfBirth1">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="BirthDt" type="{urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07}ISODate"/>
* <element name="PrvcOfBirth" type="{urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07}Max35Text" minOccurs="0"/>
* <element name="CityOfBirth" type="{urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07}Max35Text"/>
* <element name="CtryOfBirth" type="{urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07}CountryCode"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DateAndPlaceOfBirth1", namespace = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07", propOrder = {
"birthDt",
"prvcOfBirth",
"cityOfBirth",
"ctryOfBirth"
})
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public class DateAndPlaceOfBirth1 {
@XmlElement(name = "BirthDt", namespace = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07", required = true)
@XmlSchemaType(name = "date")
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
protected XMLGregorianCalendar birthDt;
@XmlElement(name = "PrvcOfBirth", namespace = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07")
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
protected String prvcOfBirth;
@XmlElement(name = "CityOfBirth", namespace = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07", required = true)
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
protected String cityOfBirth;
@XmlElement(name = "CtryOfBirth", namespace = "urn:iso:std:iso:20022:tech:xsd:pacs.008.001.07", required = true)
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
protected String ctryOfBirth;
/**
* Gets the value of the birthDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public XMLGregorianCalendar getBirthDt() {
return birthDt;
}
/**
* Sets the value of the birthDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public void setBirthDt(XMLGregorianCalendar value) {
this.birthDt = value;
}
/**
* Gets the value of the prvcOfBirth property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public String getPrvcOfBirth() {
return prvcOfBirth;
}
/**
* Sets the value of the prvcOfBirth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public void setPrvcOfBirth(String value) {
this.prvcOfBirth = value;
}
/**
* Gets the value of the cityOfBirth property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public String getCityOfBirth() {
return cityOfBirth;
}
/**
* Sets the value of the cityOfBirth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public void setCityOfBirth(String value) {
this.cityOfBirth = value;
}
/**
* Gets the value of the ctryOfBirth property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public String getCtryOfBirth() {
return ctryOfBirth;
}
/**
* Sets the value of the ctryOfBirth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-05-01T07:05:51+07:00", comments = "JAXB RI v2.2.8-b130911.1802")
public void setCtryOfBirth(String value) {
this.ctryOfBirth = value;
}
}
|
/*
* Copyright 2016 NHN Entertainment Corp.
*
* NHN Entertainment Corp. licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nhnent.haste.framework;
import com.nhnent.haste.common.Check;
import com.nhnent.haste.framework.fiber.FiberFactory;
import com.nhnent.haste.framework.security.AesCryptoProvider;
import com.nhnent.haste.framework.security.CryptoProvider;
import com.nhnent.haste.protocol.Protocol;
import com.nhnent.haste.protocol.ReturnCode;
import com.nhnent.haste.protocol.messages.*;
import com.nhnent.haste.transport.ApplicationPeer;
import com.nhnent.haste.transport.DisconnectReason;
import com.nhnent.haste.transport.NetworkPeer;
import com.nhnent.haste.transport.QoS;
import com.nhnent.haste.transport.state.ConnectionState;
import org.jetlang.fibers.Fiber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base class for receiving a payload and disconnect message from {@link NetworkPeer}.
*/
public abstract class ClientPeer implements ApplicationPeer {
private static final Logger logger = LoggerFactory.getLogger(ClientPeer.class);
private class ReceiveRunnable implements Runnable {
private byte[] receivedData;
private int receivedDataLength;
private byte channel;
private boolean isEncrypted;
private QoS qos;
public ReceiveRunnable(byte[] data, int dataLength, byte channel, boolean isEncrypted, QoS qos) {
this.receivedData = data;
this.receivedDataLength = dataLength;
this.channel = channel;
this.isEncrypted = isEncrypted;
this.qos = qos;
}
@Override
public void run() {
if (networkPeer == null) {
logger.warn("networkPeer is null");
return;
}
if (networkPeer.getConnectionState().isNotEqual(ConnectionState.CONNECTED)) {
logger.warn("networkPeer is not connected");
return;
}
if (receivedData == null) {
logger.warn("receivedData is null when receiving");
return;
}
ClientPeer.this.onReceived(receivedData, receivedDataLength, channel, isEncrypted, qos);
}
}
private class OnDisconnectRunnable implements Runnable {
private DisconnectReason reason;
private String detail;
private OnDisconnectRunnable(DisconnectReason reason, String detail) {
this.reason = reason;
this.detail = detail;
}
@Override
public void run() {
ClientPeer.this.onDisconnect(reason, detail);
}
}
private CryptoProvider cryptoProvider;
private NetworkPeer networkPeer;
private Fiber fiber = FiberFactory.newFiber();
protected Protocol protocol;
public ClientPeer(InitialRequest initialRequest, NetworkPeer networkPeer) {
this.networkPeer = networkPeer;
this.protocol = initialRequest.getProtocol();
this.cryptoProvider = new AesCryptoProvider(networkPeer.getSecretKey());
networkPeer.setApplicationPeer(this);
fiber.start();
}
@Override
public void internal_onReceive(byte[] data, int dataLength, byte channel, boolean isEncrypted, QoS qos) {
if (data.length < dataLength)
return;
ReceiveRunnable runnable = new ReceiveRunnable(data, dataLength, channel, isEncrypted, qos);
fiber.execute(runnable);
}
@Override
public void internal_onDisconnect(DisconnectReason reason, String detail) {
fiber.execute(new OnDisconnectRunnable(reason, detail));
}
public void disconnect(DisconnectReason reason, String detail) {
networkPeer.disconnect(reason, detail);
}
private void onReceived(byte[] payloadBytes, int payloadLength, byte channel, boolean isEncrypted, QoS qos) {
if (isEncrypted) {
byte[] decryptedPayload = this.cryptoProvider.decrypt(payloadBytes, 0, payloadLength);
if (decryptedPayload == null) {
if (logger.isWarnEnabled())
logger.warn("Failed Encrypted Data : length[{}]", payloadLength);
return;
}
payloadBytes = decryptedPayload;
}
MessageType type = this.protocol.getMessageType(payloadBytes);
switch (type) {
case INITIAL_REQUEST:
// TODO Validate InitialRequest
InitialResponse initialResponse = new InitialResponse(ReturnCode.OK, "success");
send(initialResponse, channel, false, QoS.RELIABLE_SEQUENCED);
break;
case INITIAL_RESPONSE:
break;
case REQUEST_MESSAGE:
case RESPONSE_MESSAGE:
case EVENT_MESSAGE:
Message message = this.protocol.deserializeMessage(payloadBytes);
if (message != null) {
if (logger.isTraceEnabled()) {
logger.trace("onReceived message : {}", message.toString());
}
if (message instanceof RequestMessage) {
onReceive((RequestMessage) message, SendOptions.take(channel, isEncrypted, qos));
}
}
break;
case NONE:
logger.debug("Invalid message code!");
break;
}
}
protected boolean send(ResponseMessage response, SendOptions options) {
return send(response, options.getChannel(), options.isEncrypt(), options.getQos());
}
protected boolean send(ResponseMessage response, byte channel, boolean encrypt, QoS qos) {
return send((Message) response, channel, encrypt, qos);
}
public boolean send(Message message, SendOptions options) {
return send(message, options.getChannel(), options.isEncrypt(), options.getQos());
}
protected boolean send(Message message, byte channel, boolean encrypt, QoS qos) {
Check.NotNull(message, "message");
byte[] payload = protocol.serialize(message);
if (encrypt) {
payload = this.cryptoProvider.encrypt(payload);
}
return send(payload, payload.length, channel, encrypt, qos);
}
protected boolean send(InitialResponse initialResponse, byte channel, boolean encrypt, QoS qos) {
Check.NotNull(initialResponse, "initialResponse");
byte[] payload = protocol.serialize(initialResponse);
if (encrypt) {
payload = this.cryptoProvider.encrypt(payload);
}
return send(payload, payload.length, channel, encrypt, qos);
}
protected boolean send(byte[] payload, int payloadLength, byte channel, boolean encrypt, QoS qos) {
if (networkPeer == null) {
return false;
}
if (networkPeer.getConnectionState().isEqual(ConnectionState.DISCONNECTED)) {
return false;
}
boolean result = networkPeer.enqueueOutgoingCommand(payload, payloadLength, channel, encrypt, qos);
if (result) {
onSent(payload, channel, encrypt, qos);
} else {
onFailedToSend(payload, channel, encrypt, qos);
}
return result;
}
protected void onFailedToSend(byte[] payload, byte channel, boolean encrypt, QoS qos) {
logger.error("ch[{}] Failed to send command!!", channel);
}
protected void onSent(byte[] payload, byte channel, boolean encrypt, QoS qos) {
}
public long getCurrentRTT() {
return networkPeer.getMeanOfRoundTripTime();
}
public long getCurrentRTTDeviation() {
return networkPeer.getMeanOfRoundTripTimeDeviation();
}
public long getLowestRoundTripTime() {
return networkPeer.getLowestRoundTripTime();
}
public long getHighestRoundTripTimeDeviation() {
return networkPeer.getHighestRoundTripTimeDeviation();
}
/**
* Called when this peer was received a message from {@link NetworkPeer}
* @param request A request message.
* @param options A option about networking.
*/
protected abstract void onReceive(RequestMessage request, SendOptions options);
/**
* Called when this peer was disconnected.
* @param reason The reason of disconnection.
* @param detail The detail message of disconnection.
*/
protected abstract void onDisconnect(DisconnectReason reason, String detail);
}
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 动态模板参数
*
* @author auto create
* @since 1.0, 2021-05-11 12:04:04
*/
public class ExtTemplateConf extends AlipayObject {
private static final long serialVersionUID = 1443694639579892374L;
/**
* 淘宝uid
*/
@ApiField("buyer_id")
private String buyerId;
/**
* 先享后买id
*/
@ApiField("xxhm_info_id")
private String xxhmInfoId;
public String getBuyerId() {
return this.buyerId;
}
public void setBuyerId(String buyerId) {
this.buyerId = buyerId;
}
public String getXxhmInfoId() {
return this.xxhmInfoId;
}
public void setXxhmInfoId(String xxhmInfoId) {
this.xxhmInfoId = xxhmInfoId;
}
}
|
package com.wizzardo.http;
import com.wizzardo.http.request.ByteTree;
import com.wizzardo.http.request.Header;
import com.wizzardo.http.request.Request;
import com.wizzardo.http.utils.AsciiReader;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.wizzardo.http.mapping.UrlMapping.SEGMENT_CACHE;
/**
* Created by wizzardo on 12.06.15.
*/
public abstract class HttpHeadersReader {
protected static final ByteTree headersTree = new ByteTree();
protected byte[] buffer;
protected int r;
protected String tempKey;
protected boolean waitForNewLine;
protected Map<String, MultiValue> headers;
protected boolean complete = false;
protected boolean onlyAllowedHeaders = false;
static {
for (Header header : Header.values()) {
headersTree.appendIgnoreCase(header.value);
}
for (Request.Method method : Request.Method.values()) {
headersTree.append(method.name());
}
headersTree.appendIgnoreCase("gzip,deflate,sdch");
headersTree.appendIgnoreCase("en-US,en;q=0.8,ru;q=0.6");
headersTree.append(HttpConnection.HTTP_1_0);
headersTree.append(HttpConnection.HTTP_1_1);
for (int i = 0; i < 512; i++) {
headersTree.append(String.valueOf(i));
}
}
public HttpHeadersReader(Map<String, MultiValue> headers) {
if (headers == null)
headers = new LinkedHashMap<>(16);
this.headers = headers;
}
public HttpHeadersReader() {
headers = new LinkedHashMap<>(16);
}
public void clear() {
if (!headers.isEmpty())
headers = new LinkedHashMap<>(16);
tempKey = null;
complete = false;
waitForNewLine = false;
r = 0;
}
public int read(byte[] bytes) {
return read(bytes, 0, bytes.length);
}
/**
* @return new offset in given byte array to read from.
*/
protected abstract int parseFirstLine(byte[] chars, int offset, int length);
protected int parseHeadersWithFirstLine(byte[] chars, int offset, int length) {
int newOffset = parseFirstLine(chars, offset, length);
length -= (newOffset - offset);
if (length > 0)
return parseHeaders(chars, newOffset, length);
else
return -1;
}
protected int parseHeaders(byte[] chars, int offset, int length) {
int l = offset + length;
if (waitForNewLine) {
for (int i = offset; i < l; i += 2) {
byte ch = chars[i];
if (ch == '\n') {
if (i > offset) {
if (chars[i - 1] == '\r') {
waitForNewLine = false;
if (tempKey != null) {
put(tempKey, getValue(chars, offset, i - offset - 1));
// headers.put(tempKey, getValue(s, offset, i - offset - 1));
// offset++;
tempKey = null;
}
// r = 0;
i++;
return parseHeaders(chars, i, length - (i - offset));
}
} else if (i == offset && r > 0 && buffer[r - 1] == 13) {
waitForNewLine = false;
r--;
if (tempKey != null) {
put(tempKey, getValue(chars, offset, i - offset - 1));
// headers.put(tempKey, getValue(s, offset, i - offset - 1));
// offset++;
tempKey = null;
}
// r = 0;
i++;
return parseHeaders(chars, i, length - (i - offset));
}
} else if (ch == '\r' && ++i < l && chars[i] == '\n') {
waitForNewLine = false;
if (tempKey != null) {
put(tempKey, getValue(chars, offset, i - offset - 1));
// headers.put(tempKey, getValue( offset, i - offset - 1));
// offset++;
tempKey = null;
}
// r = 0;
i++;
return parseHeaders(chars, i, length - (i - offset));
}
}
putIntoBuffer(chars, offset, length);
return -1;
}
if (length >= 2) {
if (r == 1 && buffer[0] == '\r' && chars[offset] == '\n') {
complete = true;
return offset + 1;
}
if (chars[offset] == '\r' && chars[offset + 1] == '\n') {
complete = true;
return offset + 2;
}
} else if (r == 1 && buffer[0] == '\r' && length == 1 && chars[offset] == '\n') {
complete = true;
return offset + 1;
}
for (int i = offset; i < l; i++) {
byte ch = chars[i];
if (ch == ':') {
// tempKey = getValue(bytes, offset, i - offset);
tempKey = getValue(chars, offset, i - offset);
// tempKey = getValue(s, offset, i - offset);
waitForNewLine = true;
i++;
return parseHeaders(chars, i, length - (i - offset));
}
}
putIntoBuffer(chars, offset, length);
return -1;
}
/**
* @return int offset in given byte array to request body.
* -1 if headers aren't completed
*/
public int read(byte[] bytes, int offset, int length) {
if (complete || length == 0)
return -1;
return parseHeadersWithFirstLine(bytes, offset, length);
}
protected void put(String key, String value) {
MultiValue hv = headers.putIfAbsent(key, new MultiValue(value));
if (hv != null)
hv.append(value);
}
protected void putIntoBuffer(byte[] bytes, int offset, int length) {
if (length == 0)
return;
if (buffer == null) {
buffer = new byte[length];
} else if (buffer.length - r < length) {
byte[] b = new byte[r + length];
if (r != 0)
System.arraycopy(buffer, 0, b, 0, r);
buffer = b;
}
System.arraycopy(bytes, offset, buffer, r, length);
r += length;
}
protected byte[] getCharsValue(byte[] chars, int offset, int length) {
if (r > 0) {
byte[] b = new byte[length + r];
System.arraycopy(buffer, 0, b, 0, r);
if (length > 0)
System.arraycopy(chars, offset, b, r, length);
r = 0;
return b;
}
byte[] b = new byte[length];
if (length > 0)
System.arraycopy(chars, offset, b, 0, length);
return b;
}
protected String getValue(byte[] chars, int offset, int length, String ifEmpty) {
String s = getValue(chars, offset, length);
return s.isEmpty() ? ifEmpty : s;
}
protected String getValue(byte[] chars, int offset, int length) {
ByteTree.Node byteTree = headersTree.getRoot();
if (r > 0) {
if (length < 0)
length = 0;
int bo = 0;
byte[] buffer = this.buffer;
while (bo < buffer.length && buffer[bo] <= ' ') {
bo++;
}
r -= bo;
byteTree = byteTree.getNode(buffer, bo, r);
if (byteTree != null) {
byteTree = byteTree.getNode(chars, offset, length);
if (byteTree != null) {
String value = byteTree.getValue();
if (value != null) {
r = 0;
return value;
} else if (onlyAllowedHeaders) {
r = 0;
return null;
}
} else if (onlyAllowedHeaders) {
r = 0;
return null;
}
} else if (onlyAllowedHeaders) {
r = 0;
return null;
}
byte[] b = new byte[length + r];
System.arraycopy(buffer, bo, b, 0, r);
if (length > 0)
System.arraycopy(chars, offset, b, r, length);
length = b.length;
offset = 0;
chars = b;
r = 0;
}
while (length > 0 && chars[offset] <= ' ') {
offset++;
length--;
}
while (length > 0 && chars[offset + length - 1] <= ' ') {
length--;
}
if (byteTree != null) {
String value = byteTree.get(chars, offset, length);
if (value != null || onlyAllowedHeaders)
return value;
}
return AsciiReader.read(chars, offset, length);
}
public Map<String, MultiValue> getHeaders() {
return headers;
}
public boolean isComplete() {
return complete;
}
}
|
package abi37_0_0.expo.modules.documentpicker;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import androidx.annotation.Nullable;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import abi37_0_0.org.unimodules.core.ExportedModule;
import abi37_0_0.org.unimodules.core.ModuleRegistry;
import abi37_0_0.org.unimodules.core.Promise;
import abi37_0_0.org.unimodules.core.interfaces.ActivityEventListener;
import abi37_0_0.org.unimodules.core.interfaces.ActivityProvider;
import abi37_0_0.org.unimodules.core.interfaces.ExpoMethod;
import abi37_0_0.org.unimodules.core.interfaces.services.UIManager;
import abi37_0_0.org.unimodules.core.utilities.FileUtilities;
public class DocumentPickerModule extends ExportedModule implements ActivityEventListener {
private static final String TAG = "ExpoDocumentPicker";
private static int OPEN_DOCUMENT_CODE = 4137;
private ModuleRegistry mModuleRegistry;
private ActivityProvider mActivityProvider;
private UIManager mUIManager;
@Nullable
private Promise mPromise;
private boolean mCopyToCacheDirectory = true;
public DocumentPickerModule(Context context) {
super(context);
}
@Override
public String getName() {
return TAG;
}
@Override
public void onCreate(ModuleRegistry moduleRegistry) {
mModuleRegistry = moduleRegistry;
if (mModuleRegistry != null) {
mActivityProvider = mModuleRegistry.getModule(ActivityProvider.class);
mUIManager = mModuleRegistry.getModule(UIManager.class);
if (mUIManager != null) {
mUIManager.registerActivityEventListener(this);
}
}
}
@ExpoMethod
public void getDocumentAsync(Map<String, Object> options, final Promise promise) {
if (mPromise != null) {
promise.reject("E_DOCUMENT_PICKER", "Different document picking in progress. Await other document picking first.");
return;
}
// mUIManger nullability suggests there's no listener registered for Activity result
if (mActivityProvider == null || mUIManager == null) {
promise.reject("E_MISSING_MODULES", "Missing core modules. Are you sure all the installed Expo modules are properly linked?");
return;
}
mPromise = promise;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (options.get("type") != null) {
intent.setType((String) options.get("type"));
} else {
intent.setType("*/*");
}
mCopyToCacheDirectory = options.get("copyToCacheDirectory") == null || (Boolean) options.get("copyToCacheDirectory");
mActivityProvider.getCurrentActivity().startActivityForResult(intent, OPEN_DOCUMENT_CODE);
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (requestCode == OPEN_DOCUMENT_CODE) {
if (mPromise == null) {
return;
}
Bundle result = new Bundle();
if (resultCode == Activity.RESULT_OK) {
result.putString("type", "success");
Uri uri = data.getData();
final ContentResolver contentResolver = getContext().getContentResolver();
try (Cursor cursor = contentResolver.query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
result.putString("name", displayName);
if (mCopyToCacheDirectory) {
result.putString("uri", Uri.fromFile(new File(writeDocument(uri, contentResolver, displayName))).toString());
} else {
result.putString("uri", uri.toString());
}
int sizeColumnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
if (!cursor.isNull(sizeColumnIndex)) {
int size = cursor.getInt(sizeColumnIndex);
result.putInt("size", size);
} else {
result.putParcelable("size", null);
}
}
}
} else {
result.putString("type", "cancel");
}
mPromise.resolve(result);
mPromise = null;
}
}
@Override
public void onNewIntent(Intent intent) {
// do nothing
}
private String writeDocument(Uri uri, ContentResolver contentResolver, String name) {
InputStream in;
OutputStream out = null;
String path = null;
try {
in = contentResolver.openInputStream(uri);
path = FileUtilities.generateOutputPath(
getContext().getCacheDir(),
"DocumentPicker",
FilenameUtils.getExtension(name)
);
File file = new File(path);
out = new FileOutputStream(file);
IOUtils.copy(in, out);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return path;
}
}
|
package com.distrimind.bouncycastle.openpgp.test;
import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.util.Date;
import java.util.Iterator;
import javax.crypto.Cipher;
import com.distrimind.bouncycastle.bcpg.HashAlgorithmTags;
import com.distrimind.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import com.distrimind.bouncycastle.jce.provider.BouncyCastleProvider;
import com.distrimind.bouncycastle.jce.spec.ElGamalParameterSpec;
import com.distrimind.bouncycastle.openpgp.PGPEncryptedData;
import com.distrimind.bouncycastle.openpgp.PGPException;
import com.distrimind.bouncycastle.openpgp.PGPKeyPair;
import com.distrimind.bouncycastle.openpgp.PGPKeyRingGenerator;
import com.distrimind.bouncycastle.openpgp.PGPPrivateKey;
import com.distrimind.bouncycastle.openpgp.PGPPublicKey;
import com.distrimind.bouncycastle.openpgp.PGPPublicKeyRing;
import com.distrimind.bouncycastle.openpgp.PGPSecretKey;
import com.distrimind.bouncycastle.openpgp.PGPSecretKeyRing;
import com.distrimind.bouncycastle.openpgp.PGPSignature;
import com.distrimind.bouncycastle.openpgp.jcajce.JcaPGPPublicKeyRing;
import com.distrimind.bouncycastle.openpgp.jcajce.JcaPGPPublicKeyRingCollection;
import com.distrimind.bouncycastle.openpgp.jcajce.JcaPGPSecretKeyRingCollection;
import com.distrimind.bouncycastle.openpgp.operator.PGPDigestCalculator;
import com.distrimind.bouncycastle.openpgp.operator.PGPDigestCalculatorProvider;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcaPGPPrivateKey;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;
import com.distrimind.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder;
import com.distrimind.bouncycastle.util.Arrays;
import com.distrimind.bouncycastle.util.encoders.Base64;
import com.distrimind.bouncycastle.util.encoders.Hex;
import com.distrimind.bouncycastle.util.test.SimpleTest;
public class PGPKeyRingTest
extends SimpleTest
{
byte[] pub1 = Base64.decode(
"mQGiBEA83v0RBADzKVLVCnpWQxX0LCsevw/3OLs0H7MOcLBQ4wMO9sYmzGYn"
+ "xpVj+4e4PiCP7QBayWyy4lugL6Lnw7tESvq3A4v3fefcxaCTkJrryiKn4+Cg"
+ "y5rIBbrSKNtCEhVi7xjtdnDjP5kFKgHYjVOeIKn4Cz/yzPG3qz75kDknldLf"
+ "yHxp2wCgwW1vAE5EnZU4/UmY7l8kTNkMltMEAJP4/uY4zcRwLI9Q2raPqAOJ"
+ "TYLd7h+3k/BxI0gIw96niQ3KmUZDlobbWBI+VHM6H99vcttKU3BgevNf8M9G"
+ "x/AbtW3SS4De64wNSU3189XDG8vXf0vuyW/K6Pcrb8exJWY0E1zZQ1WXT0gZ"
+ "W0kH3g5ro//Tusuil9q2lVLF2ovJA/0W+57bPzi318dWeNs0tTq6Njbc/GTG"
+ "FUAVJ8Ss5v2u6h7gyJ1DB334ExF/UdqZGldp0ugkEXaSwBa2R7d3HBgaYcoP"
+ "Ck1TrovZzEY8gm7JNVy7GW6mdOZuDOHTxyADEEP2JPxh6eRcZbzhGuJuYIif"
+ "IIeLOTI5Dc4XKeV32a+bWrQidGVzdCAoVGVzdCBrZXkpIDx0ZXN0QHViaWNh"
+ "bGwuY29tPohkBBMRAgAkBQJAPN79AhsDBQkB4TOABgsJCAcDAgMVAgMDFgIB"
+ "Ah4BAheAAAoJEJh8Njfhe8KmGDcAoJWr8xgPr75y/Cp1kKn12oCCOb8zAJ4p"
+ "xSvk4K6tB2jYbdeSrmoWBZLdMLACAAC5AQ0EQDzfARAEAJeUAPvUzJJb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IADAUCQG19pAUb"
+ "DAAAAAAKCRDHzsMv2A6+h5C6B/0QWPJb1L9a/CHU7Of3zfHvzJxnk4S5fia5"
+ "WBf+Ld7Y12CH+cVI/3PTXY63imIB3zLa21TNPC5cVFUJZI7hdwyJOW1R/QZa"
+ "vGl5sosIjORqwq8vs1oqpKWc3tRue+wt/JjCWxw8G6jQiwCzM6PltqtOAL5e"
+ "bJ4jZwzRmxs/RI4UYKO6EteipJA+i7OEZx0xGdL8mTl6HQx7vrJP9pM4/CtO"
+ "5CmjPK70e2gyoiOxx9RsSc+9H59YJCrldogCCIlNuW7cvkt8K/uYdN9GAbFG"
+ "RdanignRjpqSu3vTn8r/VO63+meZfKvmpI6i2b3o/UZ8Xh9lJu1vrRoNpnuP"
+ "Nifs+ljmsAFn");
char[] sec2pass1 = "sandhya".toCharArray();
char[] sec2pass2 = "psai".toCharArray();
byte[] pub3 = Base64.decode(
"mQGiBEB9BH0RBACtYQtE7tna6hgGyGLpq+ds3r2cLC0ISn5dNw7tm9vwiNVF"
+ "JA2N37RRrifw4PvgelRSvLaX3M3ZBqC9s1Metg3v4FSlIRtSLWCNpHSvNw7i"
+ "X8C2Xy9Hdlbh6Y/50o+iscojLRE14upfR1bIkcCZQGSyvGV52V2wBImUUZjV"
+ "s2ZngwCg7mu852vK7+euz4WaL7ERVYtq9CMEAJ5swrljerDpz/RQ4Lhp6KER"
+ "KyuI0PUttO57xINGshEINgYlZdGaZHRueHe7uKfI19mb0T4N3NJWaZ0wF+Cn"
+ "rixsq0VrTUfiwfZeGluNG73aTCeY45fVXMGTTSYXzS8T0LW100Xn/0g9HRyA"
+ "xUpuWo8IazxkMqHJis2uwriYKpAfA/9anvj5BS9p5pfPjp9dGM7GTMIYl5f2"
+ "fcP57f+AW1TVR6IZiMJAvAdeWuLtwLnJiFpGlnFz273pfl+sAuqm1yNceImR"
+ "2SDDP4+vtyycWy8nZhgEuhZx3W3cWMQz5WyNJSY1JJHh9TCQkCoN8E7XpVP4"
+ "zE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5tmESF6syggzGwOLG6gXgHFbZhBixk8Xl"
+ "IDcOQLRKt+rX+3qC5ZLTQblpQlvwvxn9CMpZturVGkJHapQJphRH8hCLXbzr"
+ "qpYsCx1zC5rtpJNuYQhASc0UAQv/2YhcBBMRAgAcBQJAfQV+AhsDBAsHAwID"
+ "FQIDAxYCAQIeAQIXgAAKCRCpzFfL42UDqfa2AJ9hjtEeDTbTEAuuSbzhYFxN"
+ "/qc0FACgsmzysdbBpuN65yK01tbEaeIMtqCwAgAAnQEUBEB9BH4QAwCqRuWO"
+ "rxm5v/8WWBtPEUZnYuu3WYxefRKn6ON5ka5Ymp4AfKpKqKqn982tjlG13GVE"
+ "P2ow11L4yQKGNm+VyVEapm7SpMD0SHg9vsJygAWrfMJnBYWSgE19W6o3ckUR"
+ "sWsAAwYDAKDCSiSxC3Z5/POaCehw5iHs/vmVk5Wn831LSZEEwkSohNDbIEry"
+ "ia/9tFXSt11AP4stJtZ0MH87/6JBbiIRD4JXcx+zfzchL7Teczr/06QMphSn"
+ "sAENupbhLupfpR+BbP4DAwIvYrn+YqRaaGBjvFK1fbxCt7ZM4I2W/3BC0lCX"
+ "m/NypKNspGflec8u96uUlA0fNCnxm6f9nbB0jpvoKi0g4iqAf+P2iEYEGBEC"
+ "AAYFAkB9BH4ACgkQqcxXy+NlA6mtMgCgvccZA/Sg7BXVpxli47SYhxSHoM4A"
+ "oNCOMplSnYTuh5ikKeBWtz36gC1psAIAAA==");
char[] sec3pass1 = "123456".toCharArray();
//
// GPG comment packets.
//
byte[] sec4 = Base64.decode(
"lQG7BD0PbK8RBAC0cW4Y2MZXmAmqYp5Txyw0kSQsFvwZKHNMFRv996IsN57URVF5"
+ "BGMVPRBi9dNucWbjiSYpiYN13wE9IuLZsvVaQojV4XWGRDc+Rxz9ElsXnsYQ3mZU"
+ "7H1bNQEofstChk4z+dlvPBN4GFahrIzn/CeVUn6Ut7dVdYbiTqviANqNXwCglfVA"
+ "2OEePvqFnGxs1jhJyPSOnTED/Rw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rYCcjuzkflFbQLtQb9uNj8a"
+ "hCpU4/4DAwIUxXlRMYE8uWCranzPo83FnBPRnGJ2aC9SqZWJYVUKIn4Vf2nu"
+ "pVvCGFja0usl1WfV72hqlNKEONq7lohJBBgRAgAJBQJBwqMzAhsCAAoJEOKc"
+ "Xvehtw4afisAoME/t8xz/rj/N7QRN9p8Ji8VPGSqAJ9K8eFJ+V0mxR+octJr"
+ "6neEEX/i1Q==");
public char[] sec9pass = "foo".toCharArray();
// version 4 keys with expiry dates
byte[] pub10 = Base64.decode(
"mQGiBEKqia0RBACc3hkufmscRSC4UvPZqMDsHm4+d/GXIr+3iNMSSEySJu8yk+k0"
+ "Xs11C/K+n+v1rnn2jGGknv+1lDY6w75TIcTE6o6HGKeIDxsAm8P3MhoGU1GNPamA"
+ "eTDeNybtrN/g6C65fCY9uI11hsUboYgQZ8ND22PB0VtvdOgq9D85qNUzxwCg1BbJ"
+ "ycAKd4VqEvQ2Zglp3dCSrFMD/Ambq1kZqYa69sp3b9BPKuAgUgUPoytOArEej3Bk"
+ "easAgAxNhWJy4GxigES3vk50rVi7w8XBuqbD1mQCzldF0HX0/A7PxLBv6od5uqqF"
+ "HFxIyxg/KBZLd9ZOrsSaoUWH58jZq98X/sFtJtRi5VuJagMxCIJD4mLgtMv7Unlb"
+ "/GrsA/9DEnObA/fNTgK70T+ZmPIS5tSt+bio30Aw4YGpPCGqpnm1u73b5kqX3U3B"
+ "P+vGDvFuqZYpqQA8byAueH0MbaDHI4CFugvShXvgysJxN7ov7/8qsZZUMfK1t2Nr"
+ "SAsPuKRbcY4gNKXIElKeXbyaET7vX7uAEKuxEwdYGFp/lNTkHLQgdGVzdCBrZXkg"
+ "KHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUCQqqJrQIbAwUJACTqAAYL"
+ "CQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzLAJ42AeCRIBBjv8r8qw9y"
+ "laNj2GZ1sACgiWYHVXMA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C+d"
+ "mWB783Lpzjb9evKzsxisTdx8/jHpUSS+r//6/Guyx3aA/zUw5bbftItW57mhuNNb"
+ "JTu7WrQgdGVzdCBrZXkgKHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUC"
+ "QqqJrQIbAwUJACTqAAYLCQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzL"
+ "AJ0cYPwKeoSReY14LqJtAjnkX7URHACgsRZWfpbalrSyDnq3TtZeGPUqGX+wAgAA"
+ "nQEUBEKqia4QAwClpIsfJaSTezDE16G+MRRdU7xpZdFA9WwxjjDG3rOmnl0m0/UF"
+ "3nv3x9xp4oy2O8Afqkz7/aIbm60qZ798np9whAVukNmCvjZQrJJmuNj8vGDFdonZ"
+ "mI7SYtXJLxxVrecAAwUC/35AeUOcUhoLKTGk2ZrZl98xu2Q3mdGrz/HvJkS/FLMw"
+ "k6arOrzGa18MkC2T27TGLz0KbkRhHio9MrIpsGEQOa6y0I50REd58rrhFFIHOI/m"
+ "nkcT3/VlbCf2tRQh7WgD9f4DAwLssmOjVC+dmWDXVLRopzxbBGOvodp/LZoSDb56"
+ "gNJjDMJ1aXqWW9qTAg1CFjBq73J3oFpVzInXZ8+Q8inxv7bnWiHbiE8EGBECAA8F"
+ "AkKqia4CGwwFCQAk6gAACgkQ4w0TkGUaiMzdqgCgl2jw5hfk/JsyjulQqe1Nps1q"
+ "Lx0AoMdnFMZmTMLHn8scUW2j9XO312tmsAIAAA==");
public char[] sec10pass = "test".toCharArray();
public byte[] subKeyBindingKey = Base64.decode(
"mQGiBDWagYwRBAD7UcH4TAIp7tmUoHBNxVxCVz2ZrNo79M6fV63riOiH2uDxfIpr"
+ "IrL0cM4ehEKoqlhngjDhX60eJrOw1nC5BpYZRnDnyDYT4wTWRguxObzGq9pqA1dM"
+ "oPTJhkFZVIBgFY99/ULRqaUYIhFGgBtnwS70J8/L/PGVc3DmWRLMkTDjSQCg/5Nh"
+ "MCjMK++MdYMcM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5jbcfj+KY9/25bs0ga7kLHNZia"
+ "zbCxJdF+W179z3nudQxRaXG/0XISIH7ziZbSVni69sKc1osk1+OoOMbSuZ86z535"
+ "Pln4fXclkFE927HxfbWoO+60hkOLKh7x+8fC82b3x9vCETujEaxrscO2xS7/MYXP"
+ "8t1ffriTDmhuIuQS2q4fLgeWdqrODrMhrD8Dq7e558gzp30ZCqpiS7EmKGczL7B8"
+ "gXxbBCVSTxYMJheXt2xMXsuJAD8DBRg1moGU8gBo4j+O/10RAgWdAKCPhaFIXuC8"
+ "/cdiNMxTDw9ug3De5QCfYXmDzRSFUu/nrCi8yz/l09wsnxo=");
public byte[] subKeyBindingCheckSum = Base64.decode("3HU+");
//
// PGP8 with SHA1 checksum.
//
public byte[] rewrapKey = Base64.decode(
"lQOWBEUPOQgBCADdjPTtl8oOwqJFA5WU8p7oDK5KRWfmXeXUZr+ZJipemY5RSvAM"
+ "rxqsM47LKYbmXOJznXCQ8+PPa+VxXAsI1CXFHIFqrXSwvB/DUmb4Ec9EuvNd18Zl"
+ "hJAybzmV2KMkaUp9oG/DUvxZJqkpUddNfwqZu0KKKZWF5gwW5Oy05VCpaJxQVXFS"
+ "whdbRfwEENJiNx4RB3OlWhIjY2p+TgZfgQjiGB9i15R+37sV7TqzBUZF4WWcnIRQ"
+ "DnpUfxHgxQ0wO/h/aooyRHSpIx5i4oNpMYq9FNIyakEx/Bomdbs5hW9dFxhrE8Es"
+ "UViAYITgTsyROxmgGatGG09dcmVDJVYF4i7JAAYpAAf/VnVyUDs8HrxYTOIt4rYY"
+ "jIHToBsV0IiLpA8fEA7k078L1MwSwERVVe6oHVTjeR4A9OxE52Vroh2eOLnF3ftf"
+ "6QThVVZr+gr5qeG3yvQ36N7PXNEVOlkyBzGmFQNe4oCA+NR2iqnAIspnekVmwJV6"
+ "xVvPCjWw/A7ZArDARpfthspwNcJAp4SWfoa2eKzvUTznTyqFu2PSS5fwQZUgOB0P"
+ "Y2FNaKeqV8vEZu4SUWwLOqXBQ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ig = Base64.decode(
"mI0ETdvOgQEEALoI2a39TRk1HReEB6DP9Bu3ShZUce+/Oeg9RIL9aUFuCsNdhu02" +
"REEHjO29Jz8daPgrnJDfFepNLD6iKKru2m9P30qnhsHMIAshO2Ozfh6wKwuHRqR3" +
"L4gBDu7cCB6SLwPoD8AYG0yQSM+Do10Td87RlStxCgxpMK6R3TsRkxcFABEBAAG0" +
"OlVNTEFVVFNUQVJUOsOEw6TDlsO2w5zDvMOfOlVNTEFURU5ERSA8YXNkbGFrc2Rs" +
"QGFrc2RqLmNvbT6IuAQTAQIAIgUCTdvOgQIbAwYLCQgHAwIGFQgCCQoLBBYCAwEC" +
"HgECF4AACgkQP8kDwm8AOFiArAP/ZXrlZJB1jFEjyBb04ckpE6F/aJuSYIXf0Yx5" +
"T2eS+lA69vYuqKRC1qNROBrAn/WGNOQBFNEgGoy3F3gV5NgpIphnyIEZdZWGY2rv" +
"yjunKWlioZjWc/xbSbvpvJ3Q8RyfDXBOkDEB6uF1ksimw2eJSOUTkF9AQfS5f4rT" +
"5gs013G4jQRN286BAQQApVbjd8UhsQLB4TpeKn9+dDXAfikGgxDOb19XisjRiWxA" +
"+bKFxu5tRt6fxXl6BGSGT7DhoVbNkcJGVQFYcbR31UGKCVYcWSL3yfz+PiVuf1UB" +
"Rp44cXxxqxrLqKp1rk3dGvV4Ayy8lkk3ncDGPez6lIKvj3832yVtAzUOX1QOg9EA" +
"EQEAAYifBBgBAgAJBQJN286BAhsMAAoJED/JA8JvADhYQ80D/R3TX0FBMHs/xqEh" +
"tiS86XP/8pW6eMm2eaAYINxoDY3jmDMv2HFQ+YgrYXgqGr6eVGqDMNPj4W8VBoOt" +
"iYW7+SWY76AAl+gmWIMm2jbN8bZXFk4jmIxpycHCrtoXX8rUk/0+se8NvbmAdMGK" +
"POOoD7oxdRmJSU5hSspOCHrCwCa3");
// Key from https://www.angelfire.com/pr/pgpf/pgpoddities.html
private static final char[] v3KeyPass = "test@key.test".toCharArray();
private static final byte[] pubv3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dD3yIsxx8" +
"Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdXQ6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaG" +
"xAMZyAcpesqVDNmWn6vQClCbAkbTCD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwACAgf/cugy" +
"0nyWpA6GxoNqpdky1oCEbgII/lFKkGfQb/sHLgHURjmiaDXSuRJDRXC6YVC0HWqA+bfknR5m" +
"o1cvohu4GL/oul1eD85UfU29vg5Hr6f601o6xWVCiHF14B24JvO7jhYMd1MQRl7PVzH0a1Gp" +
"4hSoEvsUjU1HhGUhmMpUxwGJyIFt4RTkqKWK15omuJf4TLT47T58n9uClTNyxpx+oJGaiD0O" +
"SiEn9d4w5XFewhyXFQhisr99979dLq+buvH1QueMkVDExF4D8LN5gid8JPy/RqFxnHE8AcSF" +
"XHz9ou8m936pkyKYIMQkCwdw7/Wv7MK64ZED2zOnXnSb/JWY2YhGBBgRAgAGBQI38wtiAAoJ" +
"EKg2SsWJxEiGJdcAoIQOLuHGGS01Gz5WUpiQZYRtRMIYAKDuYx6bfQngRMs3/gEG0zoSGohY" +
"lQ=="
);
public void test1()
throws Exception
{
JcaPGPPublicKeyRingCollection pubRings = new JcaPGPPublicKeyRingCollection(pub1);
int count = 0;
Iterator rIt = pubRings.getKeyRings();
while (rIt.hasNext())
{
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpPub.getEncoded();
pgpPub = new PGPPublicKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpPub.getPublicKeys();
while (it.hasNext())
{
keyCount++;
PGPPublicKey pubKey = (PGPPublicKey)it.next();
Iterator sIt = pubKey.getSignatures();
while (sIt.hasNext())
{
((PGPSignature)sIt.next()).getSignatureType();
}
}
if (keyCount != 2)
{
fail("wrong number of public keys");
}
}
if (count != 1)
{
fail("wrong number of public keyrings");
}
//
// exact match
//
rIt = pubRings.getKeyRings("test (Test key) <test@ubicall.com>");
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 1)
{
fail("wrong number of public keyrings on exact match");
}
//
// partial match 1 expected
//
rIt = pubRings.getKeyRings("test", true);
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 1)
{
fail("wrong number of public keyrings on partial match 1");
}
//
// partial match 0 expected
//
rIt = pubRings.getKeyRings("XXX", true);
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 0)
{
fail("wrong number of public keyrings on partial match 0");
}
//
// case-insensitive partial match
//
rIt = pubRings.getKeyRings("TEST@ubicall.com", true, true);
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 1)
{
fail("wrong number of public keyrings on case-insensitive partial match");
}
JcaPGPSecretKeyRingCollection secretRings = new JcaPGPSecretKeyRingCollection(sec1);
rIt = secretRings.getKeyRings();
count = 0;
while (rIt.hasNext())
{
PGPSecretKeyRing pgpSec = (PGPSecretKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpSec.getEncoded();
pgpSec = new PGPSecretKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpSec.getSecretKeys();
while (it.hasNext())
{
keyCount++;
PGPSecretKey k = (PGPSecretKey)it.next();
PGPPublicKey pk = k.getPublicKey();
pk.getSignatures();
byte[] pkBytes = pk.getEncoded();
PGPPublicKeyRing pkR = new PGPPublicKeyRing(pkBytes, new JcaKeyFingerprintCalculator());
}
if (keyCount != 2)
{
fail("wrong number of secret keys");
}
}
if (count != 1)
{
fail("wrong number of secret keyrings");
}
//
// exact match
//
rIt = secretRings.getKeyRings("test (Test key) <test@ubicall.com>");
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 1)
{
fail("wrong number of secret keyrings on exact match");
}
//
// partial match 1 expected
//
rIt = secretRings.getKeyRings("test", true);
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 1)
{
fail("wrong number of secret keyrings on partial match 1");
}
//
// exact match 0 expected
//
rIt = secretRings.getKeyRings("test", false);
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 0)
{
fail("wrong number of secret keyrings on partial match 0");
}
//
// case-insensitive partial match
//
rIt = secretRings.getKeyRings("TEST@ubicall.com", true, true);
count = 0;
while (rIt.hasNext())
{
count++;
rIt.next();
}
if (count != 1)
{
fail("wrong number of secret keyrings on case-insensitive partial match");
}
}
public void test2()
throws Exception
{
JcaPGPPublicKeyRingCollection pubRings = new JcaPGPPublicKeyRingCollection(pub2);
int count = 0;
byte[] encRing = pubRings.getEncoded();
pubRings = new JcaPGPPublicKeyRingCollection(encRing);
Iterator rIt = pubRings.getKeyRings();
while (rIt.hasNext())
{
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpPub.getEncoded();
pgpPub = new PGPPublicKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpPub.getPublicKeys();
while (it.hasNext())
{
PGPPublicKey pk = (PGPPublicKey)it.next();
byte[] pkBytes = pk.getEncoded();
PGPPublicKeyRing pkR = new PGPPublicKeyRing(pkBytes, new JcaKeyFingerprintCalculator());
keyCount++;
}
if (keyCount != 2)
{
fail("wrong number of public keys");
}
}
if (count != 2)
{
fail("wrong number of public keyrings");
}
JcaPGPSecretKeyRingCollection secretRings = new JcaPGPSecretKeyRingCollection(sec2);
rIt = secretRings.getKeyRings();
count = 0;
encRing = secretRings.getEncoded();
secretRings = new JcaPGPSecretKeyRingCollection(encRing);
while (rIt.hasNext())
{
PGPSecretKeyRing pgpSec = (PGPSecretKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpSec.getEncoded();
pgpSec = new PGPSecretKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpSec.getSecretKeys();
while (it.hasNext())
{
keyCount++;
PGPSecretKey k = (PGPSecretKey)it.next();
PGPPublicKey pk = k.getPublicKey();
if (pk.getKeyID() == -1413891222336124627L)
{
int sCount = 0;
Iterator sIt = pk.getSignaturesOfType(PGPSignature.SUBKEY_BINDING);
while (sIt.hasNext())
{
int type = ((PGPSignature)sIt.next()).getSignatureType();
if (type != PGPSignature.SUBKEY_BINDING)
{
fail("failed to return correct signature type");
}
sCount++;
}
if (sCount != 1)
{
fail("failed to find binding signature");
}
}
pk.getSignatures();
if (k.getKeyID() == -4049084404703773049L
|| k.getKeyID() == -1413891222336124627L)
{
k.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(sec2pass1));
}
else if (k.getKeyID() == -6498553574938125416L
|| k.getKeyID() == 59034765524361024L)
{
k.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(sec2pass2));
}
}
if (keyCount != 2)
{
fail("wrong number of secret keys");
}
}
if (count != 2)
{
fail("wrong number of secret keyrings");
}
}
public void test3()
throws Exception
{
JcaPGPPublicKeyRingCollection pubRings = new JcaPGPPublicKeyRingCollection(pub3);
int count = 0;
byte[] encRing = pubRings.getEncoded();
pubRings = new JcaPGPPublicKeyRingCollection(encRing);
Iterator rIt = pubRings.getKeyRings();
while (rIt.hasNext())
{
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpPub.getEncoded();
pgpPub = new PGPPublicKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpPub.getPublicKeys();
while (it.hasNext())
{
keyCount++;
PGPPublicKey pubK = (PGPPublicKey)it.next();
pubK.getSignatures();
}
if (keyCount != 2)
{
fail("wrong number of public keys");
}
}
if (count != 1)
{
fail("wrong number of public keyrings");
}
JcaPGPSecretKeyRingCollection secretRings = new JcaPGPSecretKeyRingCollection(sec3);
rIt = secretRings.getKeyRings();
count = 0;
encRing = secretRings.getEncoded();
secretRings = new JcaPGPSecretKeyRingCollection(encRing);
while (rIt.hasNext())
{
PGPSecretKeyRing pgpSec = (PGPSecretKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpSec.getEncoded();
pgpSec = new PGPSecretKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpSec.getSecretKeys();
while (it.hasNext())
{
keyCount++;
PGPSecretKey k = (PGPSecretKey)it.next();
k.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(sec3pass1));
}
if (keyCount != 2)
{
fail("wrong number of secret keys");
}
}
if (count != 1)
{
fail("wrong number of secret keyrings");
}
}
public void test4()
throws Exception
{
JcaPGPSecretKeyRingCollection secretRings = new JcaPGPSecretKeyRingCollection(sec4);
Iterator rIt = secretRings.getKeyRings();
int count = 0;
byte[] encRing = secretRings.getEncoded();
secretRings = new JcaPGPSecretKeyRingCollection(encRing);
while (rIt.hasNext())
{
PGPSecretKeyRing pgpSec = (PGPSecretKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpSec.getEncoded();
pgpSec = new PGPSecretKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpSec.getSecretKeys();
while (it.hasNext())
{
keyCount++;
PGPSecretKey k = (PGPSecretKey)it.next();
k.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(sec3pass1));
}
if (keyCount != 2)
{
fail("test4 - wrong number of secret keys");
}
keyCount = 0;
it = pgpSec.getPublicKeys();
while (it.hasNext())
{
keyCount++;
PGPPublicKey k = (PGPPublicKey)it.next(); // make sure it's what we think it is!
}
if (keyCount != 2)
{
fail("test4 - wrong number of public keys");
}
}
if (count != 1)
{
fail("wrong number of secret keyrings");
}
}
public void test5()
throws Exception
{
JcaPGPPublicKeyRingCollection pubRings = new JcaPGPPublicKeyRingCollection(pub5);
int count = 0;
byte[] encRing = pubRings.getEncoded();
pubRings = new JcaPGPPublicKeyRingCollection(encRing);
Iterator rIt = pubRings.getKeyRings();
while (rIt.hasNext())
{
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpPub.getEncoded();
pgpPub = new PGPPublicKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpPub.getPublicKeys();
while (it.hasNext())
{
keyCount++;
it.next();
}
if (keyCount != 2)
{
fail("wrong number of public keys");
}
}
if (count != 1)
{
fail("wrong number of public keyrings");
}
if (noIDEA())
{
return;
}
JcaPGPSecretKeyRingCollection secretRings = new JcaPGPSecretKeyRingCollection(sec5);
rIt = secretRings.getKeyRings();
count = 0;
encRing = secretRings.getEncoded();
secretRings = new JcaPGPSecretKeyRingCollection(encRing);
while (rIt.hasNext())
{
PGPSecretKeyRing pgpSec = (PGPSecretKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpSec.getEncoded();
pgpSec = new PGPSecretKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpSec.getSecretKeys();
while (it.hasNext())
{
keyCount++;
PGPSecretKey k = (PGPSecretKey)it.next();
k.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(sec5pass1));
}
if (keyCount != 2)
{
fail("wrong number of secret keys");
}
}
if (count != 1)
{
fail("wrong number of secret keyrings");
}
}
private boolean noIDEA()
{
try
{
Cipher.getInstance("IDEA", "BC");
return false;
}
catch (Exception e)
{
return true;
}
}
public void test6()
throws Exception
{
JcaPGPPublicKeyRingCollection pubRings = new JcaPGPPublicKeyRingCollection(pub6);
Iterator rIt = pubRings.getKeyRings();
while (rIt.hasNext())
{
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next();
Iterator it = pgpPub.getPublicKeys();
while (it.hasNext())
{
PGPPublicKey k = (PGPPublicKey)it.next();
if (k.getKeyID() == 0x5ce086b5b5a18ff4L)
{
int count = 0;
Iterator sIt = k.getSignaturesOfType(PGPSignature.SUBKEY_REVOCATION);
while (sIt.hasNext())
{
PGPSignature sig = (PGPSignature)sIt.next();
count++;
}
if (count != 1)
{
fail("wrong number of revocations in test6.");
}
}
}
}
byte[] encRing = pubRings.getEncoded();
}
public void revocationTest()
throws Exception
{
PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(pub7, new JcaKeyFingerprintCalculator());
Iterator it = pgpPub.getPublicKeys();
PGPPublicKey masterKey = null;
while (it.hasNext())
{
PGPPublicKey k = (PGPPublicKey)it.next();
if (k.isMasterKey())
{
masterKey = k;
continue;
}
}
int count = 0;
PGPSignature sig = null;
Iterator sIt = masterKey.getSignaturesOfType(PGPSignature.KEY_REVOCATION);
while (sIt.hasNext())
{
sig = (PGPSignature)sIt.next();
count++;
}
if (count != 1)
{
fail("wrong number of revocations in test7.");
}
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), masterKey);
if (!sig.verifyCertification(masterKey))
{
fail("failed to verify revocation certification");
}
pgpPub = new PGPPublicKeyRing(pub7sub, new JcaKeyFingerprintCalculator());
it = pgpPub.getPublicKeys();
masterKey = null;
while (it.hasNext())
{
PGPPublicKey k = (PGPPublicKey)it.next();
if (k.isMasterKey())
{
masterKey = k;
continue;
}
count = 0;
sig = null;
sIt = k.getSignaturesOfType(PGPSignature.SUBKEY_REVOCATION);
while (sIt.hasNext())
{
sig = (PGPSignature)sIt.next();
count++;
}
if (count != 1)
{
fail("wrong number of revocations in test7 subkey.");
}
if (sig.getSignatureType() != PGPSignature.SUBKEY_REVOCATION)
{
fail("wrong signature found");
}
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), masterKey);
if (!sig.verifyCertification(masterKey, k))
{
fail("failed to verify revocation certification of subkey");
}
}
}
public void test8()
throws Exception
{
JcaPGPPublicKeyRingCollection pubRings = new JcaPGPPublicKeyRingCollection(pub8);
int count = 0;
byte[] encRing = pubRings.getEncoded();
pubRings = new JcaPGPPublicKeyRingCollection(encRing);
Iterator rIt = pubRings.getKeyRings();
while (rIt.hasNext())
{
PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpPub.getEncoded();
pgpPub = new PGPPublicKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpPub.getPublicKeys();
while (it.hasNext())
{
keyCount++;
it.next();
}
if (keyCount != 2)
{
fail("wrong number of public keys");
}
}
if (count != 2)
{
fail("wrong number of public keyrings");
}
JcaPGPSecretKeyRingCollection secretRings = new JcaPGPSecretKeyRingCollection(sec8);
rIt = secretRings.getKeyRings();
count = 0;
encRing = secretRings.getEncoded();
secretRings = new JcaPGPSecretKeyRingCollection(encRing);
while (rIt.hasNext())
{
PGPSecretKeyRing pgpSec = (PGPSecretKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpSec.getEncoded();
pgpSec = new PGPSecretKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpSec.getSecretKeys();
while (it.hasNext())
{
keyCount++;
PGPSecretKey k = (PGPSecretKey)it.next();
k.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(sec8pass));
}
if (keyCount != 2)
{
fail("wrong number of secret keys");
}
}
if (count != 1)
{
fail("wrong number of secret keyrings");
}
}
public void test9()
throws Exception
{
JcaPGPSecretKeyRingCollection secretRings = new JcaPGPSecretKeyRingCollection(sec9);
Iterator rIt = secretRings.getKeyRings();
int count = 0;
byte[] encRing = secretRings.getEncoded();
secretRings = new JcaPGPSecretKeyRingCollection(encRing);
while (rIt.hasNext())
{
PGPSecretKeyRing pgpSec = (PGPSecretKeyRing)rIt.next();
count++;
int keyCount = 0;
byte[] bytes = pgpSec.getEncoded();
pgpSec = new PGPSecretKeyRing(bytes, new JcaKeyFingerprintCalculator());
Iterator it = pgpSec.getSecretKeys();
while (it.hasNext())
{
keyCount++;
PGPSecretKey k = (PGPSecretKey)it.next();
PGPPrivateKey pKey = k.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(sec9pass));
if (keyCount == 1 && pKey != null)
{
fail("primary secret key found, null expected");
}
}
if (keyCount != 3)
{
fail("wrong number of secret keys");
}
}
if (count != 1)
{
fail("wrong number of secret keyrings");
}
}
public void test10()
throws Exception
{
PGPSecretKeyRing secretRing = new PGPSecretKeyRing(sec10, new JcaKeyFingerprintCalculator());
Iterator secretKeys = secretRing.getSecretKeys();
while (secretKeys.hasNext())
{
PGPPublicKey pubKey = ((PGPSecretKey)secretKeys.next()).getPublicKey();
if (pubKey.getValidDays() != 28)
{
fail("days wrong on secret key ring");
}
if (pubKey.getValidSeconds() != 28 * 24 * 60 * 60)
{
fail("seconds wrong on secret key ring");
}
}
PGPPublicKeyRing publicRing = new PGPPublicKeyRing(pub10, new JcaKeyFingerprintCalculator());
Iterator publicKeys = publicRing.getPublicKeys();
while (publicKeys.hasNext())
{
PGPPublicKey pubKey = (PGPPublicKey)publicKeys.next();
if (pubKey.getValidDays() != 28)
{
fail("days wrong on public key ring");
}
if (pubKey.getValidSeconds() != 28 * 24 * 60 * 60)
{
fail("seconds wrong on public key ring");
}
}
}
public void generateTest()
throws Exception
{
char[] passPhrase = "hello".toCharArray();
KeyPairGenerator dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");
dsaKpg.initialize(512);
//
// this takes a while as the key generator has to generate some DSA params
// before it generates the key.
//
KeyPair dsaKp = dsaKpg.generateKeyPair();
KeyPairGenerator elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC");
BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
ElGamalParameterSpec elParams = new ElGamalParameterSpec(p, g);
elgKpg.initialize(512);
//
// this is quicker because we are using pregenerated parameters.
//
KeyPair elgKp = elgKpg.generateKeyPair();
PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date());
PGPKeyPair elgKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date());
PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair,
"test", sha1Calc, null, null, new JcaPGPContentSignerBuilder(PGPPublicKey.DSA, HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).setProvider("BC").build(passPhrase));
keyRingGen.addSubKey(elgKeyPair);
PGPSecretKeyRing keyRing = keyRingGen.generateSecretKeyRing();
keyRing.getSecretKey().extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passPhrase));
PGPPublicKeyRing pubRing = keyRingGen.generatePublicKeyRing();
PGPPublicKey vKey = null;
PGPPublicKey sKey = null;
Iterator it = pubRing.getPublicKeys();
while (it.hasNext())
{
PGPPublicKey pk = (PGPPublicKey)it.next();
if (pk.isMasterKey())
{
vKey = pk;
}
else
{
sKey = pk;
}
}
Iterator sIt = sKey.getSignatures();
while (sIt.hasNext())
{
PGPSignature sig = (PGPSignature)sIt.next();
if (sig.getKeyID() == vKey.getKeyID()
&& sig.getSignatureType() == PGPSignature.SUBKEY_BINDING)
{
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), vKey);
if (!sig.verifyCertification(vKey, sKey))
{
fail("failed to verify sub-key signature.");
}
}
}
}
private void insertMasterTest()
throws Exception
{
char[] passPhrase = "hello".toCharArray();
KeyPairGenerator rsaKpg = KeyPairGenerator.getInstance("RSA", "BC");
rsaKpg.initialize(512);
//
// this is quicker because we are using pregenerated parameters.
//
KeyPair rsaKp = rsaKpg.generateKeyPair();
PGPKeyPair rsaKeyPair1 = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, rsaKp, new Date());
rsaKp = rsaKpg.generateKeyPair();
PGPKeyPair rsaKeyPair2 = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, rsaKp, new Date());
PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsaKeyPair1,
"test", sha1Calc, null, null, new JcaPGPContentSignerBuilder(PGPPublicKey.RSA_SIGN, HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).setProvider("BC").build(passPhrase));
PGPSecretKeyRing secRing1 = keyRingGen.generateSecretKeyRing();
PGPPublicKeyRing pubRing1 = keyRingGen.generatePublicKeyRing();
keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsaKeyPair2,
"test", sha1Calc, null, null, new JcaPGPContentSignerBuilder(PGPPublicKey.RSA_SIGN, HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).setProvider("BC").build(passPhrase));
PGPSecretKeyRing secRing2 = keyRingGen.generateSecretKeyRing();
PGPPublicKeyRing pubRing2 = keyRingGen.generatePublicKeyRing();
try
{
PGPPublicKeyRing.insertPublicKey(pubRing1, pubRing2.getPublicKey());
fail("adding second master key (public) should throw an IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
if (!e.getMessage().equals("cannot add a master key to a ring that already has one"))
{
fail("wrong message in public test");
}
}
try
{
PGPSecretKeyRing.insertSecretKey(secRing1, secRing2.getSecretKey());
fail("adding second master key (secret) should throw an IllegalArgumentException");
}
catch (IllegalArgumentException e)
{
if (!e.getMessage().equals("cannot add a master key to a ring that already has one"))
{
fail("wrong message in secret test");
}
}
}
public void generateSha1Test()
throws Exception
{
char[] passPhrase = "hello".toCharArray();
KeyPairGenerator dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");
dsaKpg.initialize(512);
//
// this takes a while as the key generator has to generate some DSA params
// before it generates the key.
//
KeyPair dsaKp = dsaKpg.generateKeyPair();
KeyPairGenerator elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC");
BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
ElGamalParameterSpec elParams = new ElGamalParameterSpec(p, g);
elgKpg.initialize(512);
//
// this is quicker because we are using pregenerated parameters.
//
KeyPair elgKp = elgKpg.generateKeyPair();
PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date());
PGPKeyPair elgKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date());
PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair,
"test", sha1Calc, null, null, new JcaPGPContentSignerBuilder(PGPPublicKey.DSA, HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).setProvider("BC").build(passPhrase));
keyRingGen.addSubKey(elgKeyPair);
PGPSecretKeyRing keyRing = keyRingGen.generateSecretKeyRing();
keyRing.getSecretKey().extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passPhrase));
if (!keyRing.getSecretKey().getPublicKey().equals(keyRing.getPublicKey()))
{
fail("secret key public key mismatch");
}
PGPPublicKeyRing pubRing = keyRingGen.generatePublicKeyRing();
PGPPublicKey vKey = null;
PGPPublicKey sKey = null;
Iterator it = pubRing.getPublicKeys();
while (it.hasNext())
{
PGPPublicKey pk = (PGPPublicKey)it.next();
if (pk.isMasterKey())
{
vKey = pk;
}
else
{
sKey = pk;
}
}
// check key id fetch
if (keyRing.getPublicKey(vKey.getKeyID()).getKeyID() != vKey.getKeyID())
{
fail("secret key public key mismatch - vKey");
}
if (keyRing.getPublicKey(sKey.getKeyID()).getKeyID() != sKey.getKeyID())
{
fail("secret key public key mismatch - sKey");
}
Iterator sIt = sKey.getSignatures();
while (sIt.hasNext())
{
PGPSignature sig = (PGPSignature)sIt.next();
if (sig.getKeyID() == vKey.getKeyID()
&& sig.getSignatureType() == PGPSignature.SUBKEY_BINDING)
{
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), vKey);
if (!sig.verifyCertification(vKey, sKey))
{
fail("failed to verify sub-key signature.");
}
}
}
}
private void test11()
throws Exception
{
PGPPublicKeyRing pubRing = new PGPPublicKeyRing(subKeyBindingKey, new JcaKeyFingerprintCalculator());
Iterator it = pubRing.getPublicKeys();
while (it.hasNext())
{
PGPPublicKey key = (PGPPublicKey)it.next();
if (key.getValidSeconds() != 0)
{
fail("expiration time non-zero");
}
}
}
private void rewrapTest()
throws Exception
{
// Read the secret key rings
JcaPGPSecretKeyRingCollection privRings = new JcaPGPSecretKeyRingCollection(
new ByteArrayInputStream(rewrapKey));
char[] newPass = "fred".toCharArray();
Iterator rIt = privRings.getKeyRings();
if (rIt.hasNext())
{
PGPSecretKeyRing pgpPriv= (PGPSecretKeyRing)rIt.next();
Iterator it = pgpPriv.getSecretKeys();
while (it.hasNext())
{
PGPSecretKey pgpKey = (PGPSecretKey)it.next();
long oldKeyID = pgpKey.getKeyID();
// re-encrypt the key with an empty password
pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey);
pgpKey = PGPSecretKey.copyWithNewPassword(
pgpKey,
new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(rewrapPass),
null);
pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey);
// this should succeed
PGPPrivateKey privTmp = pgpKey.extractPrivateKey(null);
if (pgpKey.getKeyID() != oldKeyID)
{
fail("key ID mismatch");
}
}
it = pgpPriv.getSecretKeys();
while (it.hasNext())
{
PGPSecretKey pgpKey = (PGPSecretKey)it.next();
long oldKeyID = pgpKey.getKeyID();
// re-encrypt the key with an empty password
pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey);
pgpKey = PGPSecretKey.copyWithNewPassword(
pgpKey,
null,
new JcePBESecretKeyEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5).setProvider("BC").build(newPass));
pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey);
// this should succeed
PGPPrivateKey privTmp = pgpKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(newPass));
if (pgpKey.getKeyID() != oldKeyID)
{
fail("key ID mismatch");
}
}
}
}
private void rewrapTestV3()
throws Exception
{
// Read the secret key rings
JcaPGPSecretKeyRingCollection privRings = new JcaPGPSecretKeyRingCollection(
new ByteArrayInputStream(privv3));
char[] newPass = "fred".toCharArray();
Iterator rIt = privRings.getKeyRings();
if (rIt.hasNext())
{
PGPSecretKeyRing pgpPriv = (PGPSecretKeyRing)rIt.next();
Iterator it = pgpPriv.getSecretKeys();
while (it.hasNext())
{
PGPSecretKey pgpKey = (PGPSecretKey)it.next();
long oldKeyID = pgpKey.getKeyID();
// re-encrypt the key with an empty password
pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey);
pgpKey = PGPSecretKey.copyWithNewPassword(
pgpKey,
new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(v3KeyPass),
null);
pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey);
// this should succeed
PGPPrivateKey privTmp = pgpKey.extractPrivateKey(null);
if (pgpKey.getKeyID() != oldKeyID)
{
fail("key ID mismatch");
}
}
it = pgpPriv.getSecretKeys();
while (it.hasNext())
{
PGPSecretKey pgpKey = (PGPSecretKey)it.next();
long oldKeyID = pgpKey.getKeyID();
// re-encrypt the key with an empty password
pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey);
pgpKey = PGPSecretKey.copyWithNewPassword(
pgpKey,
null,
new JcePBESecretKeyEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5, new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build().get(HashAlgorithmTags.MD5)).setProvider("BC").build(newPass));
pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey);
// this should succeed
PGPPrivateKey privTmp = pgpKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(newPass));
if (pgpKey.getKeyID() != oldKeyID)
{
fail("key ID mismatch");
}
}
}
}
private void rewrapTestMD5()
throws Exception
{
// Read the secret key rings
JcaPGPSecretKeyRingCollection privRings = new JcaPGPSecretKeyRingCollection(
new ByteArrayInputStream(rewrapKey));
char[] newPass = "fred".toCharArray();
Iterator rIt = privRings.getKeyRings();
if (rIt.hasNext())
{
PGPSecretKeyRing pgpPriv= (PGPSecretKeyRing)rIt.next();
Iterator it = pgpPriv.getSecretKeys();
PGPDigestCalculatorProvider calcProvider = new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build();
while (it.hasNext())
{
PGPSecretKey pgpKey = (PGPSecretKey)it.next();
long oldKeyID = pgpKey.getKeyID();
// re-encrypt the key with an empty password
pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey);
pgpKey = PGPSecretKey.copyWithNewPassword(
pgpKey,
new JcePBESecretKeyDecryptorBuilder(calcProvider).setProvider("BC").build(rewrapPass),
null);
pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey);
// this should succeed
PGPPrivateKey privTmp = pgpKey.extractPrivateKey(null);
if (pgpKey.getKeyID() != oldKeyID)
{
fail("key ID mismatch");
}
}
it = pgpPriv.getSecretKeys();
while (it.hasNext())
{
PGPSecretKey pgpKey = (PGPSecretKey)it.next();
long oldKeyID = pgpKey.getKeyID();
// re-encrypt the key with an empty password
pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey);
pgpKey = PGPSecretKey.copyWithNewPassword(
pgpKey,
null,
new JcePBESecretKeyEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5, calcProvider.get(HashAlgorithmTags.MD5)).setProvider("BC").build(newPass));
pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey);
// this should succeed
PGPPrivateKey privTmp = pgpKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(calcProvider).setProvider("BC").build(newPass));
if (pgpKey.getKeyID() != oldKeyID)
{
fail("key ID mismatch");
}
}
}
}
private void testPublicKeyRingWithX509()
throws Exception
{
checkPublicKeyRingWithX509(pubWithX509);
PGPPublicKeyRing pubRing = new PGPPublicKeyRing(pubWithX509, new JcaKeyFingerprintCalculator());
checkPublicKeyRingWithX509(pubRing.getEncoded());
}
private void testSecretKeyRingWithPersonalCertificate()
throws Exception
{
checkSecretKeyRingWithPersonalCertificate(secWithPersonalCertificate);
JcaPGPSecretKeyRingCollection secRing = new JcaPGPSecretKeyRingCollection(secWithPersonalCertificate);
checkSecretKeyRingWithPersonalCertificate(secRing.getEncoded());
}
private void testUmlaut()
throws Exception
{
PGPPublicKeyRing pubRing = new PGPPublicKeyRing(umlautKeySig, new JcaKeyFingerprintCalculator());
PGPPublicKey pub = pubRing.getPublicKey();
String userID = (String)pub.getUserIDs().next();
for (Iterator it = pub.getSignatures(); it.hasNext();)
{
PGPSignature sig = (PGPSignature)it.next();
if (sig.getSignatureType() == PGPSignature.POSITIVE_CERTIFICATION)
{
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), pub);
if (!sig.verifyCertification(userID, pub))
{
fail("failed UTF8 userID test");
}
}
}
//
// this is quicker because we are using pregenerated parameters.
//
KeyPairGenerator rsaKpg = KeyPairGenerator.getInstance("RSA", "BC");
KeyPair rsaKp = rsaKpg.generateKeyPair();
PGPKeyPair rsaKeyPair1 = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, rsaKp, new Date());
rsaKp = rsaKpg.generateKeyPair();
PGPKeyPair rsaKeyPair2 = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, rsaKp, new Date());
char[] passPhrase = "passwd".toCharArray();
PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsaKeyPair1,
userID, sha1Calc, null, null, new JcaPGPContentSignerBuilder(PGPPublicKey.RSA_SIGN, HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).setProvider("BC").build(passPhrase));
PGPPublicKeyRing pubRing1 = keyRingGen.generatePublicKeyRing();
pub = pubRing1.getPublicKey();
for (Iterator it = pub.getSignatures(); it.hasNext();)
{
PGPSignature sig = (PGPSignature)it.next();
if (sig.getSignatureType() == PGPSignature.POSITIVE_CERTIFICATION)
{
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), pub);
if (!sig.verifyCertification(userID, pub))
{
fail("failed UTF8 userID creation test");
}
}
}
}
private void checkSecretKeyRingWithPersonalCertificate(byte[] keyRing)
throws Exception
{
JcaPGPSecretKeyRingCollection secCol = new JcaPGPSecretKeyRingCollection(keyRing);
int count = 0;
for (Iterator rIt = secCol.getKeyRings(); rIt.hasNext();)
{
PGPSecretKeyRing ring = (PGPSecretKeyRing)rIt.next();
for (Iterator it = ring.getExtraPublicKeys(); it.hasNext();)
{
it.next();
count++;
}
}
if (count != 1)
{
fail("personal certificate data subkey not found - count = " + count);
}
}
private void checkPublicKeyRingWithX509(byte[] keyRing)
throws Exception
{
PGPPublicKeyRing pubRing = new PGPPublicKeyRing(keyRing, new JcaKeyFingerprintCalculator());
Iterator it = pubRing.getPublicKeys();
if (it.hasNext())
{
PGPPublicKey key = (PGPPublicKey)it.next();
Iterator sIt = key.getSignatures();
if (sIt.hasNext())
{
PGPSignature sig = (PGPSignature)sIt.next();
if (sig.getKeyAlgorithm() != 100)
{
fail("experimental signature not found");
}
if (!areEqual(sig.getSignature(), Hex.decode("000101")))
{
fail("experimental encoding check failed");
}
}
else
{
fail("no signature found");
}
}
else
{
fail("no key found");
}
}
// test for key ring with non-UTF8 User ID.
private void testBadUserID()
throws Exception
{
PGPPublicKeyRing pgpRing = new JcaPGPPublicKeyRing(problemUserID);
byte[] enc = pgpRing.getEncoded();
if (!Arrays.areEqual(problemUserID, enc))
{
fail("encoded key does not match original");
}
PGPPublicKey pubKey = pgpRing.getPublicKey();
Iterator it = pubKey.getRawUserIDs();
byte[] rawID = (byte[])it.next();
it = pubKey.getSignaturesForID(rawID);
PGPSignature sig = (PGPSignature)it.next();
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), pubKey);
if (!sig.verifyCertification(rawID, pubKey))
{
fail("Certification not validated for rawID");
}
}
public void testNoExportPrivateKey()
throws Exception
{
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
JcaPGPKeyConverter converter = new JcaPGPKeyConverter();
PGPPublicKey pubKey = converter.getPGPPublicKey(PGPPublicKey.RSA_GENERAL, kp.getPublic(), new Date());
PGPPrivateKey privKey = new JcaPGPPrivateKey(pubKey, kp.getPrivate());
doTestNoExportPrivateKey(new PGPKeyPair(pubKey, privKey));
}
private void doTestNoExportPrivateKey(PGPKeyPair keyPair)
throws Exception
{
PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, keyPair,
"test", sha1Calc, null, null, new JcaPGPContentSignerBuilder(PGPPublicKey.RSA_SIGN, HashAlgorithmTags.SHA1), null);
PGPPublicKey pubKey = keyPair.getPublicKey();
PGPPublicKeyRing pubRing = keyRingGen.generatePublicKeyRing();
if (pubRing.getPublicKey(pubKey.getKeyID()) == null)
{
fail("no public key found");
}
for (Iterator it = pubRing.getPublicKey().getSignatures(); it.hasNext();)
{
PGPSignature sig = (PGPSignature)it.next();
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), pubKey);
if (!sig.verifyCertification("test", pubKey))
{
fail("certification failed");
}
}
pubRing.getEncoded();
PGPSecretKeyRing secRing = keyRingGen.generateSecretKeyRing();
secRing.getEncoded();
}
public void performTest()
throws Exception
{
try
{
test1();
test2();
test3();
test4();
test5();
test6();
revocationTest();
test8();
test9();
test10();
test11();
generateTest();
generateSha1Test();
rewrapTest();
rewrapTestV3();
rewrapTestMD5();
testPublicKeyRingWithX509();
testSecretKeyRingWithPersonalCertificate();
insertMasterTest();
testUmlaut();
testBadUserID();
testNoExportPrivateKey();
}
catch (PGPException e)
{
if (((PGPException)e).getUnderlyingException() != null)
{
Exception ex = ((PGPException)e).getUnderlyingException();
fail("exception: " + ex, ex);
}
else
{
fail("exception: " + e, e);
}
}
}
public String getName()
{
return "PGPKeyRingTest";
}
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new PGPKeyRingTest());
}
}
|
package org.infinispan.server.test.cs.custom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.File;
import javax.management.ObjectName;
import org.infinispan.arquillian.core.InfinispanResource;
import org.infinispan.arquillian.core.RemoteInfinispanServer;
import org.infinispan.arquillian.core.RunningServer;
import org.infinispan.arquillian.core.WithRunningServer;
import org.infinispan.arquillian.utils.MBeanServerConnectionProvider;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.persistence.cluster.MyCustomCacheStore;
import org.infinispan.persistence.spi.ExternalStore;
import org.infinispan.server.infinispan.spi.InfinispanSubsystem;
import org.infinispan.server.test.category.CacheStore;
import org.infinispan.server.test.util.ITestUtils;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
/**
* Tests Deployeable Cache Stores which are placed into server deployments directory.
*
* @author <a href="mailto:jmarkos@redhat.com">Jakub Markos</a>
* @author Sebastian Laskawiec
*/
@RunWith(Arquillian.class)
@Category(CacheStore.class)
public class CustomCacheStoreIT {
private static final Log log = LogFactory.getLog(CustomCacheStoreIT.class);
@InfinispanResource("standalone-customcs")
RemoteInfinispanServer server;
final int managementPort = 9990;
final String cacheLoaderMBean = "jboss." + InfinispanSubsystem.SUBSYSTEM_NAME + ":type=Cache,name=\"default(local)\",manager=\"local\",component=CacheLoader";
@BeforeClass
public static void before() throws Exception {
String serverDir = System.getProperty("server1.dist");
JavaArchive deployedCacheStore = ShrinkWrap.create(JavaArchive.class);
deployedCacheStore.addPackage(MyCustomCacheStore.class.getPackage());
deployedCacheStore.addAsServiceProvider(ExternalStore.class, MyCustomCacheStore.class);
deployedCacheStore.as(ZipExporter.class).exportTo(
new File(serverDir, "/standalone/deployments/custom-store.jar"), true);
}
@Test
@WithRunningServer({@RunningServer(name = "standalone-customcs")})
public void testIfDeployedCacheContainsProperValues() throws Exception {
RemoteCacheManager rcm = ITestUtils.createCacheManager(server);
RemoteCache<String, String> rc = rcm.getCache();
assertNull(rc.get("key1"));
rc.put("key1", "value1");
assertEquals("value1", rc.get("key1"));
// check via jmx that MyCustomCacheStore is indeed used
MBeanServerConnectionProvider provider = new MBeanServerConnectionProvider(server.getHotrodEndpoint().getInetAddress().getHostName(), managementPort);
assertEquals("[org.infinispan.persistence.cluster.MyCustomCacheStore]", getAttribute(provider, cacheLoaderMBean, "stores"));
}
private String getAttribute(MBeanServerConnectionProvider provider, String mbean, String attr) throws Exception {
return provider.getConnection().getAttribute(new ObjectName(mbean), attr).toString();
}
}
|
package com.vadim.lakes.domain.models;
import com.google.gson.annotations.SerializedName;
public class Lake {
@SerializedName("id")
private Integer mId;
@SerializedName("title")
private String mTitle;
@SerializedName("description")
private String mDescription;
@SerializedName("img")
private String mImg;
@SerializedName("lat")
private Double mLat;
@SerializedName("lon")
private Double mLon;
public Lake(Integer id, String title, String description, String img, Double lat, Double lon) {
this.mId = id;
this.mTitle = title;
this.mDescription = description;
this.mImg = img;
this.mLat = lat;
this.mLon = lon;
}
public Lake() {
}
public Integer getId() {
return mId;
}
public void setId(Integer id) {
this.mId = id;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
this.mTitle = title;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String description) {
this.mDescription = description;
}
public String getImg() {
return mImg;
}
public void setImg(String img) {
this.mImg = img;
}
public Double getLat() {
return mLat;
}
public void setLat(Double lat) {
this.mLat = lat;
}
public Double getLon() {
return mLon;
}
public void setLon(Double lon) {
this.mLon = lon;
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.dcdn.model.v20180115;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.dcdn.transform.v20180115.DescribeDcdnDomainIpaBpsDataResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class DescribeDcdnDomainIpaBpsDataResponse extends AcsResponse {
private String requestId;
private String domainName;
private String startTime;
private String endTime;
private String dataInterval;
private List<DataModule> bpsDataPerInterval;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getDomainName() {
return this.domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public String getStartTime() {
return this.startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return this.endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getDataInterval() {
return this.dataInterval;
}
public void setDataInterval(String dataInterval) {
this.dataInterval = dataInterval;
}
public List<DataModule> getBpsDataPerInterval() {
return this.bpsDataPerInterval;
}
public void setBpsDataPerInterval(List<DataModule> bpsDataPerInterval) {
this.bpsDataPerInterval = bpsDataPerInterval;
}
public static class DataModule {
private String timeStamp;
private Float ipaBps;
public String getTimeStamp() {
return this.timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public Float getIpaBps() {
return this.ipaBps;
}
public void setIpaBps(Float ipaBps) {
this.ipaBps = ipaBps;
}
}
@Override
public DescribeDcdnDomainIpaBpsDataResponse getInstance(UnmarshallerContext context) {
return DescribeDcdnDomainIpaBpsDataResponseUnmarshaller.unmarshall(this, context);
}
}
|
/**
* OSHI (https://github.com/oshi/oshi)
*
* Copyright (c) 2010 - 2019 The OSHI Project Team:
* https://github.com/oshi/oshi/graphs/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 oshi.hardware.platform.unix.freebsd;
import oshi.hardware.VirtualMemory;
import oshi.hardware.common.AbstractGlobalMemory;
import oshi.util.platform.unix.freebsd.BsdSysctlUtil;
/**
* Memory obtained by sysctl vm.stats
*/
public class FreeBsdGlobalMemory extends AbstractGlobalMemory {
private static final long serialVersionUID = 1L;
/** {@inheritDoc} */
@Override
public long getAvailable() {
long inactive = BsdSysctlUtil.sysctl("vm.stats.vm.v_inactive_count", 0L);
long cache = BsdSysctlUtil.sysctl("vm.stats.vm.v_cache_count", 0L);
long free = BsdSysctlUtil.sysctl("vm.stats.vm.v_free_count", 0L);
this.memAvailable = (inactive + cache + free) * getPageSize();
return this.memAvailable;
}
/** {@inheritDoc} */
@Override
public long getTotal() {
if (this.memTotal < 0) {
this.memTotal = BsdSysctlUtil.sysctl("hw.physmem", 0L);
}
return this.memTotal;
}
/** {@inheritDoc} */
@Override
public long getPageSize() {
if (this.pageSize < 0) {
this.pageSize = BsdSysctlUtil.sysctl("hw.pagesize", 4096L);
}
return this.pageSize;
}
/** {@inheritDoc} */
@Override
public VirtualMemory getVirtualMemory() {
if (this.virtualMemory == null) {
this.virtualMemory = new FreeBsdVirtualMemory();
}
return this.virtualMemory;
}
}
|
/**
* 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.hadoop.hbase.client;
import java.io.IOException;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotEnabledException;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.ipc.HBaseRpcController;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hbase.thirdparty.com.google.protobuf.RpcController;
import org.apache.hadoop.hbase.util.Bytes;
/**
* Implementations make a RPC call against a RegionService via a protobuf Service.
* Implement rpcCall() and the parent class setClientByServiceName; this latter is where the
* RPC stub gets set (the appropriate protobuf 'Service'/Client). Be sure to make use of the
* RpcController that this instance is carrying via #getRpcController().
*
* <p>TODO: this class is actually tied to one region, because most of the paths make use of
* the regioninfo part of location when building requests. The only reason it works for
* multi-region requests (e.g. batch) is that they happen to not use the region parts.
* This could be done cleaner (e.g. having a generic parameter and 2 derived classes,
* RegionCallable and actual RegionServerCallable with ServerName.
*
* @param <T> The class that the ServerCallable handles.
* @param <S> The protocol to use (Admin or Client or even an Endpoint over in MetaTableAccessor).
*/
// TODO: MasterCallable and this Class have a lot in common. UNIFY!
// Public but should be package private only it is used by MetaTableAccessor. FIX!!
@InterfaceAudience.Private
public abstract class RegionServerCallable<T, S> implements RetryingCallable<T> {
private final Connection connection;
private final TableName tableName;
private final byte[] row;
/**
* Some subclasses want to set their own location. Make it protected.
*/
protected HRegionLocation location;
protected S stub;
/**
* This is 99% of the time a HBaseRpcController but also used doing Coprocessor Endpoints and in
* this case, it is a ServerRpcControllable which is not a HBaseRpcController.
* Can be null!
*/
protected final RpcController rpcController;
private int priority = HConstants.NORMAL_QOS;
/**
* @param connection Connection to use.
* @param rpcController Controller to use; can be shaded or non-shaded.
* @param tableName Table name to which <code>row</code> belongs.
* @param row The row we want in <code>tableName</code>.
*/
public RegionServerCallable(Connection connection, TableName tableName, byte [] row,
RpcController rpcController) {
this(connection, tableName, row, rpcController, HConstants.NORMAL_QOS);
}
public RegionServerCallable(Connection connection, TableName tableName, byte [] row,
RpcController rpcController, int priority) {
super();
this.connection = connection;
this.tableName = tableName;
this.row = row;
this.rpcController = rpcController;
this.priority = priority;
}
protected RpcController getRpcController() {
return this.rpcController;
}
protected void setStub(S stub) {
this.stub = stub;
}
protected S getStub() {
return this.stub;
}
/**
* Override that changes call Exception from {@link Exception} to {@link IOException}.
* Also does set up of the rpcController.
*/
@Override
public T call(int callTimeout) throws IOException {
try {
// Iff non-null and an instance of a SHADED rpcController, do config! Unshaded -- i.e.
// com.google.protobuf.RpcController or null -- will just skip over this config.
if (getRpcController() != null) {
RpcController shadedRpcController = (RpcController)getRpcController();
// Do a reset to clear previous states, such as CellScanner.
shadedRpcController.reset();
if (shadedRpcController instanceof HBaseRpcController) {
HBaseRpcController hrc = (HBaseRpcController)getRpcController();
// If it is an instance of HBaseRpcController, we can set priority on the controller based
// off the tableName. Set call timeout too.
hrc.setPriority(tableName);
hrc.setPriority(priority);
hrc.setCallTimeout(callTimeout);
}
}
return rpcCall();
} catch (Exception e) {
throw ProtobufUtil.handleRemoteException(e);
}
}
/**
* Run the RPC call. Implement this method. To get at the rpcController that has been created
* and configured to make this rpc call, use getRpcController(). We are trying to contain
* rpcController references so we don't pollute codebase with protobuf references; keep the
* protobuf references contained and only present in a few classes rather than all about the
* code base.
* @throws Exception
*/
protected abstract T rpcCall() throws Exception;
/**
* Get the RpcController CellScanner.
* If the RpcController is a HBaseRpcController, which it is in all cases except
* when we are processing Coprocessor Endpoint, then this method returns a reference to the
* CellScanner that the HBaseRpcController is carrying. Do it up here in this Callable
* so we don't have to scatter ugly instanceof tests around the codebase. Will return null
* if called in a Coproccessor Endpoint context. Should never happen.
*/
protected CellScanner getRpcControllerCellScanner() {
return (getRpcController() != null && getRpcController() instanceof HBaseRpcController)?
((HBaseRpcController)getRpcController()).cellScanner(): null;
}
protected void setRpcControllerCellScanner(CellScanner cellScanner) {
if (getRpcController() != null && getRpcController() instanceof HBaseRpcController) {
((HBaseRpcController)this.rpcController).setCellScanner(cellScanner);
}
}
/**
* @return {@link ClusterConnection} instance used by this Callable.
*/
protected ClusterConnection getConnection() {
return (ClusterConnection) this.connection;
}
protected HRegionLocation getLocation() {
return this.location;
}
protected void setLocation(final HRegionLocation location) {
this.location = location;
}
public TableName getTableName() {
return this.tableName;
}
public byte [] getRow() {
return this.row;
}
protected int getPriority() { return this.priority;}
@Override
public void throwable(Throwable t, boolean retrying) {
if (location != null) {
getConnection().updateCachedLocations(tableName, location.getRegionInfo().getRegionName(),
row, t, location.getServerName());
}
}
@Override
public String getExceptionMessageAdditionalDetail() {
return "row '" + Bytes.toString(row) + "' on table '" + tableName + "' at " + location;
}
@Override
public long sleep(long pause, int tries) {
return ConnectionUtils.getPauseTime(pause, tries);
}
/**
* @return the HRegionInfo for the current region
*/
public HRegionInfo getHRegionInfo() {
if (this.location == null) {
return null;
}
return this.location.getRegionInfo();
}
@Override
public void prepare(final boolean reload) throws IOException {
// check table state if this is a retry
if (reload && tableName != null && !tableName.equals(TableName.META_TABLE_NAME)
&& getConnection().isTableDisabled(tableName)) {
throw new TableNotEnabledException(tableName.getNameAsString() + " is disabled.");
}
try (RegionLocator regionLocator = connection.getRegionLocator(tableName)) {
this.location = regionLocator.getRegionLocation(row);
}
if (this.location == null) {
throw new IOException("Failed to find location, tableName=" + tableName +
", row=" + Bytes.toString(row) + ", reload=" + reload);
}
setStubByServiceName(this.location.getServerName());
}
/**
* Set the RCP client stub
* @param serviceName to get the rpc stub for
* @throws IOException When client could not be created
*/
protected abstract void setStubByServiceName(ServerName serviceName) throws IOException;
}
|
package net.minidev.ovh.api.license;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* All quantities of domain available for a license
*/
public enum OvhDomainNumberEnum {
@JsonProperty("0")
_0("0"),
@JsonProperty("1")
_1("1"),
@JsonProperty("10")
_10("10"),
@JsonProperty("100")
_100("100"),
@JsonProperty("30")
_30("30"),
@JsonProperty("300")
_300("300"),
unlimited("unlimited");
final String value;
OvhDomainNumberEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
|
package com.spelchec.surveyor.model;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import com.spelchec.surveyor.MD5;
public class Question {
public String question;
public String type;
public Integer selectionLimit;
public List options;
public Boolean allowOther;
public String getHashCode() {
try {
return MD5.toHash(question);
} catch (NoSuchAlgorithmException e) {
return "error";
}
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getSelectionLimit() {
return selectionLimit;
}
public void setSelectionLimit(Integer selectionLimit) {
this.selectionLimit = selectionLimit;
}
public List getOptions() {
return options;
}
public void setOptions(List options) {
this.options = options;
}
public Boolean getAllowOther() {
return allowOther;
}
public void setAllowOther(Boolean allowOther) {
this.allowOther = allowOther;
}
}
|
package com.github.mozvip.subtitles.model;
import java.nio.file.Path;
import org.apache.commons.lang3.StringUtils;
import com.github.mozvip.subtitles.utils.RegExp;
public class VideoNameParser {
private final static String NAME_REGEXP = ".+";
public final static String SEPARATOR_REGEXP = "[\\s\\.]+";
private static String[] filters = new String[] {
"(.*)" + SEPARATOR_REGEXP + "READNFO" + SEPARATOR_REGEXP + "(.*)",
"(.*)" + SEPARATOR_REGEXP + "FANSUB" + SEPARATOR_REGEXP + "(.*)",
"(.*)" + SEPARATOR_REGEXP + "UNRATED" + SEPARATOR_REGEXP + "(.*)",
"(.*)" + SEPARATOR_REGEXP + "FASTSUB" + SEPARATOR_REGEXP + "(.*)",
"(.*)" + SEPARATOR_REGEXP + "REPACK" + SEPARATOR_REGEXP + "(.*)",
"(.*)" + SEPARATOR_REGEXP + "Theatrical\\s+Cut" + SEPARATOR_REGEXP + "(.*)"
};
public static String clean( String title, String[] filtersRegExps ) {
title = title.replace('_', ' ');
title = title.replaceAll("\\s+", " ");
boolean mustContinue = true;
while (mustContinue) {
mustContinue = false;
for (String filter : filtersRegExps) {
String[] groups = RegExp.parseGroups( title, filter );
if (groups != null) {
title = StringUtils.join( groups, " ");
mustContinue = true;
}
}
}
return title;
}
public static VideoInfo getVideoInfo( Path path ) {
String title = getTitle(path);
return getVideoInfo(title);
}
public static VideoInfo getVideoInfo( String title ) {
VideoInfo info = getEpisodeInfo(null, title);
if (info == null) {
info = getMovieInfo(title);
}
return info;
}
private static String getName(String string) {
String name = string;
name = name.replace('.', ' ');
name = name.replace('_', ' ');
return name.trim();
}
public static TVShowEpisodeInfo getEpisodeInfo( String tvshow, String fileName ) {
// "(fileName)\.s()e()\.(quality)\.(source)\.(codec)-(release)\.(ext)";
VideoQuality quality = null;
if (fileName.contains("1080")) {
fileName = fileName.replace("1080p", "");
fileName = fileName.replace("1080", "");
quality = VideoQuality._1080p;
}
if (fileName.contains("2160")) {
fileName = fileName.replace("2160p", "");
fileName = fileName.replace("2160", "");
quality = VideoQuality._2160p;
}
if (fileName.contains("x264")) {
fileName = fileName.replace("x264", "");
}
// remove year from fileName
fileName = fileName.replaceAll("19\\d{2}|20\\d{2}", "");
String [] patterns = new String[]{
"(.*)s(\\d{2})\\.?e(\\d{2})\\.?e(\\d{2})(.*)",
"(.*)s(\\d{2})\\.?e(\\d{2})(.*)",
"(.*)(\\d{1,2})\\s+-\\s+(\\d{1,2})\\s+(.*)",
"(.*)(\\d+)x(\\d+)(.*)",
"(.*)(\\d{1})(\\d{2})(\\D{1}.*)",
"(.*)(\\d{2})e?(\\d{2})(.*)",
"(.*)\\.Part\\.(\\d+)\\.(.*)"
};
VideoSource source = VideoSource.findMatch(fileName);
for (String pattern:patterns) {
String[] groups = RegExp.parseGroups(fileName, pattern);
if (groups != null) {
String name = getName( groups[0] );
name = StringUtils.isEmpty(name) ? tvshow : name;
if (groups.length == 3) {
int firstEpisode = Integer.parseInt(groups[1]);
int lastEpisode = firstEpisode;
String extraNameData = groups[groups.length - 1];
return new TVShowEpisodeInfo(tvshow != null ? tvshow : name, 1, firstEpisode, lastEpisode, quality, source, extraNameData);
} else {
int extractedSeason = Integer.parseInt(groups[1]);
int firstEpisode = Integer.parseInt(groups[2]);
int lastEpisode = groups.length > 4 ? Integer.parseInt(groups[3]) : firstEpisode;
String extraNameData = groups[groups.length - 1];
return new TVShowEpisodeInfo(tvshow != null ? tvshow : name, extractedSeason, firstEpisode, lastEpisode, quality, source, extraNameData);
}
}
}
return null;
}
public static MovieInfo getMovieInfo( String title ) {
String[] groups = RegExp.parseGroups(title, "(.+)\\.(19\\d{2}|20\\d{2})\\.(?:\\D+\\.)?([^.]+p)\\.([^.]+)\\.(.+)-([^.]+)\\.([^.]+)");
if (groups != null) {
String name = groups[0];
int year = Integer.parseInt(groups[1]);
VideoQuality quality = VideoQuality.findMatch(groups[2]);
VideoSource source = VideoSource.findMatch(groups[3]);
String release = groups[5];
if (quality != null && source != null) {
return new MovieInfo(name, year, quality, source, release);
} else {
// TODO
}
}
VideoQuality quality = null;
if (title.contains("1080")) {
title = title.replace("1080p", "");
title = title.replace("1080", "");
quality = VideoQuality._1080p;
}
if (title.contains("2160")) {
title = title.replace("2160p", "");
title = title.replace("2160", "");
quality = VideoQuality._2160p;
}
VideoSource source = VideoSource.findMatch(title);
groups = RegExp.parseGroups(title, "(" + NAME_REGEXP + ")" + SEPARATOR_REGEXP + "\\(?(19\\d{2}|20\\d{2})\\)?(.*)");
if (groups != null) {
String name = getName( groups[0] );
return new MovieInfo( name, Integer.parseInt( groups[1]), quality, source, groups[2] );
}
return new MovieInfo( title, -1, null, source, null );
}
private static String getTitle(Path file) {
String filename = file.getFileName().toString();
String fileNameWithoutExtension = filename;
fileNameWithoutExtension = fileNameWithoutExtension.substring(0, fileNameWithoutExtension.lastIndexOf('.'));
return clean( fileNameWithoutExtension, filters );
}
}
|
/*
* Copyright 2014-2020 [fisco-dev]
*
* 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.fisco.bcos.sdk.amop.topic;
import static org.fisco.bcos.sdk.amop.topic.TopicManager.topicNeedVerifyPrefix;
import static org.fisco.bcos.sdk.amop.topic.TopicManager.verifyChannelPrefix;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.fisco.bcos.sdk.amop.Amop;
import org.fisco.bcos.sdk.amop.AmopCallback;
import org.fisco.bcos.sdk.channel.Channel;
import org.fisco.bcos.sdk.channel.ResponseCallback;
import org.fisco.bcos.sdk.channel.model.Options;
import org.fisco.bcos.sdk.crypto.CryptoSuite;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.model.AmopMsg;
import org.fisco.bcos.sdk.model.CryptoType;
import org.fisco.bcos.sdk.model.Message;
import org.fisco.bcos.sdk.model.MsgType;
import org.fisco.bcos.sdk.model.Response;
import org.fisco.bcos.sdk.network.MsgHandler;
import org.fisco.bcos.sdk.utils.Hex;
import org.fisco.bcos.sdk.utils.ObjectMapperFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AmopMsgHandler implements MsgHandler {
private static Logger logger = LoggerFactory.getLogger(AmopMsgHandler.class);
private TopicManager topicManager;
private Channel channel;
private long defaultTimeout = 5000;
private Map<String, ResponseCallback> seq2Callback = new ConcurrentHashMap<>();
private boolean isRunning = false;
private CryptoSuite cryptoSuite = new CryptoSuite(CryptoType.ECDSA_TYPE);
public AmopMsgHandler(Channel channel, TopicManager topicManager) {
this.topicManager = topicManager;
this.channel = channel;
}
public void setIsRunning(boolean isRunning) {
this.isRunning = isRunning;
}
@Override
public void onConnect(ChannelHandlerContext ctx) {
if (!isRunning) {
logger.warn("Amop on connect, amop is not running, exit.");
return;
}
String host = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress();
Integer port = ((SocketChannel) ctx.channel()).remoteAddress().getPort();
String ipAndPort = host + ":" + port;
logger.info("Node connected, update topics to node. node:" + ipAndPort);
try {
Set<String> topics = topicManager.getSubByPeer(ipAndPort);
byte[] topicBytes =
ObjectMapperFactory.getObjectMapper().writeValueAsBytes(topics.toArray());
Message msg = new Message();
msg.setType((short) MsgType.AMOP_CLIENT_TOPICS.getType());
msg.setResult(0);
msg.setSeq(newSeq());
msg.setData(topicBytes);
ctx.writeAndFlush(msg);
} catch (JsonProcessingException e) {
logger.warn("Amop on connect, subscribe error: {}", e.getMessage());
}
}
@Override
public void onMessage(ChannelHandlerContext ctx, Message msg) {
logger.trace("receive msg, msg type:{}, seq:{}", msg.getType(), msg.getSeq());
if (!isRunning) {
logger.warn("Amop on msg, amop is not running, exit.");
}
if (msg.getType() == (short) MsgType.AMOP_RESPONSE.getType()) {
// Receive a signed Amop message for authorization.
onAmopResponse(ctx, msg);
return;
}
if (msg.getType() == (short) MsgType.REQUEST_TOPICCERT.getType()) {
// As amop private topic message sender
onVerifyRequest(ctx, msg);
} else if (msg.getType() == (short) MsgType.AMOP_REQUEST.getType()
|| msg.getType() == (short) MsgType.AMOP_MULBROADCAST.getType()) {
AmopMsg amopMsg = new AmopMsg(msg);
try {
amopMsg.decodeAmopBody(msg.getData());
} catch (Exception e) {
logger.error(
"Receive an invalid message, msg type:{}, seq:{}",
msg.getType(),
msg.getSeq());
return;
}
if (isVerifyingPrivateTopic(amopMsg)) {
// Receive a private topic authorization message.
onPrivateTopicRandomValue(ctx, amopMsg);
} else {
// Receive an Amop message.
onAmopMsg(ctx, amopMsg);
}
} else {
logger.error(
"amop module receive a not supported type message, type:{}", msg.getType());
}
}
@Override
public void onDisconnect(ChannelHandlerContext ctx) {}
public void onVerifyRequest(ChannelHandlerContext ctx, Message msg) {
logger.trace(
"private topic verify step 1: node request random number. seq:{} type:{}, content:{}",
msg.getSeq(),
msg.getType(),
new String(msg.getData()));
// Response to node at the first time.
responseVerifyRequest(ctx, msg);
// Start a verify procedure
// Read message data to RequestVerifyData
String content = new String(msg.getData());
RequestVerifyData data;
try {
data =
ObjectMapperFactory.getObjectMapper()
.readValue(content, RequestVerifyData.class);
} catch (JsonProcessingException e) {
logger.error(
"receive request start private topic verify message, message is invalid, seq:{} msgtype:{}",
msg.getSeq(),
msg.getType());
return;
}
String topic = data.getTopic();
String nodeId = data.getNodeId();
logger.trace(
"private topic verify step 1: node request random number. seq:{} topic:{} nodeId:{}",
msg.getSeq(),
topic,
nodeId);
// Reply random value to node
String rmdString = UUID.randomUUID().toString().replaceAll("-", "");
AmopMsg respMsg = new AmopMsg();
respMsg.setType((short) MsgType.AMOP_REQUEST.getType());
respMsg.setSeq(Amop.newSeq());
respMsg.setResult(0);
respMsg.setData(rmdString.getBytes());
respMsg.setTopic(data.getTopicForCert());
// send message out
Options opt = new Options();
opt.setTimeout(defaultTimeout);
ResponseCallback callback =
new ResponseCallback() {
@Override
public void onResponse(Response response) {
if (0 != response.getErrorCode()) {
logger.error(
"get random value signature of amop private topic failed :{}:{}",
response.getErrorCode(),
response.getErrorMessage());
return;
}
AmopMsg amopMsg = new AmopMsg();
amopMsg.decodeAmopBody(response.getContentBytes());
int valid = checkSignature(topic, rmdString.getBytes(), amopMsg.getData());
try {
sendUpdateTopicStatus(valid, topic, nodeId, ctx);
} catch (JsonProcessingException e) {
logger.error("update topic status error: {}", e.getMessage());
}
}
};
logger.trace(
"private topic verify step 2: send out random number. seq:{} topic:{} data:{}",
respMsg.getSeq(),
respMsg.getTopic(),
new String(respMsg.getData()));
channel.asyncSendToRandom(respMsg.getMessage(), callback, opt);
}
public void responseVerifyRequest(ChannelHandlerContext ctx, Message msg) {
Message response = new Message();
response.setSeq(msg.getSeq());
response.setResult(0);
response.setType((short) MsgType.REQUEST_TOPICCERT.getType());
response.setData("".getBytes());
ctx.writeAndFlush(response);
}
public int checkSignature(String topic, byte[] randomValue, byte[] signature) {
List<String> pubKeys = topicManager.getPublicKeysByTopic(topic);
Iterator<String> pks = pubKeys.iterator();
while (pks.hasNext()) {
String publicKey = pks.next();
if (cryptoSuite.verify(
publicKey,
Hex.toHexString(cryptoSuite.hash(randomValue)),
Hex.toHexString(signature))) {
return 0;
} else {
logger.warn(
"verify topic {} failed, randomValue: {}, publicKey: {}",
topic,
Hex.toHexString(randomValue),
publicKey);
}
}
return 1;
}
private boolean isVerifyingPrivateTopic(AmopMsg amopMsg) {
return amopMsg.getTopic().length() > verifyChannelPrefix.length()
&& verifyChannelPrefix.equals(
amopMsg.getTopic().substring(0, verifyChannelPrefix.length()));
}
public static boolean isPrivateTopic(String topic) {
return topic.length() > topicNeedVerifyPrefix.length()
&& topicNeedVerifyPrefix.equals(topic.substring(0, topicNeedVerifyPrefix.length()));
}
public static String removePrivateTopicPrefix(String topic) {
if (isPrivateTopic(topic)) {
return topic.substring(topicNeedVerifyPrefix.length());
} else {
return topic;
}
}
private String getSimpleTopic(String fullTopic) {
return fullTopic.substring(verifyChannelPrefix.length(), fullTopic.length() - 33);
}
public void onPrivateTopicRandomValue(ChannelHandlerContext ctx, AmopMsg msg) {
logger.trace(
"private topic verify step 2: receive random value, seq:{} type:{} topic:{} data:{}",
msg.getSeq(),
msg.getType(),
msg.getTopic(),
new String(msg.getData()));
byte[] randValue = msg.getData();
String topic = msg.getTopic();
CryptoKeyPair cryptoKeyPair = topicManager.getPrivateKeyByTopic(getSimpleTopic(topic));
String signature = "";
if (null == cryptoKeyPair) {
logger.error("topic:{} not subscribed, reject message", getSimpleTopic(topic));
return;
} else {
try {
signature =
cryptoSuite
.getSignatureImpl()
.signWithStringSignature(
Hex.toHexString(cryptoSuite.hash(randValue)),
cryptoKeyPair);
} catch (Exception e) {
logger.error(
"please check the public key of topic {} is correct configured, error {}",
topic,
e.getMessage());
}
}
sendSignedRandomNumber(signature, topic, msg.getSeq(), ctx);
}
public void onAmopMsg(ChannelHandlerContext ctx, AmopMsg amopMsg) {
logger.debug(
"receive a Amop message. seq:{} msgtype:{}", amopMsg.getSeq(), amopMsg.getType());
if (!topicManager.isSubTopic(amopMsg.getTopic())) {
logger.warn(
"receive an amop msg which is not subscribed, topic:{}", amopMsg.getTopic());
return;
}
AmopCallback callback = topicManager.getCallback(amopMsg.getTopic());
if (callback == null) {
logger.error(
"can not process Amop message, callback for topic {} is not found",
amopMsg.getTopic());
return;
}
AmopMsgIn msgIn = new AmopMsgIn();
msgIn.setTopic(amopMsg.getTopic());
if (isPrivateTopic(amopMsg.getTopic())) {
msgIn.setTopic(removePrivateTopicPrefix(amopMsg.getTopic()));
msgIn.setTopicType(TopicType.PRIVATE_TOPIC);
}
msgIn.setMessageID(amopMsg.getSeq());
msgIn.setContent(amopMsg.getData());
msgIn.setResult(amopMsg.getResult());
msgIn.setCtx(ctx);
msgIn.setType(amopMsg.getType());
byte[] content = callback.receiveAmopMsg(msgIn);
// Response the amop msg
if (amopMsg.getType() == (short) MsgType.AMOP_MULBROADCAST.getType()) {
// If received a broadcast msg, do not response.
return;
}
amopMsg.setResult(0);
amopMsg.setType((short) MsgType.AMOP_RESPONSE.getType());
amopMsg.setData(content);
logger.trace(
"Send response, seq:{} topic:{} content:{}",
amopMsg.getSeq(),
amopMsg.getTopic(),
new String(content));
ctx.writeAndFlush(amopMsg.getMessage());
}
public void onAmopResponse(ChannelHandlerContext ctx, Message msg) {
logger.debug("receive amop response. seq:{} msgtype:{} ", msg.getSeq(), msg.getType());
ResponseCallback callback = seq2Callback.get(msg.getSeq());
if (null != callback) {
Response resp = new Response();
resp.setMessageID(msg.getSeq());
resp.setErrorCode(msg.getResult());
if (msg.getResult() != 0) {
resp.setErrorMessage("response errors");
}
// 103: the AMOP_requests or the AMOP_multicast_requests have been rejected due to
// over bandwidth limit
if (msg.getResult()
== AmopRespError.REJECT_AMOP_REQ_FOR_OVER_BANDWIDTHLIMIT.getError()) {
logger.error(
"AMOP request was rejected due to over bandwidth limit, message: {}",
msg.getSeq());
resp.setErrorMessage("AMOP request was rejected due to over bandwidth limit");
}
if (msg.getResult() == AmopRespError.NO_AVAILABLE_SESSION.getError()) {
logger.error(
"AMOP request was rejected due to over bandwidth limit, message: {}",
msg.getSeq());
resp.setErrorMessage("AMOP request was rejected due to over bandwidth limit");
}
if (msg.getData() != null) {
AmopMsg amopMsg = new AmopMsg();
amopMsg.decodeAmopBody(msg.getData());
resp.setContent(new String(amopMsg.getData()));
}
callback.onResponse(resp);
} else {
logger.error("can not found response callback, timeout:{}", msg.getData());
return;
}
}
private void sendSignedRandomNumber(
String signature, String topic, String seq, ChannelHandlerContext ctx) {
AmopMsg msg = new AmopMsg();
msg.setTopic(topic);
msg.setResult(0);
msg.setSeq(seq);
msg.setType((short) MsgType.AMOP_RESPONSE.getType());
msg.setData(Hex.decode(signature));
logger.trace(
"private topic verify step 3: sign on random value and send out, seq:{} type:{} topic:{} data:{}",
msg.getSeq(),
msg.getType(),
msg.getTopic(),
new String(msg.getData()));
ctx.writeAndFlush(msg.getMessage());
}
public void sendUpdateTopicStatus(
int valid, String topic, String nodeId, ChannelHandlerContext ctx)
throws JsonProcessingException {
UpdateTopicStatus updateTopicStatus = new UpdateTopicStatus();
updateTopicStatus.setCheckResult(valid);
updateTopicStatus.setNodeId(nodeId);
updateTopicStatus.setTopic(topic);
String jsonStr =
ObjectMapperFactory.getObjectMapper().writeValueAsString(updateTopicStatus);
Message msg = new Message();
msg.setData(jsonStr.getBytes());
msg.setSeq(newSeq());
msg.setResult(0);
msg.setType((short) MsgType.UPDATE_TOPIICSTATUS.getType());
logger.info(
"private topic verify step4: finish signature verify, send out msg to update topic status, seq:{} topic:{} valid:{}",
msg.getSeq(),
topic,
valid);
ctx.writeAndFlush(msg);
}
public void addCallback(String seq, ResponseCallback callback) {
seq2Callback.put(seq, callback);
}
private String newSeq() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
|
package org.everit.json.schema.loader;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
class ClassPathAwareSchemaClient implements SchemaClient {
private static final List<String> HANDLED_PREFIXES = unmodifiableList(asList("classpath://", "classpath:/", "classpath:"));
private final SchemaClient fallbackClient;
ClassPathAwareSchemaClient(SchemaClient fallbackClient) {
this.fallbackClient = requireNonNull(fallbackClient, "fallbackClient cannot be null");
}
@Override public InputStream get(String url) {
Optional<String> maybeString = handleProtocol(url);
if(maybeString.isPresent()) {
InputStream stream = this.loadFromClasspath(maybeString.get());
if(stream != null) {
return stream;
} else {
throw new UncheckedIOException(new IOException(String.format("Could not find %s", url)));
}
} else {
return fallbackClient.get(url);
}
}
private InputStream loadFromClasspath(String str) {
return getClass().getResourceAsStream(str);
}
private Optional<String> handleProtocol(String url) {
return HANDLED_PREFIXES.stream().filter(url::startsWith)
.map(prefix -> "/" + url.substring(prefix.length()))
.findFirst();
}
}
|
package jp.co.flect.xmlschema;
import org.w3c.dom.Element;
public class InvalidSchemaException extends XMLSchemaException {
private static final long serialVersionUID = -1910806122487904847L;
private Element element;
public InvalidSchemaException(String msg, Element el) {
super(msg);
this.element = el;
}
public Element getElement() { return this.element;}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/schema/trainingjob/definition/automl_image_segmentation.proto
package com.google.cloud.aiplatform.v1.schema.trainingjob.definition;
public interface AutoMlImageSegmentationInputsOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlImageSegmentationInputs)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlImageSegmentationInputs.ModelType model_type = 1;</code>
* @return The enum numeric value on the wire for modelType.
*/
int getModelTypeValue();
/**
* <code>.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlImageSegmentationInputs.ModelType model_type = 1;</code>
* @return The modelType.
*/
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlImageSegmentationInputs.ModelType getModelType();
/**
* <pre>
* The training budget of creating this model, expressed in milli node
* hours i.e. 1,000 value in this field means 1 node hour. The actual
* metadata.costMilliNodeHours will be equal or less than this value.
* If further model training ceases to provide any improvements, it will
* stop without using the full budget and the metadata.successfulStopReason
* will be `model-converged`.
* Note, node_hour = actual_hour * number_of_nodes_involved. Or
* actaul_wall_clock_hours = train_budget_milli_node_hours /
* (number_of_nodes_involved * 1000)
* For modelType `cloud-high-accuracy-1`(default), the budget must be between
* 20,000 and 2,000,000 milli node hours, inclusive. The default value is
* 192,000 which represents one day in wall time
* (1000 milli * 24 hours * 8 nodes).
* </pre>
*
* <code>int64 budget_milli_node_hours = 2;</code>
* @return The budgetMilliNodeHours.
*/
long getBudgetMilliNodeHours();
/**
* <pre>
* The ID of the `base` model. If it is specified, the new model will be
* trained based on the `base` model. Otherwise, the new model will be
* trained from scratch. The `base` model must be in the same
* Project and Location as the new Model to train, and have the same
* modelType.
* </pre>
*
* <code>string base_model_id = 3;</code>
* @return The baseModelId.
*/
java.lang.String getBaseModelId();
/**
* <pre>
* The ID of the `base` model. If it is specified, the new model will be
* trained based on the `base` model. Otherwise, the new model will be
* trained from scratch. The `base` model must be in the same
* Project and Location as the new Model to train, and have the same
* modelType.
* </pre>
*
* <code>string base_model_id = 3;</code>
* @return The bytes for baseModelId.
*/
com.google.protobuf.ByteString
getBaseModelIdBytes();
}
|
/**
*/
/* THIS FILE IS DERIVED FROM spidermonkey_drv.c
* ORIGINAL COPYRIGHT NOTICE
author Kevin Smith <ksmith@basho.com>
copyright 2009-2010 Basho Technologies
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 erjang.driver.js;
import java.io.IOException;
import java.nio.ByteBuffer;
import kilim.Pausable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.ScriptableObject;
import erjang.EAtom;
import erjang.EBinary;
import erjang.EHandle;
import erjang.ERT;
import erjang.ETuple;
import erjang.driver.EAsync;
import erjang.driver.EDriver;
import erjang.driver.EDriverInstance;
import erjang.driver.IO;
public class EJSDriverInstance extends EDriverInstance {
static final EAtom am_ok = ERT.am_ok;
static final EAtom am_error = ERT.am_error;
static final EAtom am_unknown_command = EAtom.intern("unknown_command");
static ContextFactory cf_global = ContextFactory.getGlobal();
static class EContext extends Context {
public EContext() {
super(cf_global);
}
}
public EJSDriverInstance(EDriver driver) {
super(driver);
}
void send_ok_response(EBinary call_id) throws Pausable {
driver_output_term(ETuple.make(call_id, am_ok));
}
void send_error_string_response(EBinary call_id, String msg)
throws Pausable {
driver_output_term(ETuple.make(call_id, am_error, EBinary
.fromString(msg)));
}
void send_string_response(EBinary call_id, String result) throws Pausable {
driver_output_term(ETuple.make(call_id, am_ok, EBinary
.fromString(result)));
}
void unknown_command(EBinary call_id) throws Pausable {
driver_output_term(ETuple.make(call_id, am_error, am_unknown_command));
}
short IJ = ('i' << 8) | 'j';
short EJ = ('e' << 8) | 'j';
short DJ = ('d' << 8) | 'j';
short SD = ('s' << 8) | 'd';
private VM vm;
@Override
protected void readyAsync(EAsync data) throws Pausable {
data.ready();
}
@Override
protected void output(EHandle caller, final ByteBuffer buf) throws IOException,
Pausable {
final int cmd = buf.getShort();
final EBinary call_id = read_binary(buf);
if (cmd == IJ) {
int heap_size = buf.getInt();
vm = sm_initialize(heap_size * 1024 * 1024);
send_ok_response(call_id);
} else {
EAsync job = new EAsync() {
String err, resp;
// called in separate thread
@Override
public void async() {
if (cmd == EJ) {
String filename = read_string(buf);
String code = read_string(buf);
String result = sm_eval(filename, code, true);
if (result.startsWith("{\"error\"")) {
err = result;
} else {
resp = result;
}
} else if (cmd == DJ) {
String filename = read_string(buf);
String code = read_string(buf);
String result = sm_eval(filename, code, false);
if (result != null) {
err = result;
}
} else if (cmd == SD) {
vm = null;
}
}
// called when done
@Override
public void ready() throws Pausable {
if (err != null) {
send_error_string_response(call_id, err);
} else if (resp != null) {
send_string_response(call_id, err);
} else {
send_ok_response(call_id);
}
}
};
driver_async(job);
}
}
static class VM {
EContext cx;
ScriptableObject global;
}
private VM sm_initialize(int i) {
VM vm = new VM();
vm.cx = new EContext();
cf_global.enterContext(vm.cx);
try {
vm.global = vm.cx.initStandardObjects();
return vm;
} finally {
Context.exit();
}
}
private String sm_eval(String filename, String code, boolean handle_retval) {
Context ctx = cf_global.enterContext(vm.cx);
try {
Script scr = ctx.compileString(code, filename, 1, null);
Object result = scr.exec(ctx, vm.global);
if (handle_retval) {
if (result instanceof String) {
return (String) result;
} else if (result == Context.getUndefinedValue()){
return "{\"error\": \"Expression returned undefined\", \"lineno\": 0, \"source\": \"unknown\"}";
} else {
return "{\"error\": \"non-JSON return value\", \"lineno\": 0, \"source\": \"unknown\"}";
}
} else {
return null;
}
} finally {
Context.exit();
}
}
private EBinary read_binary(ByteBuffer buf) {
int str_len = buf.getInt();
EBinary str = new EBinary(buf.array(),
buf.position()+buf.arrayOffset(), str_len);
buf.position(buf.position()+str_len);
return str;
}
private String read_string(ByteBuffer buf) {
int str_len = buf.getInt();
byte[] data = new byte[str_len];
buf.get(data);
return new String(data, IO.UTF8);
}
}
|
package fr.lacnet.mcm.ext1.card.door.curse;
import fr.lacnet.mcm.ext1.card.door.Door;
import fr.lacnet.mcm.ext1.player.Player;
/**
*
* @author jlacroix
*
*/
public interface Curse extends Door {
/**
*
* @param player
* who will be cursed
*/
void apply(Player player);
/**
*
*/
void doCurse();
}
|
package Utils;
import Lianjia.Community;
import Lianjia.House;
import ORM.Service.HouseService;
import java.util.List;
import java.util.Map;
public class HouseRunner implements Runnable {
private List<Community> communities;
private Map<String,House> resMap;
public HouseRunner(List<Community> communities,Map<String,House> resMap) {
this.communities = communities;
this.resMap = resMap;
}
@Override
public void run() {
int count = 0;
for (Community community : communities) {
count += community.getCount();
HouseService service = new HouseService();
service.getCompleteHouseDataByCommunity(community,resMap);
}
CommonUtils.Logger().info(Thread.currentThread().getName() + "----一个线程结束,处理了" + communities.size() + "个小区" + count + "条二手房数据");
}
}
|
package jmxexperiment;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
public class JMXExperiment {
public static void main(String[] args) {
System.out.println("hello world!");
try {
// The object Name doesn't need to follow the package qualified name, it can be completely different
// THe part after the colon is just a comma-separated listed of key-value pairs
ObjectName objectName = new ObjectName("com.jorisroovers.jmx.experiment:type=basic,name=game");
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
server.registerMBean(new Game(), objectName);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Registration for Game mbean with the platform server is successfull");
System.out.println("Please open jConsole to access Game mbean");
while (true) {
// to ensure application does not terminate
}
}
}
|
/**
* Ejercicio 10 tema 05
*
* Calcula la media de los números introducidos.
*
* @author José Robles Bastidas
*/
public class Ejercicio10 {
public static void main(String[] args) {
double numerosCantidad = 0;
double numeroIntroducido = 0;
double suma = 0;
System.out.println("Este programa calcula la media de los números introducidos");
System.out.println("Vaya introduciendo números, para parar ingrese un número negativo:");
while (numeroIntroducido >= 0) {
numeroIntroducido = Double.parseDouble(System.console().readLine());
numerosCantidad++;
suma += numeroIntroducido;
}
System.out.println("La media de los números positivos introducidos es " + (suma - numeroIntroducido)/ (numerosCantidad - 1));
}
}
|
package com.nmys.story.model.entity;
import lombok.Data;
/**
* Description:配置选项
* Author:70kg
* Param
* Return
* Date 2018/5/11 13:42
*/
@Data
public class Options {
// 配置名称
private String name;
// 配置值
private String value;
// 配置描述
private String description;
}
|
package edu.uchicago.cs.heprofiler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for {@link HEProfiler}.
*
* @author Connor Imes
*/
public final class HEProfilerTest {
@Before
public void init() {
HEProfiler.init(EnumA.class, null, 20, null, 0, "target");
}
@After
public void destroy() {
try {
HEProfiler.dispose();
} catch (IllegalStateException e) {
// do nothing
}
}
@Test
public void test_normal() {
// just need the before and after methods to run
}
@Test(expected = IllegalStateException.class)
public void test_double_init() {
HEProfiler.init(EnumA.class, null, 20, null, 0, "target");
}
@Test(expected = IllegalStateException.class)
public void test_double_dipose() {
HEProfiler.dispose();
HEProfiler.dispose();
}
private enum EnumA {
A
}
}
|
//2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
//
//What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
public class test005 {
public static void main(String[] args) {
System.out.println(getSmallestMultiple(20));
}
static long getSmallestMultiple(long x) {
long n=1;
for(long i=1;i<=x;i++)
n=getProduct(n,i);
return n;
}
static long getProduct(long x,long y) {
return x*y/getFactor(x,y);
}
static long getFactor(long x,long y) {
long n=1;
for(long i=1;i<=x;i++)
{
if(x/i*i==x&&y/i*i==y)
n=i;
}
return n;
}
}
|
package myProgram;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
String no = "123456789";
int pos3 = no.indexOf("3");
System.out.println("The Pos of 3 is: "+pos3+"\nof:"+no);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.