hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
5350e4374359f25c46533872c2c77060f3008213 | 3,490 | package com.rbkmoney.newway.handler.dominant.impl;
import com.rbkmoney.damsel.domain.*;
import com.rbkmoney.newway.dao.dominant.iface.DomainObjectDao;
import com.rbkmoney.newway.dao.dominant.impl.PaymentMethodDaoImpl;
import com.rbkmoney.newway.domain.enums.PaymentMethodType;
import com.rbkmoney.newway.domain.tables.pojos.PaymentMethod;
import com.rbkmoney.newway.handler.dominant.AbstractDominantHandler;
import com.rbkmoney.newway.util.PaymentMethodUtils;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
import java.util.Optional;
import java.util.function.Supplier;
@Component
public class PaymentMethodHandler extends AbstractDominantHandler<PaymentMethodObject, PaymentMethod, String> {
private static final String SEPARATOR = ".";
private static final String DEPRECATED = "_deprecated";
private final PaymentMethodDaoImpl paymentMethodDao;
public PaymentMethodHandler(PaymentMethodDaoImpl paymentMethodDao) {
this.paymentMethodDao = paymentMethodDao;
}
@Override
protected DomainObjectDao<PaymentMethod, String> getDomainObjectDao() {
return paymentMethodDao;
}
@Override
protected PaymentMethodObject getTargetObject() {
return getDomainObject().getPaymentMethod();
}
@Override
protected String getTargetObjectRefId() {
var paymentMethod = wrapPaymentMethod(getTargetObject().getRef().getId());
Optional<String> paymentMethodRefId = PaymentMethodUtils.getPaymentMethodRefIdByBankCard(paymentMethod)
.or(() -> PaymentMethodUtils.getPaymentMethodRefIdByPaymentTerminal(paymentMethod))
.or(() -> PaymentMethodUtils.getPaymentMethodRefIdByDigitalWallet(paymentMethod))
.or(() -> PaymentMethodUtils.getPaymentMethodRefIdByCryptoCurrency(paymentMethod))
.or(() -> PaymentMethodUtils.getPaymentMethodRefIdByMobile(paymentMethod));
if (paymentMethodRefId.isEmpty()) {
throw new IllegalArgumentException("Unknown payment method: " + paymentMethod);
}
return getPaymentType(getTargetObject()) + SEPARATOR + paymentMethodRefId.get();
}
private Supplier<Optional<com.rbkmoney.damsel.domain.PaymentMethod>> wrapPaymentMethod(
@NotNull com.rbkmoney.damsel.domain.PaymentMethod paymentMethod) {
return () -> Optional.of(paymentMethod);
}
private String getPaymentType(PaymentMethodObject pmObj) {
return pmObj.getRef().getId().getSetField().getFieldName().replaceAll(DEPRECATED, "");
}
@Override
protected boolean acceptDomainObject() {
return getDomainObject().isSetPaymentMethod();
}
@Override
public PaymentMethod convertToDatabaseObject(
PaymentMethodObject paymentMethodObject,
Long versionId,
boolean current) {
PaymentMethod paymentMethod = new PaymentMethod();
paymentMethod.setVersionId(versionId);
paymentMethod.setPaymentMethodRefId(getTargetObjectRefId());
var data = paymentMethodObject.getData();
paymentMethod.setName(data.getName());
paymentMethod.setDescription(data.getDescription());
paymentMethod.setType(
Enum.valueOf(
PaymentMethodType.class,
getPaymentType(paymentMethodObject)
)
);
paymentMethod.setCurrent(current);
return paymentMethod;
}
}
| 39.213483 | 111 | 0.719484 |
e5eade3dad6bdb677c89b0f085559f4833feef0e | 442 | package com.deer.wms.bill.manage.model;
import com.deer.wms.project.seed.core.service.QueryParams;
/**
* Created by on 2019/02/21.
*/
public class MtAlonePrintModelParams extends QueryParams {
/**
* 模版类型
*/
private Integer printModelType;
public Integer getPrintModelType() {
return printModelType;
}
public void setPrintModelType(Integer printModelType) {
this.printModelType = printModelType;
}
}
| 19.217391 | 59 | 0.710407 |
f5816c87fae5208e0eccd3c660f37c09beeb6cbb | 1,224 | /*
* Copyright 2017 Andrii Horishnii
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.andreyrage.leftdb.entities;
import com.github.andreyrage.leftdb.annotation.ColumnName;
import com.github.andreyrage.leftdb.annotation.ColumnPrimaryKey;
/**
* Created by rage on 26.07.16.
*/
public abstract class BaseEntity {
@ColumnPrimaryKey
private long id;
@ColumnName("base")
private String baseField;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getBaseField() {
return baseField;
}
public void setBaseField(String baseField) {
this.baseField = baseField;
}
}
| 24.979592 | 75 | 0.700163 |
4c0f3387aaacf1453acd64b1a6a4819c3a72231b | 3,199 | package it.polimi.vovarini.model.godcards;
import it.polimi.vovarini.common.exceptions.BoxFullException;
import it.polimi.vovarini.common.exceptions.InvalidNumberOfPlayersException;
import it.polimi.vovarini.common.exceptions.InvalidPositionException;
import it.polimi.vovarini.model.Game;
import it.polimi.vovarini.model.Player;
import it.polimi.vovarini.model.Point;
import it.polimi.vovarini.model.board.Board;
import it.polimi.vovarini.model.board.items.Block;
import it.polimi.vovarini.model.moves.Movement;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HeraTests {
private Game game;
private GodCard hera;
@BeforeEach
public void init() {
try {
game = new Game(2);
game.addPlayer("Guest01");
game.addPlayer("Guest02");
hera = GodCardFactory.create(GodName.Hera);
hera.setGameData(game);
for (Player player : game.getPlayers()) {
player.setGodCard(hera);
}
} catch (InvalidNumberOfPlayersException e) {
e.printStackTrace();
}
}
private static Stream<Arguments> provideAllPossibleMovementMoves() {
LinkedList<Arguments> args = new LinkedList<>();
Board board = new Board(Board.DEFAULT_SIZE);
LinkedList<Point> allPoints = new LinkedList<>();
for (int x = 0; x < board.getSize(); x++) {
for (int y = 0; y < board.getSize(); y++) {
allPoints.add(new Point(x, y));
}
}
for (Point start : allPoints) {
List<Point> startAdjacentPositions = board.getAdjacentPositions(start);
for (Point end : startAdjacentPositions) {
args.add(Arguments.of(start, end));
}
}
return args.stream();
}
@Test
@DisplayName("Test that a GodCard of type Hera can be instantiated correctly")
public void heraCreation() {
assertEquals(GodName.Hera, game.getCurrentPlayer().getGodCard().name);
}
@ParameterizedTest
@MethodSource("provideAllPossibleMovementMoves")
@DisplayName("Test that Hera's winning constraint are correctly applied")
void testWinningConstraint(Point start, Point end) {
try {
game.getBoard().place(Block.blocks[0], start);
game.getBoard().place(Block.blocks[1], start);
game.getBoard().place(game.getCurrentPlayer().getCurrentWorker(), start);
game.getBoard().place(Block.blocks[0], end);
game.getBoard().place(Block.blocks[1], end);
game.getBoard().place(Block.blocks[2], end);
} catch (InvalidPositionException | BoxFullException e) {
e.printStackTrace();
}
Movement movement = new Movement(game.getBoard(), start, end);
int endX = end.getX();
int endY = end.getY();
boolean expected = endX != 0 && endX != Board.DEFAULT_SIZE - 1 && endY != 0 && endY != Board.DEFAULT_SIZE - 1;
assertEquals(expected, hera.isMovementWinning(movement));
}
}
| 31.362745 | 114 | 0.70522 |
6e48112f4be9e3ce0e58c824a52289d7d7a774f3 | 499 | package eu.f3rog.blade.compiler;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.TypeElement;
import eu.f3rog.blade.compiler.util.ProcessorError;
/**
* Interface {@link ProcessorModule}
*
* @author FrantisekGazo
* @version 2015-12-19
*/
public interface ProcessorModule {
void prepare() throws ProcessorError;
void process(TypeElement bladeElement) throws ProcessorError;
void process(RoundEnvironment roundEnv) throws ProcessorError;
}
| 20.791667 | 66 | 0.777555 |
5cd6f975203d34b10f0892213cbe828ebf77a886 | 589 | package com.anteoy.coreJava.reflect;
public class ClassDemo2 {
public static void main(String[] args) {
Class c1 = int.class;//int ��������
Class c2 = String.class;//String��������� String���ֽ��루�Լ�������)
Class c3 = double.class;
Class c4 = Double.class;
Class c5 = void.class;
System.out.println(c1.getName());
System.out.println(c2.getName());
System.out.println(c2.getSimpleName());//�������������������
System.out.println(c5.getName());
System.err.println(new String("A").equals("b"));
}
}
| 29.45 | 75 | 0.548387 |
83d4e2f11b61970c11b818b4e8a26b50c787fe7e | 704 | package it.polimi.ingsw.message.updateMsg;
import it.polimi.ingsw.message.ViewObserver;
import it.polimi.ingsw.message.viewMsg.ViewGameMsg;
/**
* Turn Controller --> VV --> CLI/GUI
*
* msg send from Server to client to notify him that is not his turn
* but another player is actually playing
*/
public class VWaitYourTurnMsg extends ViewGameMsg {
private String username;
public VWaitYourTurnMsg(String msgContent, String username) {
super(msgContent);
this.username = username;
}
public String getUsername() {
return username;
}
@Override
public void notifyHandler(ViewObserver viewObserver) {
viewObserver.receiveMsg(this);
}
}
| 24.275862 | 68 | 0.704545 |
45bf05bd096987370fefe3be7da7af7c7ef4c4ba | 359 | package be.woutschoovaerts.mollie.data.permission;
import be.woutschoovaerts.mollie.data.common.Link;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PermissionLinks {
private Link self;
private Link documentation;
}
| 17.95 | 50 | 0.81337 |
1efd8ed1989a98272018b9891445d2c222bda3a7 | 1,238 | /*
* Copyright (C) 2020 Intel Corporation. All rights reserved. SPDX-License-Identifier: Apache-2.0
*/
package com.openiot.cloud.base.profiling;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import com.openiot.cloud.base.help.BaseUtil;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleAlarmHandler implements AlarmHandler {
private static final Logger logger = LoggerFactory.getLogger(DurationCounter.class);
private String alarmOutputPath;
public SimpleAlarmHandler(String alarmOutputPath) {
this.alarmOutputPath = alarmOutputPath;
}
@Override
public void triggerAlarm(String content) {
Path report = Paths.get(alarmOutputPath);
try (OutputStream out =
new BufferedOutputStream(Files.newOutputStream(report, CREATE, APPEND))) {
out.write(content.getBytes());
} catch (IOException e) {
logger.warn("IOException when output alarm to " + alarmOutputPath);
logger.warn(BaseUtil.getStackTrace(e));
}
}
}
| 30.195122 | 97 | 0.761712 |
8d7a3d56dfca812b331db66bfd788bd41b53008b | 41,395 | /*
* Copyright 2004-2013 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.docksidestage.mysql.dbflute.cbean.cq.bs;
import java.util.*;
import org.dbflute.cbean.*;
import org.dbflute.cbean.chelper.*;
import org.dbflute.cbean.ckey.*;
import org.dbflute.cbean.coption.*;
import org.dbflute.cbean.cvalue.ConditionValue;
import org.dbflute.cbean.ordering.*;
import org.dbflute.cbean.scoping.*;
import org.dbflute.cbean.sqlclause.SqlClause;
import org.dbflute.dbmeta.DBMetaProvider;
import org.docksidestage.mysql.dbflute.allcommon.*;
import org.docksidestage.mysql.dbflute.cbean.*;
import org.docksidestage.mysql.dbflute.cbean.cq.*;
/**
* The abstract condition-query of white_compound_pk_ref.
* @author DBFlute(AutoGenerator)
*/
public abstract class AbstractBsWhiteCompoundPkRefCQ extends AbstractConditionQuery {
// ===================================================================================
// Constructor
// ===========
public AbstractBsWhiteCompoundPkRefCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(referrerQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// DB Meta
// =======
@Override
protected DBMetaProvider xgetDBMetaProvider() {
return DBMetaInstanceHandler.getProvider();
}
public String asTableDbName() {
return "white_compound_pk_ref";
}
// ===================================================================================
// Query
// =====
/**
* Equal(=). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param multipleFirstId The value of multipleFirstId as equal. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleFirstId_Equal(Integer multipleFirstId) {
doSetMultipleFirstId_Equal(multipleFirstId);
}
protected void doSetMultipleFirstId_Equal(Integer multipleFirstId) {
regMultipleFirstId(CK_EQ, multipleFirstId);
}
/**
* GreaterThan(>). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param multipleFirstId The value of multipleFirstId as greaterThan. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleFirstId_GreaterThan(Integer multipleFirstId) {
regMultipleFirstId(CK_GT, multipleFirstId);
}
/**
* LessThan(<). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param multipleFirstId The value of multipleFirstId as lessThan. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleFirstId_LessThan(Integer multipleFirstId) {
regMultipleFirstId(CK_LT, multipleFirstId);
}
/**
* GreaterEqual(>=). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param multipleFirstId The value of multipleFirstId as greaterEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleFirstId_GreaterEqual(Integer multipleFirstId) {
regMultipleFirstId(CK_GE, multipleFirstId);
}
/**
* LessEqual(<=). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param multipleFirstId The value of multipleFirstId as lessEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleFirstId_LessEqual(Integer multipleFirstId) {
regMultipleFirstId(CK_LE, multipleFirstId);
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param minNumber The min number of multipleFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of multipleFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param opLambda The callback for option of range-of. (NotNull)
*/
public void setMultipleFirstId_RangeOf(Integer minNumber, Integer maxNumber, ConditionOptionCall<RangeOfOption> opLambda) {
setMultipleFirstId_RangeOf(minNumber, maxNumber, xcROOP(opLambda));
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param minNumber The min number of multipleFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of multipleFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param rangeOfOption The option of range-of. (NotNull)
*/
public void setMultipleFirstId_RangeOf(Integer minNumber, Integer maxNumber, RangeOfOption rangeOfOption) {
regROO(minNumber, maxNumber, xgetCValueMultipleFirstId(), "MULTIPLE_FIRST_ID", rangeOfOption);
}
/**
* InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param multipleFirstIdList The collection of multipleFirstId as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setMultipleFirstId_InScope(Collection<Integer> multipleFirstIdList) {
doSetMultipleFirstId_InScope(multipleFirstIdList);
}
protected void doSetMultipleFirstId_InScope(Collection<Integer> multipleFirstIdList) {
regINS(CK_INS, cTL(multipleFirstIdList), xgetCValueMultipleFirstId(), "MULTIPLE_FIRST_ID");
}
/**
* NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
* @param multipleFirstIdList The collection of multipleFirstId as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setMultipleFirstId_NotInScope(Collection<Integer> multipleFirstIdList) {
doSetMultipleFirstId_NotInScope(multipleFirstIdList);
}
protected void doSetMultipleFirstId_NotInScope(Collection<Integer> multipleFirstIdList) {
regINS(CK_NINS, cTL(multipleFirstIdList), xgetCValueMultipleFirstId(), "MULTIPLE_FIRST_ID");
}
/**
* IsNull {is null}. And OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
*/
public void setMultipleFirstId_IsNull() { regMultipleFirstId(CK_ISN, DOBJ); }
/**
* IsNotNull {is not null}. And OnlyOnceRegistered. <br>
* MULTIPLE_FIRST_ID: {PK, NotNull, INT(10)}
*/
public void setMultipleFirstId_IsNotNull() { regMultipleFirstId(CK_ISNN, DOBJ); }
protected void regMultipleFirstId(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueMultipleFirstId(), "MULTIPLE_FIRST_ID"); }
protected abstract ConditionValue xgetCValueMultipleFirstId();
/**
* Equal(=). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param multipleSecondId The value of multipleSecondId as equal. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleSecondId_Equal(Integer multipleSecondId) {
doSetMultipleSecondId_Equal(multipleSecondId);
}
protected void doSetMultipleSecondId_Equal(Integer multipleSecondId) {
regMultipleSecondId(CK_EQ, multipleSecondId);
}
/**
* GreaterThan(>). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param multipleSecondId The value of multipleSecondId as greaterThan. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleSecondId_GreaterThan(Integer multipleSecondId) {
regMultipleSecondId(CK_GT, multipleSecondId);
}
/**
* LessThan(<). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param multipleSecondId The value of multipleSecondId as lessThan. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleSecondId_LessThan(Integer multipleSecondId) {
regMultipleSecondId(CK_LT, multipleSecondId);
}
/**
* GreaterEqual(>=). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param multipleSecondId The value of multipleSecondId as greaterEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleSecondId_GreaterEqual(Integer multipleSecondId) {
regMultipleSecondId(CK_GE, multipleSecondId);
}
/**
* LessEqual(<=). And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param multipleSecondId The value of multipleSecondId as lessEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setMultipleSecondId_LessEqual(Integer multipleSecondId) {
regMultipleSecondId(CK_LE, multipleSecondId);
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param minNumber The min number of multipleSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of multipleSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param opLambda The callback for option of range-of. (NotNull)
*/
public void setMultipleSecondId_RangeOf(Integer minNumber, Integer maxNumber, ConditionOptionCall<RangeOfOption> opLambda) {
setMultipleSecondId_RangeOf(minNumber, maxNumber, xcROOP(opLambda));
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param minNumber The min number of multipleSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of multipleSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param rangeOfOption The option of range-of. (NotNull)
*/
public void setMultipleSecondId_RangeOf(Integer minNumber, Integer maxNumber, RangeOfOption rangeOfOption) {
regROO(minNumber, maxNumber, xgetCValueMultipleSecondId(), "MULTIPLE_SECOND_ID", rangeOfOption);
}
/**
* InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param multipleSecondIdList The collection of multipleSecondId as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setMultipleSecondId_InScope(Collection<Integer> multipleSecondIdList) {
doSetMultipleSecondId_InScope(multipleSecondIdList);
}
protected void doSetMultipleSecondId_InScope(Collection<Integer> multipleSecondIdList) {
regINS(CK_INS, cTL(multipleSecondIdList), xgetCValueMultipleSecondId(), "MULTIPLE_SECOND_ID");
}
/**
* NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
* @param multipleSecondIdList The collection of multipleSecondId as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setMultipleSecondId_NotInScope(Collection<Integer> multipleSecondIdList) {
doSetMultipleSecondId_NotInScope(multipleSecondIdList);
}
protected void doSetMultipleSecondId_NotInScope(Collection<Integer> multipleSecondIdList) {
regINS(CK_NINS, cTL(multipleSecondIdList), xgetCValueMultipleSecondId(), "MULTIPLE_SECOND_ID");
}
/**
* IsNull {is null}. And OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
*/
public void setMultipleSecondId_IsNull() { regMultipleSecondId(CK_ISN, DOBJ); }
/**
* IsNotNull {is not null}. And OnlyOnceRegistered. <br>
* MULTIPLE_SECOND_ID: {PK, NotNull, INT(10)}
*/
public void setMultipleSecondId_IsNotNull() { regMultipleSecondId(CK_ISNN, DOBJ); }
protected void regMultipleSecondId(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueMultipleSecondId(), "MULTIPLE_SECOND_ID"); }
protected abstract ConditionValue xgetCValueMultipleSecondId();
/**
* Equal(=). And NullIgnored, OnlyOnceRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param refFirstId The value of refFirstId as equal. (basically NotNull: error as default, or no condition as option)
*/
public void setRefFirstId_Equal(Integer refFirstId) {
doSetRefFirstId_Equal(refFirstId);
}
protected void doSetRefFirstId_Equal(Integer refFirstId) {
regRefFirstId(CK_EQ, refFirstId);
}
/**
* GreaterThan(>). And NullIgnored, OnlyOnceRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param refFirstId The value of refFirstId as greaterThan. (basically NotNull: error as default, or no condition as option)
*/
public void setRefFirstId_GreaterThan(Integer refFirstId) {
regRefFirstId(CK_GT, refFirstId);
}
/**
* LessThan(<). And NullIgnored, OnlyOnceRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param refFirstId The value of refFirstId as lessThan. (basically NotNull: error as default, or no condition as option)
*/
public void setRefFirstId_LessThan(Integer refFirstId) {
regRefFirstId(CK_LT, refFirstId);
}
/**
* GreaterEqual(>=). And NullIgnored, OnlyOnceRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param refFirstId The value of refFirstId as greaterEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setRefFirstId_GreaterEqual(Integer refFirstId) {
regRefFirstId(CK_GE, refFirstId);
}
/**
* LessEqual(<=). And NullIgnored, OnlyOnceRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param refFirstId The value of refFirstId as lessEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setRefFirstId_LessEqual(Integer refFirstId) {
regRefFirstId(CK_LE, refFirstId);
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param minNumber The min number of refFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of refFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param opLambda The callback for option of range-of. (NotNull)
*/
public void setRefFirstId_RangeOf(Integer minNumber, Integer maxNumber, ConditionOptionCall<RangeOfOption> opLambda) {
setRefFirstId_RangeOf(minNumber, maxNumber, xcROOP(opLambda));
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param minNumber The min number of refFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of refFirstId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param rangeOfOption The option of range-of. (NotNull)
*/
public void setRefFirstId_RangeOf(Integer minNumber, Integer maxNumber, RangeOfOption rangeOfOption) {
regROO(minNumber, maxNumber, xgetCValueRefFirstId(), "REF_FIRST_ID", rangeOfOption);
}
/**
* InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param refFirstIdList The collection of refFirstId as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefFirstId_InScope(Collection<Integer> refFirstIdList) {
doSetRefFirstId_InScope(refFirstIdList);
}
protected void doSetRefFirstId_InScope(Collection<Integer> refFirstIdList) {
regINS(CK_INS, cTL(refFirstIdList), xgetCValueRefFirstId(), "REF_FIRST_ID");
}
/**
* NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* REF_FIRST_ID: {IX+, NotNull, INT(10), FK to white_compound_pk}
* @param refFirstIdList The collection of refFirstId as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefFirstId_NotInScope(Collection<Integer> refFirstIdList) {
doSetRefFirstId_NotInScope(refFirstIdList);
}
protected void doSetRefFirstId_NotInScope(Collection<Integer> refFirstIdList) {
regINS(CK_NINS, cTL(refFirstIdList), xgetCValueRefFirstId(), "REF_FIRST_ID");
}
protected void regRefFirstId(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueRefFirstId(), "REF_FIRST_ID"); }
protected abstract ConditionValue xgetCValueRefFirstId();
/**
* Equal(=). And NullIgnored, OnlyOnceRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param refSecondId The value of refSecondId as equal. (basically NotNull: error as default, or no condition as option)
*/
public void setRefSecondId_Equal(Integer refSecondId) {
doSetRefSecondId_Equal(refSecondId);
}
protected void doSetRefSecondId_Equal(Integer refSecondId) {
regRefSecondId(CK_EQ, refSecondId);
}
/**
* GreaterThan(>). And NullIgnored, OnlyOnceRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param refSecondId The value of refSecondId as greaterThan. (basically NotNull: error as default, or no condition as option)
*/
public void setRefSecondId_GreaterThan(Integer refSecondId) {
regRefSecondId(CK_GT, refSecondId);
}
/**
* LessThan(<). And NullIgnored, OnlyOnceRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param refSecondId The value of refSecondId as lessThan. (basically NotNull: error as default, or no condition as option)
*/
public void setRefSecondId_LessThan(Integer refSecondId) {
regRefSecondId(CK_LT, refSecondId);
}
/**
* GreaterEqual(>=). And NullIgnored, OnlyOnceRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param refSecondId The value of refSecondId as greaterEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setRefSecondId_GreaterEqual(Integer refSecondId) {
regRefSecondId(CK_GE, refSecondId);
}
/**
* LessEqual(<=). And NullIgnored, OnlyOnceRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param refSecondId The value of refSecondId as lessEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setRefSecondId_LessEqual(Integer refSecondId) {
regRefSecondId(CK_LE, refSecondId);
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param minNumber The min number of refSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of refSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param opLambda The callback for option of range-of. (NotNull)
*/
public void setRefSecondId_RangeOf(Integer minNumber, Integer maxNumber, ConditionOptionCall<RangeOfOption> opLambda) {
setRefSecondId_RangeOf(minNumber, maxNumber, xcROOP(opLambda));
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param minNumber The min number of refSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of refSecondId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param rangeOfOption The option of range-of. (NotNull)
*/
public void setRefSecondId_RangeOf(Integer minNumber, Integer maxNumber, RangeOfOption rangeOfOption) {
regROO(minNumber, maxNumber, xgetCValueRefSecondId(), "REF_SECOND_ID", rangeOfOption);
}
/**
* InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param refSecondIdList The collection of refSecondId as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefSecondId_InScope(Collection<Integer> refSecondIdList) {
doSetRefSecondId_InScope(refSecondIdList);
}
protected void doSetRefSecondId_InScope(Collection<Integer> refSecondIdList) {
regINS(CK_INS, cTL(refSecondIdList), xgetCValueRefSecondId(), "REF_SECOND_ID");
}
/**
* NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* REF_SECOND_ID: {NotNull, INT(10), FK to white_compound_pk}
* @param refSecondIdList The collection of refSecondId as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefSecondId_NotInScope(Collection<Integer> refSecondIdList) {
doSetRefSecondId_NotInScope(refSecondIdList);
}
protected void doSetRefSecondId_NotInScope(Collection<Integer> refSecondIdList) {
regINS(CK_NINS, cTL(refSecondIdList), xgetCValueRefSecondId(), "REF_SECOND_ID");
}
protected void regRefSecondId(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueRefSecondId(), "REF_SECOND_ID"); }
protected abstract ConditionValue xgetCValueRefSecondId();
/**
* Equal(=). And NullOrEmptyIgnored, OnlyOnceRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)}
* @param refName The value of refName as equal. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefName_Equal(String refName) {
doSetRefName_Equal(fRES(refName));
}
protected void doSetRefName_Equal(String refName) {
regRefName(CK_EQ, refName);
}
/**
* NotEqual(<>). And NullOrEmptyIgnored, OnlyOnceRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)}
* @param refName The value of refName as notEqual. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefName_NotEqual(String refName) {
doSetRefName_NotEqual(fRES(refName));
}
protected void doSetRefName_NotEqual(String refName) {
regRefName(CK_NES, refName);
}
/**
* InScope {in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)}
* @param refNameList The collection of refName as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefName_InScope(Collection<String> refNameList) {
doSetRefName_InScope(refNameList);
}
protected void doSetRefName_InScope(Collection<String> refNameList) {
regINS(CK_INS, cTL(refNameList), xgetCValueRefName(), "REF_NAME");
}
/**
* NotInScope {not in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)}
* @param refNameList The collection of refName as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setRefName_NotInScope(Collection<String> refNameList) {
doSetRefName_NotInScope(refNameList);
}
protected void doSetRefName_NotInScope(Collection<String> refNameList) {
regINS(CK_NINS, cTL(refNameList), xgetCValueRefName(), "REF_NAME");
}
/**
* LikeSearch with various options. (versatile) {like '%xxx%' escape ...}. And NullOrEmptyIgnored, SeveralRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)} <br>
* <pre>e.g. setRefName_LikeSearch("xxx", op <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> op.<span style="color: #CC4747">likeContain()</span>);</pre>
* @param refName The value of refName as likeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option)
* @param opLambda The callback for option of like-search. (NotNull)
*/
public void setRefName_LikeSearch(String refName, ConditionOptionCall<LikeSearchOption> opLambda) {
setRefName_LikeSearch(refName, xcLSOP(opLambda));
}
/**
* LikeSearch with various options. (versatile) {like '%xxx%' escape ...}. And NullOrEmptyIgnored, SeveralRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)} <br>
* <pre>e.g. setRefName_LikeSearch("xxx", new <span style="color: #CC4747">LikeSearchOption</span>().likeContain());</pre>
* @param refName The value of refName as likeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option)
* @param likeSearchOption The option of like-search. (NotNull)
*/
public void setRefName_LikeSearch(String refName, LikeSearchOption likeSearchOption) {
regLSQ(CK_LS, fRES(refName), xgetCValueRefName(), "REF_NAME", likeSearchOption);
}
/**
* NotLikeSearch with various options. (versatile) {not like 'xxx%' escape ...} <br>
* And NullOrEmptyIgnored, SeveralRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)}
* @param refName The value of refName as notLikeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option)
* @param opLambda The callback for option of like-search. (NotNull)
*/
public void setRefName_NotLikeSearch(String refName, ConditionOptionCall<LikeSearchOption> opLambda) {
setRefName_NotLikeSearch(refName, xcLSOP(opLambda));
}
/**
* NotLikeSearch with various options. (versatile) {not like 'xxx%' escape ...} <br>
* And NullOrEmptyIgnored, SeveralRegistered. <br>
* REF_NAME: {NotNull, VARCHAR(50)}
* @param refName The value of refName as notLikeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option)
* @param likeSearchOption The option of not-like-search. (NotNull)
*/
public void setRefName_NotLikeSearch(String refName, LikeSearchOption likeSearchOption) {
regLSQ(CK_NLS, fRES(refName), xgetCValueRefName(), "REF_NAME", likeSearchOption);
}
protected void regRefName(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueRefName(), "REF_NAME"); }
protected abstract ConditionValue xgetCValueRefName();
// ===================================================================================
// ScalarCondition
// ===============
/**
* Prepare ScalarCondition as equal. <br>
* {where FOO = (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<WhiteCompoundPkRefCB> scalar_Equal() {
return xcreateSLCFunction(CK_EQ, WhiteCompoundPkRefCB.class);
}
/**
* Prepare ScalarCondition as equal. <br>
* {where FOO <> (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<WhiteCompoundPkRefCB> scalar_NotEqual() {
return xcreateSLCFunction(CK_NES, WhiteCompoundPkRefCB.class);
}
/**
* Prepare ScalarCondition as greaterThan. <br>
* {where FOO > (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<WhiteCompoundPkRefCB> scalar_GreaterThan() {
return xcreateSLCFunction(CK_GT, WhiteCompoundPkRefCB.class);
}
/**
* Prepare ScalarCondition as lessThan. <br>
* {where FOO < (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<WhiteCompoundPkRefCB> scalar_LessThan() {
return xcreateSLCFunction(CK_LT, WhiteCompoundPkRefCB.class);
}
/**
* Prepare ScalarCondition as greaterEqual. <br>
* {where FOO >= (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<WhiteCompoundPkRefCB> scalar_GreaterEqual() {
return xcreateSLCFunction(CK_GE, WhiteCompoundPkRefCB.class);
}
/**
* Prepare ScalarCondition as lessEqual. <br>
* {where FOO <= (select max(BAR) from ...)}
* <pre>
* cb.query().<span style="color: #CC4747">scalar_LessEqual()</span>.max(new SubQuery<WhiteCompoundPkRefCB>() {
* public void query(WhiteCompoundPkRefCB subCB) {
* subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span>
* subCB.query().setBar...
* }
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<WhiteCompoundPkRefCB> scalar_LessEqual() {
return xcreateSLCFunction(CK_LE, WhiteCompoundPkRefCB.class);
}
@SuppressWarnings("unchecked")
protected <CB extends ConditionBean> void xscalarCondition(String fn, SubQuery<CB> sq, String rd, HpSLCCustomized<CB> cs, ScalarConditionOption op) {
assertObjectNotNull("subQuery", sq);
WhiteCompoundPkRefCB cb = xcreateScalarConditionCB(); sq.query((CB)cb);
String pp = keepScalarCondition(cb.query()); // for saving query-value
cs.setPartitionByCBean((CB)xcreateScalarConditionPartitionByCB()); // for using partition-by
registerScalarCondition(fn, cb.query(), pp, rd, cs, op);
}
public abstract String keepScalarCondition(WhiteCompoundPkRefCQ sq);
protected WhiteCompoundPkRefCB xcreateScalarConditionCB() {
WhiteCompoundPkRefCB cb = newMyCB(); cb.xsetupForScalarCondition(this); return cb;
}
protected WhiteCompoundPkRefCB xcreateScalarConditionPartitionByCB() {
WhiteCompoundPkRefCB cb = newMyCB(); cb.xsetupForScalarConditionPartitionBy(this); return cb;
}
// ===================================================================================
// Full Text Search
// ================
/**
* Match for full-text search. <br>
* Bind variable is unused because the condition value should be literal in MySQL.
* @param textColumn The text column. (NotNull, StringColumn, TargetTableColumn)
* @param conditionValue The condition value embedded without binding (by MySQL restriction) but escaped. (NullAllowed: if null or empty, no condition)
* @param modifier The modifier of full-text search. (NullAllowed: If the value is null, No modifier specified)
*/
public void match(org.dbflute.dbmeta.info.ColumnInfo textColumn
, String conditionValue
, org.dbflute.dbway.WayOfMySQL.FullTextSearchModifier modifier) {
assertObjectNotNull("textColumn", textColumn);
match(newArrayList(textColumn), conditionValue, modifier);
}
/**
* Match for full-text search. <br>
* Bind variable is unused because the condition value should be literal in MySQL.
* @param textColumnList The list of text column. (NotNull, NotEmpty, StringColumn, TargetTableColumn)
* @param conditionValue The condition value embedded without binding (by MySQL restriction) but escaped. (NullAllowed: if null or empty, no condition)
* @param modifier The modifier of full-text search. (NullAllowed: If the value is null, no modifier specified)
*/
public void match(List<org.dbflute.dbmeta.info.ColumnInfo> textColumnList
, String conditionValue
, org.dbflute.dbway.WayOfMySQL.FullTextSearchModifier modifier) {
xdoMatchForMySQL(textColumnList, conditionValue, modifier);
}
// ===================================================================================
// Manual Order
// ============
/**
* Order along manual ordering information.
* <pre>
* cb.query().addOrderBy_Birthdate_Asc().<span style="color: #CC4747">withManualOrder</span>(<span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">op</span>.<span style="color: #CC4747">when_GreaterEqual</span>(priorityDate); <span style="color: #3F7E5E">// e.g. 2000/01/01</span>
* });
* <span style="color: #3F7E5E">// order by </span>
* <span style="color: #3F7E5E">// case</span>
* <span style="color: #3F7E5E">// when BIRTHDATE >= '2000/01/01' then 0</span>
* <span style="color: #3F7E5E">// else 1</span>
* <span style="color: #3F7E5E">// end asc, ...</span>
*
* cb.query().addOrderBy_MemberStatusCode_Asc().<span style="color: #CC4747">withManualOrder</span>(<span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Withdrawal);
* <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Formalized);
* <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Provisional);
* });
* <span style="color: #3F7E5E">// order by </span>
* <span style="color: #3F7E5E">// case</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'WDL' then 0</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'FML' then 1</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'PRV' then 2</span>
* <span style="color: #3F7E5E">// else 3</span>
* <span style="color: #3F7E5E">// end asc, ...</span>
* </pre>
* <p>This function with Union is unsupported!</p>
* <p>The order values are bound (treated as bind parameter).</p>
* @param opLambda The callback for option of manual-order containing order values. (NotNull)
*/
public void withManualOrder(ManualOrderOptionCall opLambda) { // is user public!
xdoWithManualOrder(cMOO(opLambda));
}
// ===================================================================================
// Small Adjustment
// ================
// ===================================================================================
// Very Internal
// =============
protected WhiteCompoundPkRefCB newMyCB() {
return new WhiteCompoundPkRefCB();
}
// very internal (for suppressing warn about 'Not Use Import')
protected String xabUDT() { return Date.class.getName(); }
protected String xabCQ() { return WhiteCompoundPkRefCQ.class.getName(); }
protected String xabLSO() { return LikeSearchOption.class.getName(); }
protected String xabSLCS() { return HpSLCSetupper.class.getName(); }
protected String xabSCP() { return SubQuery.class.getName(); }
}
| 52.069182 | 243 | 0.647325 |
1f25a93ff7e9a6986901768dd8f950a66331da4a | 820 | package org.jlab.smoothness.presentation.util;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ConfigurationParameterInit implements ServletContextListener {
private static final Logger LOGGER = Logger.getLogger(
ConfigurationParameterInit.class.getName());
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
// We will just expose all environment variables!
context.setAttribute("env", System.getenv());
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Nothing to do
}
}
| 28.275862 | 75 | 0.752439 |
b2bd47fc0167261baef54a5e4036c5480912c4d6 | 10,101 | /*
* Copyright 2015 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.drools.workbench.screens.testscenario.client;
import java.util.HashSet;
import javax.enterprise.event.Event;
import org.drools.workbench.models.datamodel.imports.HasImports;
import org.drools.workbench.models.testscenarios.shared.Scenario;
import org.drools.workbench.screens.testscenario.client.type.TestScenarioResourceType;
import org.drools.workbench.screens.testscenario.model.TestScenarioModelContent;
import org.drools.workbench.screens.testscenario.model.TestScenarioResult;
import org.drools.workbench.screens.testscenario.service.ScenarioTestEditorService;
import org.guvnor.common.services.shared.metadata.model.Metadata;
import org.guvnor.common.services.shared.metadata.model.Overview;
import org.guvnor.common.services.shared.test.TestResultMessage;
import org.guvnor.common.services.shared.test.TestService;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.services.datamodel.model.PackageDataModelOracleBaselinePayload;
import org.kie.workbench.common.widgets.client.datamodel.AsyncPackageDataModelOracle;
import org.kie.workbench.common.widgets.client.datamodel.AsyncPackageDataModelOracleFactory;
import org.kie.workbench.common.widgets.configresource.client.widget.bound.ImportsWidgetPresenter;
import org.kie.workbench.common.widgets.metadata.client.KieEditorWrapperView;
import org.kie.workbench.common.widgets.metadata.client.widget.OverviewWidgetPresenter;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.backend.vfs.ObservablePath;
import org.uberfire.backend.vfs.Path;
import org.uberfire.client.workbench.widgets.multipage.MultiPageEditor;
import org.uberfire.ext.editor.commons.client.history.VersionRecordManager;
import org.uberfire.mvp.PlaceRequest;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class ScenarioEditorPresenterTest {
@Mock private KieEditorWrapperView kieView;
@Mock private ScenarioEditorView view;
@Mock private VersionRecordManager versionRecordManager;
@Mock private OverviewWidgetPresenter overviewWidget;
@Mock private MultiPageEditor multiPage;
@Mock private ImportsWidgetPresenter importsWidget;
private ScenarioTestEditorServiceCallerMock service;
private ScenarioEditorPresenter editor;
private ScenarioEditorView.Presenter presenter;
private Scenario scenario;
private Overview overview;
private Scenario scenarioRunResult = null;
@Before
public void setUp() throws Exception {
AsyncPackageDataModelOracleFactory modelOracleFactory = mock(AsyncPackageDataModelOracleFactory.class);
service = new ScenarioTestEditorServiceCallerMock();
editor = new ScenarioEditorPresenter(view,
importsWidget,
service,
new TestServiceCallerMock(),
new TestScenarioResourceType(),
modelOracleFactory) {
{
kieView = ScenarioEditorPresenterTest.this.kieView;
versionRecordManager = ScenarioEditorPresenterTest.this.versionRecordManager;
overviewWidget = ScenarioEditorPresenterTest.this.overviewWidget;
}
protected void makeMenuBar() {
}
};
presenter = editor;
scenarioRunResult = new Scenario();
scenario = new Scenario();
overview = new Overview();
AsyncPackageDataModelOracle dmo = mock(AsyncPackageDataModelOracle.class);
when(modelOracleFactory.makeAsyncPackageDataModelOracle(any(Path.class),
any(HasImports.class),
any(PackageDataModelOracleBaselinePayload.class))
).thenReturn(dmo);
}
@Test
public void testSimple() throws Exception {
verify(view).setPresenter(presenter);
}
@Test
public void testRunScenarioAndSave() throws Exception {
ObservablePath path = mock(ObservablePath.class);
PlaceRequest placeRequest = mock(PlaceRequest.class);
when(versionRecordManager.getCurrentPath()).thenReturn(path);
editor.onStartup(path, placeRequest);
reset(view);
reset(importsWidget);
presenter.onRunScenario();
// Make sure imports are updated
verify(view).initKSessionSelector(path,
scenarioRunResult);
verify(importsWidget).setContent(any(AsyncPackageDataModelOracle.class),
eq(scenarioRunResult.getImports()),
anyBoolean());
editor.save("Commit message");
assertEquals(scenarioRunResult, service.savedScenario);
}
@Test
public void testEmptyScenario() throws Exception {
ObservablePath path = mock(ObservablePath.class);
PlaceRequest placeRequest = mock(PlaceRequest.class);
when(versionRecordManager.getCurrentPath()).thenReturn(path);
editor.onStartup(path, placeRequest);
verify(view).renderFixtures(eq(path), any(AsyncPackageDataModelOracle.class), eq(scenario));
}
@Test
public void testRunScenario() throws Exception {
ObservablePath path = mock(ObservablePath.class);
PlaceRequest placeRequest = mock(PlaceRequest.class);
when(versionRecordManager.getCurrentPath()).thenReturn(path);
editor.onStartup(path, placeRequest);
verify(view).initKSessionSelector(eq(path), any(Scenario.class));
reset(view);
presenter.onRunScenario();
verify(view).initKSessionSelector(eq(path), any(Scenario.class));
verify(view).showAuditView(anySet());
}
class ScenarioTestEditorServiceCallerMock
implements Caller<ScenarioTestEditorService> {
RemoteCallback remoteCallback;
ScenarioTestEditorService service = new ScenarioTestEditorServiceMock();
Scenario savedScenario = null;
@Override public ScenarioTestEditorService call() {
return service;
}
@Override public ScenarioTestEditorService call(RemoteCallback<?> remoteCallback) {
return call(remoteCallback, null);
}
@Override public ScenarioTestEditorService call(RemoteCallback<?> remoteCallback, ErrorCallback<?> errorCallback) {
this.remoteCallback = remoteCallback;
return service;
}
private class ScenarioTestEditorServiceMock implements ScenarioTestEditorService {
@Override public TestScenarioModelContent loadContent(Path path) {
TestScenarioModelContent testScenarioModelContent = new TestScenarioModelContent(scenario, overview, "org.test", new PackageDataModelOracleBaselinePayload());
remoteCallback.callback(testScenarioModelContent);
return testScenarioModelContent;
}
@Override public TestScenarioResult runScenario(Path path, Scenario scenario) {
TestScenarioResult result = new TestScenarioResult("user",
scenarioRunResult,
new HashSet<String>());
remoteCallback.callback(result);
return null;
}
@Override public Path copy(Path path, String s, String s1) {
return null;
}
@Override public Path create(Path path, String s, Scenario scenario, String s1) {
return null;
}
@Override public void delete(Path path, String s) {
}
@Override public Scenario load(Path path) {
return null;
}
@Override public Path rename(Path path, String s, String s1) {
return null;
}
@Override public Path save(Path path, Scenario content, Metadata metadata, String comment) {
savedScenario = content;
return null;
}
}
}
class TestServiceCallerMock
implements Caller<TestService> {
RemoteCallback remoteCallback;
TestServiceMock service = new TestServiceMock();
@Override public TestService call() {
return null;
}
@Override public TestService call(RemoteCallback<?> remoteCallback) {
return call(remoteCallback, null);
}
@Override public TestService call(RemoteCallback<?> remoteCallback, ErrorCallback<?> errorCallback) {
this.remoteCallback = remoteCallback;
return service;
}
private class TestServiceMock implements TestService {
@Override public void runAllTests(Path path) {
}
@Override public void runAllTests(Path path, Event<TestResultMessage> customTestResultEvent) {
}
}
}
}
| 37.136029 | 174 | 0.665083 |
7e330587cac265204a8d6ebb91f926827611b122 | 1,180 | package com.optilink.android.boilerplate.flux.action;
import android.support.v4.util.ArrayMap;
public class ActionImpl implements Action<ArrayMap<String, Object>> {
private String type;
private ArrayMap<String, Object> dataMap;
public ActionImpl(String type, Object... params) {
this.type = type;
put(params);
}
private void put(Object... params) {
int length = params.length;
// key-value must correspond
if (length % 2 != 0) {
throw new IllegalArgumentException("Do you forgot the key?");
}
int i = 0;
this.dataMap = new ArrayMap<>(length / 2);
while (i < length) {
String key = (String) params[i++];
Object value = params[i++];
dataMap.put(key, value);
}
}
@Override
public String getType() {
return type;
}
@Override
public ArrayMap<String, Object> getData() {
return dataMap;
}
@Override
public String toString() {
return super.toString() + "{" +
"type='" + type + '\'' +
", dataMap=" + dataMap +
'}';
}
}
| 24.081633 | 73 | 0.541525 |
709fe63992171d61f7aaf2e527066a340b610b03 | 2,615 | package io.zero88.qwe;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import io.github.zero88.utils.Strings;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Handler;
import io.vertx.core.Verticle;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.TestContext;
import io.vertx.junit5.VertxTestContext;
import lombok.NonNull;
public interface VertxHelper {
static <T extends Verticle> T deploy(@NonNull Vertx vertx, @NonNull TestContext context,
@NonNull DeployContext<T> deployContext) {
return doDeploy(vertx, deployContext, context::fail);
}
static <T extends Verticle> T deploy(@NonNull Vertx vertx, @NonNull VertxTestContext context,
@NonNull DeployContext<T> deployContext) {
return doDeploy(vertx, deployContext, context::failNow);
}
static <T extends Verticle> T doDeploy(Vertx vertx, DeployContext<T> deployContext, Handler<Throwable> ifFailed) {
final T verticle = deployContext.verticle();
TestHelper.LOGGER.info("START DEPLOYING VERTICLE[{}]", verticle.getClass().getName());
TestHelper.LOGGER.info(Strings.duplicate("-", 150));
long start = System.nanoTime();
CountDownLatch latch = new CountDownLatch(1);
vertx.deployVerticle(verticle, deployContext.options(), ar -> {
try {
if (ar.failed()) {
if (Objects.nonNull(deployContext.failedAsserter())) {
deployContext.failedAsserter().accept(ar.cause());
} else {
ifFailed.handle(ar.cause());
}
} else {
deployContext.successAsserter().accept(ar.result());
}
} catch (Exception e) {
ifFailed.handle(e);
} finally {
latch.countDown();
}
});
TestHelper.waitTimeout(deployContext.timeout(), latch, ifFailed);
TestHelper.LOGGER.info("DEPLOYED VERTICLE[{}] AFTER [{}]ms", verticle.getClass().getName(),
(System.nanoTime() - start) / 1e6);
TestHelper.LOGGER.info(Strings.duplicate("=", 150));
return verticle;
}
static <T extends Verticle> void deployFailed(Vertx vertx, TestContext context, DeploymentOptions options,
T verticle, Handler<Throwable> errorHandler) {
vertx.deployVerticle(verticle, options, context.asyncAssertFailure(errorHandler));
}
}
| 40.859375 | 118 | 0.604207 |
fccf26aa53e9820b51de3ea3977b5e3b6bade8ee | 24,145 | /*
* Copyright 2016, 2017 DTCC, Fujitsu Australia Software Technology, IBM - All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at`
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperledger.fabric.sdk;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import io.netty.util.internal.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperledger.fabric.protos.discovery.Protocol;
import org.hyperledger.fabric.protos.peer.FabricProposal;
import org.hyperledger.fabric.protos.peer.FabricProposalResponse;
import org.hyperledger.fabric.sdk.Channel.PeerOptions;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.PeerEventingServiceException;
import org.hyperledger.fabric.sdk.exception.PeerException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.hyperledger.fabric.sdk.helper.Config;
import org.hyperledger.fabric.sdk.security.certgen.TLSCertificateKeyPair;
import org.hyperledger.fabric.sdk.transaction.TransactionContext;
import static java.lang.String.format;
import static org.hyperledger.fabric.sdk.helper.Utils.checkGrpcUrl;
import static org.hyperledger.fabric.sdk.helper.Utils.isNullOrEmpty;
import static org.hyperledger.fabric.sdk.helper.Utils.parseGrpcUrl;
/**
* The Peer class represents a peer to which SDK sends deploy, or query proposals requests.
*/
public class Peer implements Serializable {
public static final String PEER_ORGANIZATION_MSPID_PROPERTY = "org.hyperledger.fabric.sdk.peer.organization_mspid";
private static final Config config = Config.getConfig();
private static final Log logger = LogFactory.getLog(Peer.class);
private static final boolean IS_DEBUG_LEVEL = logger.isDebugEnabled();
private static final boolean IS_TRACE_LEVEL = logger.isTraceEnabled();
private static final long serialVersionUID = -5273194649991828876L;
private static final long PEER_EVENT_RETRY_WAIT_TIME = config.getPeerRetryWaitTime();
private transient String id;
private Properties properties;
private final String name;
private final String url;
private transient volatile EndorserClient endorserClent;
private transient PeerEventServiceClient peerEventingClient;
private transient volatile boolean shutdown = false;
private Channel channel;
private String channelName; // used for logging.
private transient TransactionContext transactionContext;
private transient long lastConnectTime;
private transient AtomicLong reconnectCount;
private transient BlockEvent lastBlockEvent;
private transient long lastBlockNumber = -1L;
private transient byte[] clientTLSCertificateDigest;
private transient boolean foundClientTLSCertificateDigest;
private transient boolean connected = false; // has this peer connected.
private String endPoint = null;
private String protocol = null;
// The Peer has successfully connected.
boolean hasConnected() {
return connected;
}
Peer(String name, String grpcURL, Properties properties) throws InvalidArgumentException {
reconnectCount = new AtomicLong(0L);
id = config.getNextID();
Exception e = checkGrpcUrl(grpcURL);
if (e != null) {
throw new InvalidArgumentException("Bad peer url.", e);
}
if (StringUtil.isNullOrEmpty(name)) {
throw new InvalidArgumentException("Invalid name for peer");
}
this.url = grpcURL;
this.name = name;
this.properties = properties == null ? new Properties() : (Properties) properties.clone(); //keep our own copy.
logger.debug("Created " + toString());
}
static Peer createNewInstance(String name, String grpcURL, Properties properties) throws InvalidArgumentException {
return new Peer(name, grpcURL, properties);
}
/**
* Peer's name
*
* @return return the peer's name.
*/
public String getName() {
return name;
}
public Properties getProperties() {
return properties == null ? null : (Properties) properties.clone();
}
void unsetChannel() {
logger.debug(toString() + " unset " + channel);
channel = null;
}
BlockEvent getLastBlockEvent() {
return lastBlockEvent;
}
ExecutorService getExecutorService() {
return channel.getExecutorService();
}
void initiateEventing(TransactionContext transactionContext, PeerOptions peersOptions) throws TransactionException {
this.transactionContext = transactionContext.retryTransactionSameContext();
if (peerEventingClient == null) {
//PeerEventServiceClient(Peer peer, ManagedChannelBuilder<?> channelBuilder, Properties properties)
// peerEventingClient = new PeerEventServiceClient(this, new HashSet<Channel>(Arrays.asList(new Channel[] {channel})));
peerEventingClient = new PeerEventServiceClient(this, Endpoint.createEndpoint(url, properties), properties, peersOptions);
peerEventingClient.connect(transactionContext);
}
}
/**
* The channel the peer is set on.
*
* @return
*/
Channel getChannel() {
return channel;
}
/**
* Set the channel the peer is on.
*
* @param channel
*/
void setChannel(Channel channel) throws InvalidArgumentException {
if (null != this.channel) {
throw new InvalidArgumentException(format("Can not add peer %s to channel %s because it already belongs to channel %s.",
name, channel.getName(), this.channel.getName()));
}
logger.debug(format("%s setting channel to %s, from %s", toString(), "" + channel, "" + this.channel));
this.channel = channel;
this.channelName = channel.getName();
toString = null; //recalculated
}
/**
* Get the URL of the peer.
*
* @return {string} Get the URL associated with the peer.
*/
public String getUrl() {
return url;
}
/**
* for use in list of peers comparisons , e.g. list.contains() calls
*
* @param otherPeer the peer instance to compare against
* @return true if both peer instances have the same name and url
*/
@Override
public boolean equals(Object otherPeer) {
if (this == otherPeer) {
return true;
}
if (otherPeer == null) {
return false;
}
if (!(otherPeer instanceof Peer)) {
return false;
}
Peer p = (Peer) otherPeer;
return Objects.equals(this.name, p.name) && Objects.equals(this.url, p.url);
}
@Override
public int hashCode() {
return Objects.hash(name, url);
}
CompletableFuture<FabricProposalResponse.ProposalResponse> sendProposalAsync(FabricProposal.SignedProposal proposal) {
try {
checkSendProposal(proposal);
} catch (Exception e) {
CompletableFuture<FabricProposalResponse.ProposalResponse> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
if (IS_DEBUG_LEVEL) {
logger.debug(format("peer.sendProposalAsync %s", toString()));
}
EndorserClient localEndorserClient = getEndorserClient();
return localEndorserClient.sendProposalAsync(proposal).exceptionally(throwable -> {
removeEndorserClient(true);
if (throwable instanceof CompletionException) {
throw (CompletionException) throwable;
}
throw new CompletionException(throwable);
});
}
private synchronized EndorserClient getEndorserClient() {
EndorserClient localEndorserClient = endorserClent; //work off thread local copy.
if (null == localEndorserClient || !localEndorserClient.isChannelActive()) {
if (IS_TRACE_LEVEL) {
logger.trace(format("Channel %s creating new endorser client %s", channelName, toString()));
}
Endpoint endpoint = Endpoint.createEndpoint(url, properties);
foundClientTLSCertificateDigest = true;
clientTLSCertificateDigest = endpoint.getClientTLSCertificateDigest();
localEndorserClient = new EndorserClient(channelName, name, url, endpoint.getChannelBuilder());
if (IS_DEBUG_LEVEL) {
logger.debug(format("%s created new %s", toString(), localEndorserClient.toString()));
}
endorserClent = localEndorserClient;
}
return localEndorserClient;
}
private synchronized void removeEndorserClient(boolean force) {
EndorserClient localEndorserClient = endorserClent;
endorserClent = null;
if (null != localEndorserClient) {
if (IS_DEBUG_LEVEL) {
logger.debug(format("Peer %s removing endorser client %s, isActive: %b", toString(), localEndorserClient.toString(), localEndorserClient.isChannelActive()));
}
try {
localEndorserClient.shutdown(force);
} catch (Exception e) {
logger.warn(toString() + " error message: " + e.getMessage());
}
}
}
CompletableFuture<Protocol.Response> sendDiscoveryRequestAsync(Protocol.SignedRequest discoveryRequest) {
logger.debug(format("peer.sendDiscoveryRequstAsync %s", toString()));
EndorserClient localEndorserClient = getEndorserClient();
return localEndorserClient.sendDiscoveryRequestAsync(discoveryRequest).exceptionally(throwable -> {
removeEndorserClient(true);
if (throwable instanceof CompletionException) {
throw (CompletionException) throwable;
}
throw new CompletionException(throwable);
});
}
synchronized byte[] getClientTLSCertificateDigest() {
byte[] lclientTLSCertificateDigest = clientTLSCertificateDigest;
if (lclientTLSCertificateDigest == null) {
if (!foundClientTLSCertificateDigest) {
foundClientTLSCertificateDigest = true;
Endpoint endpoint = Endpoint.createEndpoint(url, properties);
lclientTLSCertificateDigest = endpoint.getClientTLSCertificateDigest();
}
}
return lclientTLSCertificateDigest;
}
private void checkSendProposal(FabricProposal.SignedProposal proposal) throws
PeerException, InvalidArgumentException {
if (shutdown) {
throw new PeerException(format("%s was shutdown.", toString()));
}
if (proposal == null) {
throw new PeerException(toString() + " Proposal is null");
}
Exception e = checkGrpcUrl(url);
if (e != null) {
throw new InvalidArgumentException("Bad peer url.", e);
}
}
synchronized void shutdown(boolean force) {
if (shutdown) {
return;
}
final String me = toString();
logger.debug(me + " is shutting down.");
shutdown = true;
channel = null;
lastBlockEvent = null;
lastBlockNumber = -1L;
removeEndorserClient(force);
PeerEventServiceClient lpeerEventingClient = peerEventingClient;
peerEventingClient = null;
if (null != lpeerEventingClient) {
// PeerEventServiceClient peerEventingClient1 = peerEventingClient;
logger.debug(me + " is shutting down " + lpeerEventingClient);
lpeerEventingClient.shutdown(force);
}
logger.debug(me + " is shut down.");
}
String getEventingStatus() {
PeerEventServiceClient lpeerEventingClient = peerEventingClient;
if (null == lpeerEventingClient) {
return " eventing client service not active.";
}
return lpeerEventingClient.getStatus();
}
@Override
protected void finalize() throws Throwable {
if (!shutdown) {
logger.debug(toString() + " finalized without previous shutdown.");
}
shutdown(true);
super.finalize();
}
void reconnectPeerEventServiceClient(final PeerEventServiceClient failedPeerEventServiceClient,
final Throwable throwable) {
if (shutdown) {
logger.debug(toString() + "not reconnecting PeerEventServiceClient shutdown ");
return;
}
PeerEventingServiceDisconnected ldisconnectedHandler = disconnectedHandler;
if (null == ldisconnectedHandler) {
return; // just wont reconnect.
}
TransactionContext ltransactionContext = transactionContext;
if (ltransactionContext == null) {
logger.warn(toString() + " not reconnecting PeerEventServiceClient no transaction available ");
return;
}
final TransactionContext fltransactionContext = ltransactionContext.retryTransactionSameContext();
final ExecutorService executorService = getExecutorService();
final PeerOptions peerOptions = null != failedPeerEventServiceClient.getPeerOptions() ? failedPeerEventServiceClient.getPeerOptions() :
PeerOptions.createPeerOptions();
if (!shutdown && executorService != null && !executorService.isShutdown() && !executorService.isTerminated()) {
executorService.execute(() -> ldisconnectedHandler.disconnected(new PeerEventingServiceDisconnectEvent() {
@Override
public BlockEvent getLatestBLockReceived() {
return lastBlockEvent;
}
@Override
public long getLastConnectTime() {
return lastConnectTime;
}
@Override
public long getReconnectCount() {
return reconnectCount.longValue();
}
@Override
public Throwable getExceptionThrown() {
return throwable;
}
@Override
public void reconnect(Long startBLockNumber) throws TransactionException {
logger.trace(format("%s reconnecting. Starting block number: %s", Peer.this.toString(), startBLockNumber == null ? "newest" : startBLockNumber));
reconnectCount.getAndIncrement();
if (startBLockNumber == null) {
peerOptions.startEventsNewest();
} else {
peerOptions.startEvents(startBLockNumber);
}
PeerEventServiceClient lpeerEventingClient = new PeerEventServiceClient(Peer.this,
Endpoint.createEndpoint(url, properties), properties, peerOptions);
lpeerEventingClient.connect(fltransactionContext);
peerEventingClient = lpeerEventingClient;
}
}));
}
}
void setLastConnectTime(long lastConnectTime) {
this.lastConnectTime = lastConnectTime;
}
void resetReconnectCount() {
connected = true;
reconnectCount = new AtomicLong(0L);
}
long getReconnectCount() {
return reconnectCount.longValue();
}
synchronized void setTLSCertificateKeyPair(TLSCertificateKeyPair tlsCertificateKeyPair) {
if (properties == null) {
properties = new Properties();
}
properties.put("clientKeyBytes", tlsCertificateKeyPair.getKeyPemBytes());
properties.put("clientCertBytes", tlsCertificateKeyPair.getCertPEMBytes());
Endpoint endpoint = Endpoint.createEndpoint(url, properties);
foundClientTLSCertificateDigest = true;
clientTLSCertificateDigest = endpoint.getClientTLSCertificateDigest();
removeEndorserClient(true);
endorserClent = new EndorserClient(channelName, name, url, endpoint.getChannelBuilder());
}
void setHasConnected() {
connected = true;
}
void setProperties(Properties properties) {
this.properties = properties == null ? new Properties() : properties;
toString = null; //recalculated
}
public interface PeerEventingServiceDisconnected {
/**
* Called when a disconnect is detected in peer eventing service.
*
* @param event
*/
void disconnected(PeerEventingServiceDisconnectEvent event);
}
public interface PeerEventingServiceDisconnectEvent {
/**
* The latest BlockEvent received by peer eventing service.
*
* @return The latest BlockEvent.
*/
BlockEvent getLatestBLockReceived();
/**
* Last connect time
*
* @return Last connect time as reported by System.currentTimeMillis()
*/
long getLastConnectTime();
/**
* Number reconnection attempts since last disconnection.
*
* @return reconnect attempts.
*/
long getReconnectCount();
/**
* Last exception throw for failing connection
*
* @return
*/
Throwable getExceptionThrown();
void reconnect(Long startEvent) throws TransactionException;
}
private transient PeerEventingServiceDisconnected disconnectedHandler = getDefaultDisconnectHandler();
private static PeerEventingServiceDisconnected getDefaultDisconnectHandler() {
return new PeerEventingServiceDisconnected() { //default.
@Override
public synchronized void disconnected(final PeerEventingServiceDisconnectEvent event) {
BlockEvent lastBlockEvent = event.getLatestBLockReceived();
Throwable thrown = event.getExceptionThrown();
long sleepTime = PEER_EVENT_RETRY_WAIT_TIME;
if (thrown instanceof PeerEventingServiceException) {
// means we connected and got an error or connected but timout waiting on the response
// not going away.. sleep longer.
sleepTime = Math.min(5000L, PEER_EVENT_RETRY_WAIT_TIME + event.getReconnectCount() * 100L); //wait longer if we connected.
//don't flood server.
}
Long startBlockNumber = null;
if (null != lastBlockEvent) {
startBlockNumber = lastBlockEvent.getBlockNumber();
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
logger.warn(toString() + " " + e.getMessage());
}
try {
event.reconnect(startBlockNumber);
} catch (TransactionException e) {
logger.warn(toString() + " " + e.getMessage());
}
}
};
}
/**
* Get current disconnect handler service
*
* @return The current disconnect handler service.
*/
public PeerEventingServiceDisconnected getPeerEventingServiceDisconnected() {
return disconnectedHandler;
}
/**
* Set class to handle peer eventing service disconnects
*
* @param newPeerEventingServiceDisconnectedHandler New handler to replace. If set to null no retry will take place.
* @return the old handler.
*/
public PeerEventingServiceDisconnected setPeerEventingServiceDisconnected(PeerEventingServiceDisconnected newPeerEventingServiceDisconnectedHandler) {
PeerEventingServiceDisconnected ret = disconnectedHandler;
disconnectedHandler = newPeerEventingServiceDisconnectedHandler;
return ret;
}
synchronized void setLastBlockSeen(BlockEvent lastBlockSeen) {
connected = true;
long newLastBlockNumber = lastBlockSeen.getBlockNumber();
// overkill but make sure.
if (lastBlockNumber < newLastBlockNumber) {
lastBlockNumber = newLastBlockNumber;
this.lastBlockEvent = lastBlockSeen;
if (IS_TRACE_LEVEL) {
logger.trace(toString() + " last block seen: " + lastBlockNumber);
}
}
}
/**
* Possible roles a peer can perform.
*/
public enum PeerRole {
/**
* Endorsing peer installs and runs chaincode.
*/
ENDORSING_PEER("endorsingPeer"),
/**
* Chaincode query peer will be used to invoke chaincode on chaincode query requests.
*/
CHAINCODE_QUERY("chaincodeQuery"),
/**
* Ledger Query will be used when query ledger operations are requested.
*/
LEDGER_QUERY("ledgerQuery"),
/**
* Peer will monitor block events for the channel it belongs to.
*/
EVENT_SOURCE("eventSource"),
/**
* Peer will monitor block events for the channel it belongs to.
*/
SERVICE_DISCOVERY("serviceDiscovery");
/**
* All roles.
*/
public static final EnumSet<PeerRole> ALL = EnumSet.allOf(PeerRole.class);
/**
* All roles except event source.
*/
public static final EnumSet<PeerRole> NO_EVENT_SOURCE = EnumSet.complementOf(EnumSet.of(PeerRole.EVENT_SOURCE));
private final String propertyName;
PeerRole(String propertyName) {
this.propertyName = propertyName;
}
public String getPropertyName() {
return propertyName;
}
}
String getEndpoint() {
if (null == endPoint) {
Properties properties = parseGrpcUrl(url);
endPoint = properties.get("host") + ":" + properties.getProperty("port").toLowerCase().trim();
}
return endPoint;
}
public String getProtocol() {
if (null == protocol) {
Properties properties = parseGrpcUrl(url);
protocol = properties.getProperty("protocol");
}
return protocol;
}
private transient String toString;
@Override
public String toString() {
String ltoString = toString;
if (ltoString == null) {
String mspid = "";
if (properties != null && !isNullOrEmpty(properties.getProperty(PEER_ORGANIZATION_MSPID_PROPERTY))) {
mspid = ", mspid: " + properties.getProperty(PEER_ORGANIZATION_MSPID_PROPERTY);
}
ltoString = "Peer{ id: " + id + ", name: " + name + ", channelName: " + channelName + ", url: " + url + mspid + "}";
toString = ltoString;
}
return ltoString;
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
disconnectedHandler = getDefaultDisconnectHandler();
connected = false;
reconnectCount = new AtomicLong(0L);
id = config.getNextID();
lastBlockNumber = -1L;
logger.debug(format("Reserialized peer: %s", this.toString()));
}
} // end Peer
| 34.296875 | 173 | 0.637979 |
6a6350fb6913177ab108e86b933363b66baed23a | 4,170 | package com.desklampstudios.thyroxine.eighth.model;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class EighthActvInstance {
public static final int FLAG_ALL = 7168;
public static final int FLAG_ATTENDANCETAKEN = 1024;
public static final int FLAG_CANCELLED = 2048;
//public static final int FLAG_ROOMCHANGED = 4096;
public final int actvId;
public final int blockId;
@NonNull public final String comment;
public final long flags;
@NonNull public final String roomsStr;
@NonNull public final String sponsorsStr;
public final int memberCount;
public final int capacity;
public EighthActvInstance(Builder builder) {
this.actvId = builder.actvId;
this.blockId = builder.blockId;
this.comment = builder.comment;
this.flags = builder.flags;
this.roomsStr = builder.roomsStr;
this.sponsorsStr = builder.sponsorsStr;
this.memberCount = builder.memberCount;
this.capacity = builder.capacity;
}
public boolean getFlag(long flag) {
return (this.flags & flag) != 0;
}
public boolean isFull() {
return capacity > 0 && memberCount >= capacity;
}
@NonNull
@Override
public String toString() {
return String.format("EighthActvInstance[actvId=%d, blockId=%d, comment=%s, flags=%s, " +
"roomsStr=%s, sponsorsStr=%s, memberCount=%d, capacity=%d]",
actvId, blockId, comment, flags, roomsStr, sponsorsStr, memberCount, capacity);
}
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof EighthActvInstance)) return false;
EighthActvInstance other = (EighthActvInstance) o;
return actvId == other.actvId && blockId == other.blockId && flags == other.flags &&
memberCount == other.memberCount && capacity == other.capacity &&
comment.equals(other.comment) && roomsStr.equals(other.roomsStr);
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
public static class Builder {
private int actvId = -1;
private int blockId = -1;
@NonNull private String comment = "";
private long flags = 0;
@NonNull private String roomsStr = "";
@NonNull private String sponsorsStr = "";
private int memberCount = 0;
private int capacity = -1;
public Builder() {}
public Builder actvId(int actvId) {
this.actvId = actvId;
return this;
}
public Builder blockId(int blockId) {
this.blockId = blockId;
return this;
}
public Builder comment(@NonNull String comment) {
this.comment = comment;
return this;
}
public Builder flags(long flags) {
this.flags = flags;
return this;
}
public Builder withFlag(long flag) {
this.flags |= flag;
return this;
}
public Builder withFlag(long flag, boolean set) {
if (set) {
this.flags |= flag;
} else {
this.flags &= ~flag;
}
return this;
}
public Builder roomsStr(@NonNull String roomsStr) {
this.roomsStr = roomsStr;
return this;
}
public Builder sponsorsStr(@NonNull String sponsorsStr) {
this.sponsorsStr = sponsorsStr;
return this;
}
public Builder memberCount(int memberCount) {
this.memberCount = memberCount;
return this;
}
public Builder capacity(int capacity) {
this.capacity = capacity;
return this;
}
public EighthActvInstance build() {
EighthActvInstance actvInstance = new EighthActvInstance(this);
if ((actvInstance.flags & ~FLAG_ALL) != 0) {
throw new IllegalStateException("Flags invalid: " + actvInstance.flags);
}
return actvInstance;
}
}
}
| 32.578125 | 97 | 0.593525 |
716735be9624d0acac3bc50eb3d15ac635adf989 | 2,377 | package com.sidchai.music.result;
import lombok.Getter;
import lombok.ToString;
/**
* @Author sidchai
* @since 2020-05-20
*/
@Getter
@ToString
public enum ResultCodeEnum {
SUCCESS(true, 20000,"成功"),
UNKNOWN_REASON(false, 20001, "未知错误"),
BAD_SQL_GRAMMAR(false, 21001, "sql语法错误"),
JSON_PARSE_ERROR(false, 21002, "json解析异常"),
PARAM_ERROR(false, 21003, "参数不正确"),
FILE_UPLOAD_ERROR(false, 21004, "文件上传错误"),
FILE_DELETE_ERROR(false, 21005, "文件刪除错误"),
EXCEL_DATA_IMPORT_ERROR(false, 21006, "Excel数据导入错误"),
VIDEO_UPLOAD_ALIYUN_ERROR(false, 22001, "视频上传至阿里云失败"),
VIDEO_UPLOAD_TOMCAT_ERROR(false, 22002, "视频上传至业务服务器失败"),
VIDEO_DELETE_ALIYUN_ERROR(false, 22003, "阿里云视频文件删除失败"),
FETCH_VIDEO_UPLOADAUTH_ERROR(false, 22004, "获取上传地址和凭证失败"),
REFRESH_VIDEO_UPLOADAUTH_ERROR(false, 22005, "刷新上传地址和凭证失败"),
FETCH_PLAYAUTH_ERROR(false, 22006, "获取播放凭证失败"),
URL_ENCODE_ERROR(false, 23001, "URL编码失败"),
ILLEGAL_CALLBACK_REQUEST_ERROR(false, 23002, "非法回调请求"),
FETCH_ACCESSTOKEN_FAILD(false, 23003, "获取accessToken失败"),
FETCH_USERINFO_ERROR(false, 23004, "获取用户信息失败"),
LOGIN_ERROR(false, 23005, "登录失败"),
TOKEN_ERROR(false,23006, "token过期"),
COMMENT_EMPTY(false, 24006, "评论内容必须填写"),
PAY_RUN(false, 25000, "支付中"),
PAY_UNIFIEDORDER_ERROR(false, 25001, "统一下单错误"),
PAY_ORDERQUERY_ERROR(false, 25002, "查询支付结果错误"),
GATEWAY_ERROR(false, 26000, "服务不能访问"),
CODE_ERROR(false, 28000, "验证码错误"),
LOGIN_PHONE_ERROR(false, 28009, "手机号码不正确"),
LOGIN_MESSAGE_ERROR(false, 28009, "没有查到您相关信息,请先去注册"),
LOGIN_FREEZE_ERROR(false, 28009, "该账户登录错误次数过多,已冻结"),
LOGIN_USERNAME_ERROR(false, 28001, "账号或邮箱或手机不正确"),
LOGIN_PASSWORD_ERROR(false, 28008, "密码不正确"),
LOGIN_DISABLED_ERROR(false, 28002, "该用户已被禁用"),
REGISTER_MOBLE_ERROR(false, 28003, "手机号已被注册"),
REGISTER_USERNAME_ERROR(false, 28003, "用户名已被注册"),
SONG_EXIST(false, 28009, "该歌曲已添加"),
LOGIN_AUTH(false, 28004, "需要登录"),
LOGIN_ACL(false, 28005, "没有权限"),
SMS_SEND_ERROR(false, 28006, "短信发送失败"),
SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL(false, 28007, "短信发送过于频繁");
private Boolean success;
private Integer code;
private String message;
ResultCodeEnum(Boolean success, Integer code, String message) {
this.success = success;
this.code = code;
this.message = message;
}
}
| 31.276316 | 68 | 0.706353 |
4340f474700571768bf7335f0a4d23974eefb2cf | 179 | public class shuzu3{
public static void main(String[] args){
int a[]={11,12,13};
for(int i=2;i>=0;i--){
System.out.println(a[i]);
}
}
} | 22.375 | 43 | 0.480447 |
7eb84c3ffe99f9fa53aaf545ce7a186b4ca1513b | 955 | package com.github.davetrencher.timone.util;
import com.github.davetrencher.timone.TunnelPlugin;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.ui.awt.RelativePoint;
/**
* Created by dave on 20/04/16.
*/
public class Logger {
private static final StatusBar statusBar = TunnelPlugin.getStatusBar();
private static void log(String message, MessageType messageType) {
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(message, messageType, null)
.setFadeoutTime(7500)
.createBalloon()
.show(RelativePoint.getCenterOf(statusBar.getComponent()),
Balloon.Position.atRight);
}
public static void info(String message) {
Logger.log(message, MessageType.INFO);
}
}
| 29.84375 | 75 | 0.698429 |
5cb8d2450b05145bceff0724a6c86be207c32fad | 1,216 | /*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package objectBased;
import org.apache.log4j.Logger;
/**
*
* An almost trivially simple Base class.
*
* It uses the {@link #getLogger} method to retreive the logger to use. This
* method can be overrriden by derived clases to acheive "object" based logging.
*
* @author Scott Melcher
* @author Gülcü
*/
public class Base {
static Logger logger = Logger.getLogger(Base.class);
public void myMethod() {
getLogger().debug("logging message");
}
public Logger getLogger() {
System.out.println("Base.getLogger called");
return Base.logger;
}
}
| 27.022222 | 80 | 0.711349 |
5d550ad54c4bd6e4813ee4c521dffa2153637a13 | 11,021 | // ========================================================================
// Copyright 2009 NEXCOM Systems
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.cipango.ims.hss;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.wicket.util.string.Strings;
import org.cipango.diameter.AVP;
import org.cipango.diameter.AVPList;
import org.cipango.diameter.DiameterCommand;
import org.cipango.diameter.api.DiameterFactory;
import org.cipango.diameter.api.DiameterServletRequest;
import org.cipango.diameter.base.Common;
import org.cipango.diameter.ims.Cx;
import org.cipango.diameter.ims.Cx.ReasonCode;
import org.cipango.diameter.ims.Sh;
import org.cipango.ims.hss.db.PublicIdentityDao;
import org.cipango.ims.hss.db.SubscriptionDao;
import org.cipango.ims.hss.model.ApplicationServer;
import org.cipango.ims.hss.model.ImplicitRegistrationSet;
import org.cipango.ims.hss.model.ImplicitRegistrationSet.State;
import org.cipango.ims.hss.model.InitialFilterCriteria;
import org.cipango.ims.hss.model.PSI;
import org.cipango.ims.hss.model.PrivateIdentity;
import org.cipango.ims.hss.model.PublicIdentity;
import org.cipango.ims.hss.model.PublicUserIdentity;
import org.cipango.ims.hss.model.Scscf;
import org.cipango.ims.hss.model.ServiceProfile;
import org.cipango.ims.hss.model.SpIfc;
import org.cipango.ims.hss.model.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class CxManager
{
private static final Logger __log = LoggerFactory.getLogger(CxManager.class);
private DiameterFactory _diameterFactory;
private String _scscfRealm;
private Set<String> _publicIdsToUpdate = new HashSet<String>();
private PublicIdentityDao _publicIdentityDao;
private SubscriptionDao _subscriptionDao;
/**
* <pre>
* < Push-Profile-Request > ::= < Diameter Header: 305, REQ, PXY, 16777216 >
* < Session-Id >
* { Vendor-Specific-Application-Id }
* { Auth-Session-State }
* { Origin-Host }
* { Origin-Realm }
* { Destination-Host }
* { Destination-Realm }
* { User-Name }
* *[ Supported-Features ]
* [ User-Data ]
* [ Charging-Information ]
* [ SIP-Auth-Data-Item ]
* *[ AVP ]
* *[ Proxy-Info ]
* *[ Route-Record ]
* </pre>
* @throws IOException
*/
public void sendPpr(PublicIdentity publicIdentity) throws IOException
{
Scscf scscf = publicIdentity.getScscf();
if (scscf == null)
{
__log.info("No S-CSCF assigned to " + publicIdentity + ", could not send PPR request");
_publicIdsToUpdate.remove(publicIdentity.getIdentity());
return;
}
if (!_publicIdsToUpdate.contains(publicIdentity.getIdentity()))
{
__log.info("The public identity " + publicIdentity + " has been already updated.");
return;
}
DiameterServletRequest request = newRequest(Cx.PPR, scscf);
String privateIdentity = getPrivateIdentity(publicIdentity);
request.add(Common.USER_NAME, privateIdentity);
String serviceProfile = publicIdentity.getImsSubscriptionAsXml(privateIdentity, null, false);
request.getAVPs().add(Sh.USER_DATA, serviceProfile.getBytes());
request.send();
if (publicIdentity instanceof PublicUserIdentity)
{
ImplicitRegistrationSet set = ((PublicUserIdentity) publicIdentity).getImplicitRegistrationSet();
for (PublicIdentity publicId : set.getPublicIdentities())
_publicIdsToUpdate.remove(publicId.getIdentity());
}
else
_publicIdsToUpdate.remove(publicIdentity.getIdentity());
}
/**
*
* <pre>
* <Registration-Termination-Request> ::= < Diameter Header: 304, REQ, PXY, 16777216 >
* < Session-Id >
* { Vendor-Specific-Application-Id }
* { Auth-Session-State }
* { Origin-Host }
* { Origin-Realm }
* { Destination-Host }
* { Destination-Realm }
* { User-Name }
* [ Associated-Identities ]
* *[ Supported-Features ]
* *[ Public-Identity ]
* { Deregistration-Reason }
* *[ AVP ]
* *[ Proxy-Info ]
* *[ Route-Record ]
* </pre>
* @param publicIdentity
* @return
* @throws IOException
*/
@Transactional (readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void sendRtr(Collection<PublicIdentity> publicIdentities, ReasonCode reasonCode, String reasonPhrase) throws IOException
{
Scscf scscf = publicIdentities.iterator().next().getScscf();
Subscription subscription = null;
if (scscf == null)
throw new IOException("No S-CSCF assigned to " + publicIdentities);
DiameterServletRequest request = newRequest(Cx.RTR, scscf);
for (PublicIdentity publicIdentity : publicIdentities)
request.add(Cx.PUBLIC_IDENTITY, publicIdentity.getIdentity());
String privateIdentity = getPrivateIdentity(publicIdentities.iterator().next());
request.add(Common.USER_NAME, privateIdentity);
request.getAVPs().add(getDeregistrationReason(reasonCode, reasonPhrase));
request.send();
Iterator<PublicIdentity> it2 = publicIdentities.iterator();
while (it2.hasNext())
{
PublicIdentity publicIdentity = it2.next();
if (publicIdentity instanceof PublicUserIdentity)
{
PublicUserIdentity publicUserIdentity = (PublicUserIdentity) publicIdentity;
subscription = publicUserIdentity.getPrivateIdentities().iterator().next().getSubscription();
publicUserIdentity.getImplicitRegistrationSet().deregister();
}
}
checkClearScscf(subscription);
}
private AVP<AVPList> getDeregistrationReason(ReasonCode reasonCode, String reasonPhrase)
{
AVP<AVPList> avpList = new AVP<AVPList>(Cx.DERISTRATION_REASON, new AVPList());
avpList.getValue().add(Cx.REASON_CODE, reasonCode);
if (!Strings.isEmpty(reasonPhrase))
avpList.getValue().add(Cx.REASON_INFO, reasonPhrase);
return avpList;
}
@Transactional (readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void sendRtrPrivate(Collection<PrivateIdentity> privateIdentities, ReasonCode reasonCode, String reasonPhrase) throws IOException
{
Iterator<PrivateIdentity> it = privateIdentities.iterator();
PrivateIdentity privateIdentity = it.next();
Scscf scscf = privateIdentity.getSubscription().getScscf();
if (scscf == null)
throw new IOException("No S-CSCF assigned to the subscription " + privateIdentity.getSubscription().getName());
DiameterServletRequest request = newRequest(Cx.RTR, scscf);
request.add(Common.USER_NAME, privateIdentity.getIdentity());
request.getAVPs().add(getDeregistrationReason(reasonCode, reasonPhrase));
if (it.hasNext())
{
AVPList l = new AVPList();
while (it.hasNext())
l.add(Common.USER_NAME, it.next().getIdentity());
request.add(Cx.ASSOCIATED_IDENTITIES, l);
}
request.send();
for (PrivateIdentity privateId : privateIdentities)
{
Iterator<PublicUserIdentity> it2 = privateId.getPublicIdentities().iterator();
while (it2.hasNext())
it2.next().updateState(privateId.getIdentity(), State.NOT_REGISTERED);
}
checkClearScscf(privateIdentity.getSubscription());
}
private void checkClearScscf(Subscription subscription)
{
boolean activePublic = false;
for (PublicIdentity publicId : subscription.getPublicIdentities())
{
Short state = publicId.getState();
if (State.NOT_REGISTERED != state)
activePublic = true;
}
if (!activePublic)
subscription.setScscf(null);
_subscriptionDao.save(subscription);
}
private String getPrivateIdentity(PublicIdentity publicIdentity)
{
if (publicIdentity instanceof PublicUserIdentity)
{
PublicUserIdentity publicUserIdentity = (PublicUserIdentity) publicIdentity;
String privateIdentity =
publicUserIdentity.getImplicitRegistrationSet().getRegisteredPrivateIdentity();
if (privateIdentity == null)
privateIdentity = publicUserIdentity.getPrivateIdentities().iterator().next().getIdentity();
return privateIdentity;
}
else
{
return ((PSI) publicIdentity).getPrivateServiceIdentity();
}
}
private DiameterServletRequest newRequest(DiameterCommand command, Scscf scscf)
{
DiameterServletRequest request = _diameterFactory.createRequest(null, Cx.CX_APPLICATION_ID,
command, _scscfRealm, scscf.getDiameterHost());
return request;
}
public DiameterFactory getDiameterFactory()
{
return _diameterFactory;
}
public void setDiameterFactory(DiameterFactory diameterFactory)
{
_diameterFactory = diameterFactory;
}
public Set<PublicIdentity> getPublicIdsToUpdate()
{
Set<PublicIdentity> set = new HashSet<PublicIdentity>();
for (String identity : _publicIdsToUpdate)
{
PublicIdentity publicIdentity = _publicIdentityDao.findById(identity);
if (publicIdentity == null)
__log.warn("Could not found public identity " + publicIdentity);
else
set.add(publicIdentity);
}
return set;
}
public Set<String> getPublicIdsToUpdateAsString()
{
return _publicIdsToUpdate;
}
public int getNbPublicIdsToUpdate()
{
return _publicIdsToUpdate.size();
}
public void identityUpdated(PublicIdentity publicIdentity)
{
if (State.NOT_REGISTERED != publicIdentity.getState() && publicIdentity.getScscf() != null)
_publicIdsToUpdate.add(publicIdentity.getIdentity());
}
public void profileUpdated(ServiceProfile serviceProfile)
{
for (PublicIdentity publicId : serviceProfile.getPublicIdentites())
identityUpdated(publicId);
}
public void ifcUpdated(InitialFilterCriteria ifc)
{
for (SpIfc spIfc : ifc.getServiceProfiles())
profileUpdated(spIfc.getServiceProfile());
}
public void applicationServerUpdated(ApplicationServer as)
{
for (InitialFilterCriteria ifc : as.getIfcs())
ifcUpdated(ifc);
for (PSI psi : as.getPsis())
identityUpdated(psi);
}
public String getScscfRealm()
{
return _scscfRealm;
}
public void setScscfRealm(String scscfRealm)
{
_scscfRealm = scscfRealm;
}
public PublicIdentityDao getPublicIdentityDao()
{
return _publicIdentityDao;
}
public void setPublicIdentityDao(PublicIdentityDao publicIdentityDao)
{
_publicIdentityDao = publicIdentityDao;
}
public SubscriptionDao getSubscriptionDao()
{
return _subscriptionDao;
}
public void setSubscriptionDao(SubscriptionDao subscriptionDao)
{
_subscriptionDao = subscriptionDao;
}
}
| 31.760807 | 137 | 0.73115 |
60aca071fafab812bc6d9ea50888a64dcc00eb9a | 199 |
import java.lang.Thread;
public class HelloSleep {
public static void main (String[] args)
throws InterruptedException {
System.out.println("Hello, New World!");
Thread.sleep(1000);
}
}
| 16.583333 | 42 | 0.708543 |
d45c516734f6a12e60afe648f49848b7dad5d85c | 4,102 | package java.lang;
import android.os.Build;
import com.sundayliu.utils.IOHelper;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import info.loveai.xposed.xdebuggable.XDumpDex;
import java.lang.reflect.Method;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import static de.robv.android.xposed.XposedHelpers.findMethodBestMatch;
import static java.lang.Class.forName;
public class XClassLoader {
public static void handle(final XC_LoadPackage.LoadPackageParam lpparam) {
findAndHookMethod(
"java.lang.ClassLoader",
lpparam.classLoader,
"loadClass",
String.class,
boolean.class,
new XC_MethodHook() {
private static final String mPrefix = "[ClassLoader.loadClass]";
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
super.beforeHookedMethod(param);
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String name = (String)param.args[0];
// XposedBridge.log(mPrefix + "class name:" + name);
Class<?> cls = (Class<?>)param.getResult();
if (cls != null){
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
Method mGetDex = findMethodBestMatch(Class.forName("java.lang.Class"),
"getDex");
if (mGetDex != null) {
//XposedBridge.log("support getDex");
Object dex = mGetDex.invoke(cls);
Method mGetBytes = findMethodBestMatch(Class.forName("com.android.dex.Dex"),
"getBytes");
if (mGetBytes != null){
//XposedBridge.log("support Dex.getBytes");
byte[] data = (byte[])mGetBytes.invoke(dex);
if (data != null){
if (name.startsWith("de.robv.android.xposed")) return;
if (name.startsWith("android.")) return;
if (name.startsWith("java.")) return;
XposedBridge.log(mPrefix + "dex size:" + data.length);
XposedBridge.log(mPrefix + "class name:" + name);
// ClassLoader classLoader = (ClassLoader)param.thisObject;
// if (classLoader != null){
// XposedBridge.log(mPrefix + "classloader:" + classLoader.toString());
// }
// String filename = String.format("/sdcard/sdk/dex2/dex_%d.dex",data.length);
String filename = String.format("/data/data/%s/files/dex_%d.dex",
XDumpDex.sCurrentPackageName,
data.length);
IOHelper.writeByte(data,filename);
}
}
}
}
// dumpdex
// ClassLoader classloader = cls.getClassLoader();
// XposedBridge.log(mPrefix + "classloader:" + classloader.toString());
}
}
}
);
}
}
| 49.421687 | 122 | 0.440761 |
ee3655cbf15bb3517db425554f24f46fe1e6cbd6 | 182 | package org.sms.entity;
public class VideoLibrary {
private int id;
private String videoUrl;
private String subjectName;
private String levelNo;
private String description;
}
| 16.545455 | 28 | 0.785714 |
7dfa3ebbe16a91e994a4b8e3766138a625b640e5 | 2,156 | /*
* Copyright 2012 M3, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.m3.multilane.util;
import com.sun.jersey.api.client.Client;
/**
* Jersey Client Utility
*/
public class JerseyClientUtil {
private JerseyClientUtil() {
}
/**
* Default connect timeout ms
*/
private static final Integer DEFAULT_CONNECT_TIMEOUT_MILLIS = 1000;
/**
* Default read timeout ms
*/
private static final Integer DEFAULT_READ_TIMEOUT_MILLIS = 10000;
/**
* Creates a new {@link Client} instance with default connect/read timeout values.
*
* @return client instance
*/
public static Client createClient() {
return createClient(DEFAULT_CONNECT_TIMEOUT_MILLIS, DEFAULT_READ_TIMEOUT_MILLIS);
}
/**
* Creates a new {@link Client} instance with default connect timeout value and specified read timeout value.
*
* @param readTimeoutMillis
* @return client instance
*/
public static Client createClient(Integer readTimeoutMillis) {
return createClient(DEFAULT_CONNECT_TIMEOUT_MILLIS, readTimeoutMillis);
}
/**
* Creates a new {@link Client} instance with specified connect/read timeout values.
*
* @param connectTimeoutMillis
* @param readTimeoutMillis
* @return client instance
*/
public static Client createClient(Integer connectTimeoutMillis, Integer readTimeoutMillis) {
Client client = Client.create();
client.setConnectTimeout(connectTimeoutMillis.intValue());
client.setReadTimeout(readTimeoutMillis.intValue());
return client;
}
}
| 29.534247 | 113 | 0.697124 |
13878957609919a1b6a29db5c8af22de9540b101 | 783 | package breadthfirst;
import graph.Edge;
import graph.Node;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
public class BreadthFirst {
public ArrayList<Node> BreathFirst(Node node){
ArrayList<Node> visited = new ArrayList<Node>();
Queue<Node> queue = new LinkedList<Node>();
queue.add(node);
visited.add(node);
while(!queue.isEmpty()){
Node temp = queue.poll();
HashSet<Edge> edges = temp.neighbors;
for(Edge edge: edges){
if(!visited.contains(edge.node)){
queue.add(edge.node);
visited.add(edge.node);
}
}
}
return visited;
}
}
| 21.162162 | 56 | 0.563218 |
ef999b0863f3a1b8de24cd9e64d64ae8944dada7 | 575 | package ch.uzh.ifi.hase.soprafs21.rest.dto;
public class ChatGetDTO {
private String message;
private long lobby;
private String timestamp;
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public Long getlobby() {
return lobby;
}
public void setlobby(Long id) {
this.lobby = id;
}
public String getMessage(){return message;}
public void setMessage(String message) {
this.message = message;
}
}
| 19.166667 | 48 | 0.629565 |
e037cce8a10fc3abb5c5c7260933257430d45de0 | 1,384 | package culebra.viz;
import java.util.ArrayList;
import processing.core.*;
/**
* Path Class by Daniel Shiffman
* @author Daniel Shiffman
*
*/
public class Path extends PApplet {
private ArrayList<PVector> points;
private float radius = 20.0f;
/**
* Constructor
*/
public Path() {
points = new ArrayList<PVector>();
}
/**
* Adds a point to the path
* @param x x pos
* @param y y pos
* @param z z pos
*/
public void addPoint(float x, float y, float z) {
PVector point = new PVector(x, y, z);
points.add(point);
}
/**
* Displays the paths on the canvas
*/
public void display() {
// Draw thick line for radius
stroke(175, 0, 0, 50);
strokeWeight(radius * 2);
noFill();
beginShape();
for (PVector v : points) {
vertex(v.x, v.y, v.z);
}
endShape();
// Draw thin line for center of path
stroke(255);
strokeWeight(1);
noFill();
beginShape();
for (PVector v : points) {
vertex(v.x, v.y, v.z);
}
endShape();
}
/**
* Gets the path PVectors
* @return the list of path PVectors
*/
public ArrayList<PVector> getPathPoints(){
return points;
}
/**
* Gets the path radius
* @return the radius
*/
public float getPathRadius(){
return radius;
}
/**
* Sets the path radius
* @param newRadius the desired radius
*/
public void setPathRadius(float newRadius){
this.radius = newRadius;
}
}
| 17.974026 | 50 | 0.630058 |
a186f9f3702e2a9daa881514376bef02a0600121 | 1,584 | /*
Copyright (C) 2010 Copyright 2010 Google Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.google.gwt.corp.compatibility;
public class CompatibilityImpl implements Compatibility.Impl {
public CompatibilityImpl () {
}
public int floatToIntBits (float f) {
return Numbers.floatToIntBits(f);
}
public float intBitsToFloat (int i) {
return Numbers.intBitsToFloat(i);
}
@Override
public String createString (byte[] b, int ofs, int length) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getOriginatingServerAddress () {
// TODO Auto-generated method stub
return null;
}
@Override
public void printStackTrace (Throwable e) {
// TODO Auto-generated method stub
}
@Override
public String createString (byte[] b, String encoding) {
// TODO Auto-generated method stub
return null;
}
@Override
public void sleep (int i) {
// TODO Auto-generated method stub
}
}
| 24.369231 | 75 | 0.749369 |
1730b58bce4bcb9779b641180a4e8e896c7c6674 | 2,010 | /*******************************************************************************
* Copyright (c) 2018, 2020 ArSysOp
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* ArSysOp - initial API and implementation
*******************************************************************************/
package ru.arsysop.mola.workbench.internal.handlers;
import javax.inject.Named;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
public class ExitWorkbenchHandler {
@Execute
public void execute(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell, EPartService partService, IEclipseContext context)
throws ExecutionException {
if (!partService.saveAll(true)) {
return;
}
// TranslationService translationService = context.get(TranslationService.class);
String title = "Exit dialog";
String message = "Do you want to exit the product?";
if (MessageDialog.openQuestion(shell, title, message)) {
Object workbench = context.get(IWorkbench.class.getName());
if (workbench != null && workbench instanceof IWorkbench) {
((IWorkbench) workbench).close();
}
}
}
} | 38.653846 | 123 | 0.699502 |
dc8aa1ed35514c66814f9ef8470d114e6b62325a | 1,738 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libcore.net.http;
import com.squareup.okhttp.OkHttpConnection;
import com.squareup.okhttp.OkHttpsConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public final class ExternalSpdyExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.google.ca/");
OkHttpsConnection connection = (OkHttpsConnection) OkHttpConnection.open(url);
connection.setHostnameVerifier(new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession sslSession) {
System.out.println("VERIFYING " + s);
return true;
}
});
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
| 35.469388 | 112 | 0.696778 |
70aa08947267953f746fa82a1799dc440e3edf4e | 491 | package twistrating.commands;
import org.axonframework.commandhandling.annotation.TargetAggregateIdentifier;
public class RateTwistCommand {
@TargetAggregateIdentifier
private final String twistId;
private final int rating;
public RateTwistCommand(String twistId, int rating) {
this.twistId = twistId;
this.rating = rating;
}
public String getTwistId() {
return twistId;
}
public int getRating() {
return rating;
}
}
| 20.458333 | 78 | 0.690428 |
9ccda9dede6ca8e756b98aac6fad7f440648a3f4 | 1,147 | package jp.classmethod.spring_stateless_csrf_filter.example_thymeleaf3.model.repository;
import jp.classmethod.spring_stateless_csrf_filter.example_thymeleaf3.infra.EntityStore;
import jp.classmethod.spring_stateless_csrf_filter.example_thymeleaf3.model.entity.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.Optional;
@Repository
public class UserRepository implements InitializingBean {
@Autowired
private EntityStore<User> userEntityStore;
public String save(User user) {
userEntityStore.save(user.getId(), user);
return user.getId();
}
public Optional<User> findById(String id) {
return userEntityStore.findById(id);
}
public Collection<User> all() {
return userEntityStore.all();
}
@Override
public void afterPropertiesSet() throws Exception {
save(new User("john"));
save(new User("paul"));
save(new User("george"));
save(new User("ringo"));
}
}
| 27.309524 | 88 | 0.734961 |
913fceee2346faf5e44e9b2bff47b666281ad273 | 1,888 | /*
* Copyright 2021-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 com.github.davemeier82.homeautomation.spring.core.pushnotification.pushbullet;
import com.github.davemeier82.homeautomation.core.PushNotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
public class PushbulletService implements PushNotificationService {
private static final Logger log = LoggerFactory.getLogger(PushbulletService.class);
private static final String PUSHBULLET_URI = "https://api.pushbullet.com/v2/pushes";
private final WebClient webClient;
private final String token;
public PushbulletService(WebClient webClient, String token) {
this.webClient = webClient;
this.token = token;
}
@Override
public void sendTextMessage(String title, String message) {
webClient.post()
.uri(PUSHBULLET_URI)
.header("Access-Token", token)
.header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.body(Mono.just(new PushbulletNote(title, message)), PushbulletNote.class).retrieve().bodyToMono(String.class).subscribe(log::trace);
}
}
| 37.76 | 141 | 0.771186 |
0d4d0b28ee5e6e0d7613d60917551dac33dedc96 | 6,151 | /**
* Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending
*/
/*
* ---------------------------------------------------------------------------------------------------------------------
* AUTO-GENERATED CLASS - DO NOT EDIT MANUALLY - for any changes edit CharChunkPool and regenerate
* ---------------------------------------------------------------------------------------------------------------------
*/
package io.deephaven.chunk.util.pools;
import io.deephaven.util.type.ArrayTypeUtils;
import io.deephaven.chunk.attributes.Any;
import io.deephaven.chunk.*;
import io.deephaven.util.datastructures.SegmentedSoftPool;
import org.jetbrains.annotations.NotNull;
import static io.deephaven.chunk.util.pools.ChunkPoolConstants.*;
/**
* {@link ChunkPool} implementation for chunks of floats.
*/
@SuppressWarnings("rawtypes")
public final class FloatChunkPool implements ChunkPool {
private final WritableFloatChunk<Any> EMPTY = WritableFloatChunk.writableChunkWrap(ArrayTypeUtils.EMPTY_FLOAT_ARRAY);
/**
* Sub-pools by power-of-two sizes for {@link WritableFloatChunk}s.
*/
private final SegmentedSoftPool<WritableFloatChunk>[] writableFloatChunks;
/**
* Sub-pool of {@link ResettableFloatChunk}s.
*/
private final SegmentedSoftPool<ResettableFloatChunk> resettableFloatChunks;
/**
* Sub-pool of {@link ResettableWritableFloatChunk}s.
*/
private final SegmentedSoftPool<ResettableWritableFloatChunk> resettableWritableFloatChunks;
FloatChunkPool() {
//noinspection unchecked
writableFloatChunks = new SegmentedSoftPool[NUM_POOLED_CHUNK_CAPACITIES];
for (int pcci = 0; pcci < NUM_POOLED_CHUNK_CAPACITIES; ++pcci) {
final int chunkLog2Capacity = pcci + SMALLEST_POOLED_CHUNK_LOG2_CAPACITY;
final int chunkCapacity = 1 << chunkLog2Capacity;
writableFloatChunks[pcci] = new SegmentedSoftPool<>(
SUB_POOL_SEGMENT_CAPACITY,
() -> ChunkPoolInstrumentation.getAndRecord(() -> WritableFloatChunk.makeWritableChunkForPool(chunkCapacity)),
(final WritableFloatChunk chunk) -> chunk.setSize(chunkCapacity)
);
}
resettableFloatChunks = new SegmentedSoftPool<>(
SUB_POOL_SEGMENT_CAPACITY,
() -> ChunkPoolInstrumentation.getAndRecord(ResettableFloatChunk::makeResettableChunkForPool),
ResettableFloatChunk::clear
);
resettableWritableFloatChunks = new SegmentedSoftPool<>(
SUB_POOL_SEGMENT_CAPACITY,
() -> ChunkPoolInstrumentation.getAndRecord(ResettableWritableFloatChunk::makeResettableChunkForPool),
ResettableWritableFloatChunk::clear
);
}
@Override
public final <ATTR extends Any> WritableChunk<ATTR> takeWritableChunk(final int capacity) {
return takeWritableFloatChunk(capacity);
}
@Override
public final <ATTR extends Any> void giveWritableChunk(@NotNull final WritableChunk<ATTR> writableChunk) {
giveWritableFloatChunk(writableChunk.asWritableFloatChunk());
}
@Override
public final <ATTR extends Any> ResettableReadOnlyChunk<ATTR> takeResettableChunk() {
return takeResettableFloatChunk();
}
@Override
public final <ATTR extends Any> void giveResettableChunk(@NotNull final ResettableReadOnlyChunk<ATTR> resettableChunk) {
giveResettableFloatChunk(resettableChunk.asResettableFloatChunk());
}
@Override
public final <ATTR extends Any> ResettableWritableChunk<ATTR> takeResettableWritableChunk() {
return takeResettableWritableFloatChunk();
}
@Override
public final <ATTR extends Any> void giveResettableWritableChunk(@NotNull final ResettableWritableChunk<ATTR> resettableWritableChunk) {
giveResettableWritableFloatChunk(resettableWritableChunk.asResettableWritableFloatChunk());
}
public final <ATTR extends Any> WritableFloatChunk<ATTR> takeWritableFloatChunk(final int capacity) {
if (capacity == 0) {
//noinspection unchecked
return (WritableFloatChunk<ATTR>) EMPTY;
}
final int poolIndexForTake = getPoolIndexForTake(checkCapacityBounds(capacity));
if (poolIndexForTake >= 0) {
final WritableFloatChunk result = writableFloatChunks[poolIndexForTake].take();
result.setSize(capacity);
//noinspection unchecked
return ChunkPoolReleaseTracking.onTake(result);
}
//noinspection unchecked
return ChunkPoolReleaseTracking.onTake(WritableFloatChunk.makeWritableChunkForPool(capacity));
}
public final void giveWritableFloatChunk(@NotNull final WritableFloatChunk writableFloatChunk) {
if (writableFloatChunk == EMPTY || writableFloatChunk.isAlias(EMPTY)) {
return;
}
ChunkPoolReleaseTracking.onGive(writableFloatChunk);
final int capacity = writableFloatChunk.capacity();
final int poolIndexForGive = getPoolIndexForGive(checkCapacityBounds(capacity));
if (poolIndexForGive >= 0) {
writableFloatChunks[poolIndexForGive].give(writableFloatChunk);
}
}
public final <ATTR extends Any> ResettableFloatChunk<ATTR> takeResettableFloatChunk() {
//noinspection unchecked
return ChunkPoolReleaseTracking.onTake(resettableFloatChunks.take());
}
public final void giveResettableFloatChunk(@NotNull final ResettableFloatChunk resettableFloatChunk) {
resettableFloatChunks.give(ChunkPoolReleaseTracking.onGive(resettableFloatChunk));
}
public final <ATTR extends Any> ResettableWritableFloatChunk<ATTR> takeResettableWritableFloatChunk() {
//noinspection unchecked
return ChunkPoolReleaseTracking.onTake(resettableWritableFloatChunks.take());
}
public final void giveResettableWritableFloatChunk(@NotNull final ResettableWritableFloatChunk resettableWritableFloatChunk) {
resettableWritableFloatChunks.give(ChunkPoolReleaseTracking.onGive(resettableWritableFloatChunk));
}
}
| 43.316901 | 140 | 0.694846 |
0367b8ccb36793f0253c8c525ea11a4b87bf1d53 | 2,296 | package com.labyrinth.game.Screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.labyrinth.game.Actor.BaseActor;
import com.labyrinth.game.Game.BaseGame;
import com.labyrinth.game.Game.MazeGame;
public class EndScreen extends BaseScreen {
private Music endGameMusic;
@Override
public void initialize() {
BaseActor end = new BaseActor(0, 0, mainStage);
end.loadTexture("backgrounds/gameOver.png");
end.centerAtPosition(800, 540);
endGameMusic = Gdx.audio.newMusic(Gdx.files.internal("audio/endGame.mp3"));
TextButton replayButton = new TextButton("Replay (ENTER)", BaseGame.textButtonStyle);
replayButton.addListener(
(Event e) ->
{
if(!(e instanceof InputEvent) ||
!((InputEvent) e).getType().equals(Type.touchDown)){
return false;
}
endGameMusic.stop();
MazeGame.setActiveScreen(new LevelScreen());
return false;
}
);
TextButton quitButton = new TextButton("Quit (ESC)", BaseGame.textButtonStyle);
quitButton.addListener(
(Event e) ->
{
if(!(e instanceof InputEvent) ||
!((InputEvent) e).getType().equals(Type.touchDown)){
return false;
}
Gdx.app.exit();
return false;
}
);
uiTable.add(replayButton).center().padRight(50f);
uiTable.add(quitButton).center();
endGameMusic.play();
}
@Override
public void update(float dt) { }
@Override
public boolean keyDown(int keycode) {
if (Gdx.input.isKeyPressed(Keys.ENTER)) {
endGameMusic.stop();
MazeGame.setActiveScreen(new LevelScreen());
}
if (Gdx.input.isKeyPressed(Keys.ESCAPE)) {
Gdx.app.exit();
}
return false;
}
}
| 30.613333 | 93 | 0.58101 |
5d8a0e361b6f1a57f21c23386c2885c3c8c52e9b | 654 | import org.junit.Assert;
import org.junit.Test;
public class Q00307mTest {
@Test
public void test() {
Q00307m numArray = new Q00307m(new int[]{1, 3, 5, 4, 2});
Assert.assertEquals(9, numArray.sumRange(0, 2)); // 返回 9 ,sum([1,3,5]) = 9
Assert.assertEquals(13, numArray.sumRange(0, 3)); // 返回 9 ,sum([1,3,5]) = 9
Assert.assertEquals(6, numArray.sumRange(3, 4)); // 返回 9 ,sum([1,3,5]) = 9
numArray.update(1, 2); // nums = [1,2,5]
Assert.assertEquals(8, numArray.sumRange(0, 2)); // 返回 8 ,sum([1,2,5]) = 9
Assert.assertEquals(12, numArray.sumRange(0, 3)); // 返回 8 ,sum([1,2,5]) = 9
}
} | 38.470588 | 83 | 0.571865 |
4636a2752ca488432912faf79adf42ce74567384 | 1,632 | package org.tenwell.identity.common.resolver;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
public class IdentityExceptionResolver implements HandlerExceptionResolver{
static Logger LOGGER = LoggerFactory.getLogger(IdentityExceptionResolver.class);
@Resource(name="messageSource")
MessageSource messageSource;
@Resource(name="jsonView")
MappingJacksonJsonView jsonView;
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// TODO Auto-generated method stub
LOGGER.error(ex.getMessage(), ex);
String contentType = request.getContentType();
ModelAndView mv = new ModelAndView(jsonView);
if(ex instanceof SQLException) {
int sqlErrorCode = ((SQLException)ex).getErrorCode();
mv.addObject("err", String.format("%s [error code %d]", ex.getClass().getName(), sqlErrorCode));
mv.addObject("traceInfo", ex.toString());
} else {
mv.addObject("err", ex.getClass().getName());
mv.addObject("traceInfo", ex.toString());
}
return mv;
}
}
| 36.266667 | 128 | 0.772059 |
6616de80f076a854ceef2b3b416e43693a6f2ddd | 490 | package lumberwizard.scholarlyarcana.world.spell;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
public class Firebolt extends Spell {
public Firebolt() {
super(TargetType.ENTITY);
}
@Override
public InteractionResultHolder<ItemStack> castSpell(Level level, Player player, ItemStack spellbook) {
return null;
}
}
| 25.789474 | 106 | 0.757143 |
1e86094bf2a8751e48953f80936e1e84cfcf0c43 | 5,901 | package io.quarkus.oidc.client;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import io.quarkus.oidc.common.runtime.OidcCommonConfig;
import io.quarkus.oidc.common.runtime.OidcConstants;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
@ConfigGroup
public class OidcClientConfig extends OidcCommonConfig {
/**
* A unique OIDC client identifier. It must be set when OIDC clients are created dynamically
* and is optional in all other cases.
*/
@ConfigItem
public Optional<String> id = Optional.empty();
/**
* If this client configuration is enabled.
*/
@ConfigItem(defaultValue = "true")
public boolean clientEnabled = true;
/**
* List of access token scopes
*/
@ConfigItem
public Optional<List<String>> scopes = Optional.empty();
/**
* Refresh token time skew in seconds.
* If this property is enabled then the configured number of seconds is added to the current time
* when checking whether the access token should be refreshed. If the sum is greater than this access token's
* expiration time then a refresh is going to happen.
*/
@ConfigItem
public Optional<Duration> refreshTokenTimeSkew = Optional.empty();
public Grant grant = new Grant();
@ConfigGroup
public static class Grant {
public static enum Type {
/**
* 'client_credentials' grant requiring an OIDC client authentication only
*/
CLIENT("client_credentials"),
/**
* 'password' grant requiring both OIDC client and user ('username' and 'password') authentications
*/
PASSWORD("password"),
/**
* 'authorization_code' grant requiring an OIDC client authentication as well as
* at least 'code' and 'redirect_uri' parameters which must be passed to OidcClient at the token request time.
*/
CODE("authorization_code"),
/**
* 'urn:ietf:params:oauth:grant-type:token-exchange' grant requiring an OIDC client authentication as well as
* at least 'subject_token' parameter which must be passed to OidcClient at the token request time.
*/
EXCHANGE("urn:ietf:params:oauth:grant-type:token-exchange");
private String grantType;
private Type(String grantType) {
this.grantType = grantType;
}
public String getGrantType() {
return grantType;
}
}
/**
* Grant type
*/
@ConfigItem(defaultValue = "client")
public Type type = Type.CLIENT;
/**
* Access token property name in a token grant response
*/
@ConfigItem(defaultValue = OidcConstants.ACCESS_TOKEN_VALUE)
public String accessTokenProperty = OidcConstants.ACCESS_TOKEN_VALUE;
/**
* Refresh token property name in a token grant response
*/
@ConfigItem(defaultValue = OidcConstants.REFRESH_TOKEN_VALUE)
public String refreshTokenProperty = OidcConstants.REFRESH_TOKEN_VALUE;
/**
* Refresh token property name in a token grant response
*/
@ConfigItem(defaultValue = OidcConstants.EXPIRES_IN)
public String expiresInProperty = OidcConstants.EXPIRES_IN;
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getAccessTokenProperty() {
return accessTokenProperty;
}
public void setAccessTokenProperty(String accessTokenProperty) {
this.accessTokenProperty = accessTokenProperty;
}
public String getRefreshTokenProperty() {
return refreshTokenProperty;
}
public void setRefreshTokenProperty(String refreshTokenProperty) {
this.refreshTokenProperty = refreshTokenProperty;
}
public String getExpiresInProperty() {
return expiresInProperty;
}
public void setExpiresInProperty(String expiresInProperty) {
this.expiresInProperty = expiresInProperty;
}
}
/**
* Grant options
*/
@ConfigItem
public Map<String, Map<String, String>> grantOptions;
/**
* Requires that all filters which use 'OidcClient' acquire the tokens at the post-construct initialization time,
* possibly long before these tokens are used.
* This property should be disabled if the access token may expire before it is used for the first time and no refresh token
* is available.
*/
@ConfigItem(defaultValue = "true")
public boolean earlyTokensAcquisition = true;
public Optional<String> getId() {
return id;
}
public void setId(String id) {
this.id = Optional.of(id);
}
public Map<String, Map<String, String>> getGrantOptions() {
return grantOptions;
}
public void setGrantOptions(Map<String, Map<String, String>> grantOptions) {
this.grantOptions = grantOptions;
}
public boolean isClientEnabled() {
return clientEnabled;
}
public void setClientEnabled(boolean clientEnabled) {
this.clientEnabled = clientEnabled;
}
public Optional<List<String>> getScopes() {
return scopes;
}
public void setScopes(List<String> scopes) {
this.scopes = Optional.of(scopes);
}
public Optional<Duration> getRefreshTokenTimeSkew() {
return refreshTokenTimeSkew;
}
public void setRefreshTokenTimeSkew(Duration refreshTokenTimeSkew) {
this.refreshTokenTimeSkew = Optional.of(refreshTokenTimeSkew);
}
}
| 30.895288 | 128 | 0.64023 |
6e20f8a96cfbf0d886c1cdfdfba1cf13eac89cab | 649 | package iterator_java_util;
import java.util.Arrays;
import java.util.List;
import domein.CafeMenu;
import domein.DinerMenu;
import domein.Menu;
import domein.PancakeHouseMenu;
import domein.Waitress;
public class IteratorStartUp {
public static void main(String args[]) {
//PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
//DinerMenu dinerMenu = new DinerMenu();
List<Menu> menus = Arrays.asList(new PancakeHouseMenu(), new DinerMenu(), new CafeMenu());
//Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);
Waitress waitress = new Waitress(menus);
waitress.printMenu();
}
}
| 24.961538 | 93 | 0.728814 |
f2f7b17152b2ebdfe437f5cb07cfd175a1333152 | 516 | package com.gmail.imshhui.easy;
import org.junit.Assert;
import org.junit.Test;
/**
* User: liyulin
* Date: 2020/1/13
*/
public class AssignCookiesTEst {
AssignCookies client = new AssignCookies();
@Test
public void findContentChildren() {
int[] g = {1, 2, 3};
int[] s = {1, 1};
Assert.assertEquals(1, client.findContentChildren(g, s));
Assert.assertEquals(2, client.findContentChildren(new int[]{10, 9, 8, 7}, new int[]{5, 6, 7, 8}));
}
}
| 23.454545 | 107 | 0.593023 |
0e2212f056fdadcc279ebb0505ea33b0de1b812f | 3,613 | /*
* Copyright (c) 2015 IBM Corporation and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.brunel.maps.projection;
import org.brunel.geom.Point;
import org.brunel.geom.Rect;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Base class for a map projection
*/
public abstract class Projection {
public Rect projectedBounds(Point[] points) {
Rect r = null;
for (Point p : points) {
Point q = transform(p);
if (r==null)
r = new Rect(q.x, q.x, q.y,q.y);
else
r = r.union(q);
}
return r;
}
// Output formatting must be in US default
public static final NumberFormat F = new DecimalFormat("#.####", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
static final String width = "geom.inner_width"; // Javascript name for the map width in px
static final String height = "geom.inner_height"; // Javascript name for the map height in px
static final String LN = "\n\t\t"; // For output formatting
String translateDefinition() {
return ".translate([" + width + "/2, " + height + "/2])";
}
String scaleDefinition(Rect extent) {
return ".scale(Math.min((" + width + "-4)/" + F.format(extent.width())
+ ", (" + height + "-4)/" + F.format(extent.height()) + "))";
}
/**
* The D3 definition
*
* @return D3 string defining the function
* @param bounds the lat/long bounds to display
*/
public abstract String d3Definition(Rect bounds);
/**
* Rough estimate of the area of a small rectangle at the given location, when projected
* @param p point to estimate at
* @return calcuated area
*/
public double getTissotArea(Point p) {
double h = 5e-4; // About 50m at the equator
double dx = Math.abs(transform(p.translate(-h, 0)).x - transform(p.translate(h, 0)).x);
double dy = Math.abs(transform(p.translate(0, -h)).y - transform(p.translate(0, h)).y);
return dx * dy;
}
/**
* Projects forward
*
* @param p point in lat/long coordinates
* @return 2D screen coordinates
*/
public abstract Point transform(Point p);
/**
* Projects backwards. May not be defined for all projections
*
* @param p the projected point
* @return 2D longitude, latitude
*/
public abstract Point inverse(Point p);
/**
* Provides a good guess at the size of a projected rectangle
*
* @param b rectangle to project
* @return size in projected coordinate space
*/
Rect transform(Rect b) {
Rect bounds = null;
for (Point pt : b.makeBoundaryPoints()) {
Point p = transform(pt);
if (bounds == null) bounds = new Rect(p.x, p.x, p.y, p.y);
else bounds = bounds.union(p);
}
return bounds;
}
}
| 31.692982 | 119 | 0.603653 |
4c1e8f5968ad3791e8c5701d32b0c3e023fc0969 | 29,841 | /**
* 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.sqoop.manager;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.avro.LogicalType;
import org.apache.avro.Schema.Type;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.BytesWritable;
import org.apache.sqoop.avro.AvroUtil;
import org.apache.sqoop.mapreduce.hcat.SqoopHCatUtilities;
import org.apache.sqoop.SqoopOptions;
import org.apache.sqoop.hive.HiveTypes;
import org.apache.sqoop.lib.BlobRef;
import org.apache.sqoop.lib.ClobRef;
import org.apache.sqoop.mapreduce.parquet.ParquetJobConfiguratorFactory;
import org.apache.sqoop.util.ExportException;
import org.apache.sqoop.util.ImportException;
/**
* Abstract interface that manages connections to a database.
* The implementations of this class drive the actual discussion with
* the database about table formats, etc.
*/
public abstract class ConnManager {
public static final Log LOG = LogFactory.getLog(SqlManager.class.getName());
protected SqoopOptions options;
/**
* Return a list of all databases on a server.
*/
public abstract String [] listDatabases();
/**
* Return a list of all tables in a database.
*/
public abstract String [] listTables();
/**
* Return a list of column names in a table in the order returned by the db.
*/
public abstract String [] getColumnNames(String tableName);
/**
* Return a list of stored procedure argument names in the order
* that they are declared.
*/
public String [] getColumnNamesForProcedure(String procedureName) {
throw new UnsupportedOperationException(
"No stored procedure support for this database");
}
/**
* Return a list of column names in query in the order returned by the db.
*/
public String [] getColumnNamesForQuery(String query) {
LOG.error("This database does not support free-form query column names.");
return null;
}
/**
* Return the name of the primary key for a table, or null if there is none.
*/
public abstract String getPrimaryKey(String tableName);
/**
* Resolve a database-specific type to the Java type that should contain it.
* @param sqlType sql type
* @return the name of a Java type to hold the sql datatype, or null if none.
*/
public String toJavaType(int sqlType) {
// Mappings taken from:
// http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
if (sqlType == Types.INTEGER) {
return "Integer";
} else if (sqlType == Types.VARCHAR) {
return "String";
} else if (sqlType == Types.CHAR) {
return "String";
} else if (sqlType == Types.LONGVARCHAR) {
return "String";
} else if (sqlType == Types.NVARCHAR) {
return "String";
} else if (sqlType == Types.NCHAR) {
return "String";
} else if (sqlType == Types.LONGNVARCHAR) {
return "String";
} else if (sqlType == Types.NUMERIC) {
return "java.math.BigDecimal";
} else if (sqlType == Types.DECIMAL) {
return "java.math.BigDecimal";
} else if (sqlType == Types.BIT) {
return "Boolean";
} else if (sqlType == Types.BOOLEAN) {
return "Boolean";
} else if (sqlType == Types.TINYINT) {
return "Integer";
} else if (sqlType == Types.SMALLINT) {
return "Integer";
} else if (sqlType == Types.BIGINT) {
return "Long";
} else if (sqlType == Types.REAL) {
return "Float";
} else if (sqlType == Types.FLOAT) {
return "Double";
} else if (sqlType == Types.DOUBLE) {
return "Double";
} else if (sqlType == Types.DATE) {
return "java.sql.Date";
} else if (sqlType == Types.TIME) {
return "java.sql.Time";
} else if (sqlType == Types.TIMESTAMP) {
return "java.sql.Timestamp";
} else if (sqlType == Types.BINARY
|| sqlType == Types.VARBINARY) {
return BytesWritable.class.getName();
} else if (sqlType == Types.CLOB) {
return ClobRef.class.getName();
} else if (sqlType == Types.BLOB
|| sqlType == Types.LONGVARBINARY) {
return BlobRef.class.getName();
} else {
// TODO(aaron): Support DISTINCT, ARRAY, STRUCT, REF, JAVA_OBJECT.
// Return null indicating database-specific manager should return a
// java data type if it can find one for any nonstandard type.
return null;
}
}
/**
* Resolve a database-specific type to Hive data type.
* @param sqlType sql type
* @return hive type
*/
public String toHiveType(int sqlType) {
return HiveTypes.toHiveType(sqlType);
}
/**
* Resolve a database-specific type to HCat data type. Largely follows Sqoop's
* hive translation.
* @param sqlType
* sql type
* @return hcat type
*/
public String toHCatType(int sqlType) {
return SqoopHCatUtilities.toHCatType(sqlType);
}
/**
* Resolve a database-specific type to Avro data type.
* @param sqlType sql type
* @return avro type
*/
public Type toAvroType(int sqlType) {
switch (sqlType) {
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return Type.INT;
case Types.BIGINT:
return Type.LONG;
case Types.BIT:
case Types.BOOLEAN:
return Type.BOOLEAN;
case Types.REAL:
return Type.FLOAT;
case Types.FLOAT:
case Types.DOUBLE:
return Type.DOUBLE;
case Types.NUMERIC:
case Types.DECIMAL:
return Type.STRING;
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR:
case Types.NVARCHAR:
case Types.NCHAR:
return Type.STRING;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
return Type.LONG;
case Types.BLOB:
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return Type.BYTES;
default:
throw new IllegalArgumentException("Cannot convert SQL type "
+ sqlType);
}
}
/**
* Resolve a database-specific type to Avro logical data type.
* @param sqlType sql type
* @param precision
* @param scale
* @return avro type
*/
public LogicalType toAvroLogicalType(int sqlType, Integer precision, Integer scale) {
Configuration conf = options.getConf();
switch (sqlType) {
case Types.NUMERIC:
case Types.DECIMAL:
return AvroUtil.createDecimalType(precision, scale, conf);
default:
throw new IllegalArgumentException("Cannot convert SQL type "
+ sqlType + " to avro logical type");
}
}
/**
* Return java type for SQL type.
* @param tableName table name
* @param columnName column name
* @param sqlType sql type
* @return java type
*/
public String toJavaType(String tableName, String columnName, int sqlType) {
// ignore table name and column name by default.
return toJavaType(sqlType);
}
/**
* Return hive type for SQL type.
* @param tableName table name
* @param columnName column name
* @param sqlType sql type
* @return hive type
*/
public String toHiveType(String tableName, String columnName, int sqlType) {
// ignore table name and column name by default.
return toHiveType(sqlType);
}
/**
* Return avro type for SQL type.
* @param tableName table name
* @param columnName column name
* @param sqlType sql type
* @return avro type
*/
public Type toAvroType(String tableName, String columnName, int sqlType) {
// ignore table name and column name by default.
return toAvroType(sqlType);
}
/**
* Return avro logical type for SQL type.
* @param tableName table name
* @param columnName column name
* @param sqlType sql type
* @param precision precision
* @param scale scale
* @return avro type
*/
public LogicalType toAvroLogicalType(String tableName, String columnName, int sqlType, Integer precision, Integer scale) {
// ignore table name and column name by default.
return toAvroLogicalType(sqlType, precision, scale);
}
/**
* Return an unordered mapping from colname to sqltype for
* all columns in a table.
*
* The Integer type id is a constant from java.sql.Types
*/
public abstract Map<String, Integer> getColumnTypes(String tableName);
/**
* Return an unordered mapping from colname to sqltype for
* all the input arguments for a stored procedure.
*
* The Integer type id is a constant from java.sql.Types
*/
public Map<String, Integer> getColumnTypesForProcedure(
String procedureName) {
throw new UnsupportedOperationException(
"No stored procedure support for this database");
}
/**
* Return an unordered mapping from colname to sqltype for
* all columns in a table or query.
*
* The Integer type id is a constant from java.sql.Types
*
* @param tableName the name of the table
* @param sqlQuery the SQL query to use if tableName is null
*/
public Map<String, Integer> getColumnTypes(String tableName,
String sqlQuery) throws IOException {
Map<String, Integer> columnTypes;
if (null != tableName) {
// We're generating a class based on a table import.
columnTypes = getColumnTypes(tableName);
} else {
// This is based on an arbitrary query.
String query = sqlQuery;
if (query.indexOf(SqlManager.SUBSTITUTE_TOKEN) == -1) {
throw new IOException("Query [" + query + "] must contain '"
+ SqlManager.SUBSTITUTE_TOKEN + "' in WHERE clause.");
}
columnTypes = getColumnTypesForQuery(query);
}
return columnTypes;
}
/**
* Return an unordered mapping from colname to sqltype, precision and scale
* for all columns in a table.
*
* Precision and scale are as defined in the resultset metadata,
*
* The Integer type id is a constant from java.sql.Types
*/
public Map<String, List<Integer>> getColumnInfo(String tableName) {
throw new UnsupportedOperationException(
"Get column information is not supported by this manager");
}
/**
* Return an unordered mapping from colname to sqltype, precision and scale
* all the input arguments for a stored procedure.
*
* Precision and scale are as defined in the resultset metadata,
*
* The Integer type id is a constant from java.sql.Types
*/
public Map<String, List<Integer>> getColumnInfoForProcedure(
String procedureName) {
throw new UnsupportedOperationException(
"No stored procedure support for this database");
}
/**
* Return an unordered mapping from colname to sqltype, precision and scale
* for all columns in a query.
*
* Precision and scale are as defined in the resultset metadata,
*
* The Integer type id is a constant from java.sql.Types
*/
public Map<String, List<Integer>> getColumnInfoForQuery(String query) {
LOG.error("This database does not support free-form query column info.");
return null;
}
/**
* Return an unordered mapping from colname to sqltype, precision and scale
* for all columns in a table or query.
*
* The Integer type id is a constant from java.sql.Types
* Precision and scale are as defined in the resultset metadata,
* @param tableName the name of the table
* @param sqlQuery the SQL query to use if tableName is null
*/
public Map<String, List<Integer>> getColumnInfo(String tableName,
String sqlQuery) throws IOException {
Map<String, List<Integer>> colInfo;
if (null != tableName) {
// We're generating a class based on a table import.
colInfo = getColumnInfo(tableName);
} else {
// This is based on an arbitrary query.
String query = sqlQuery;
if (query.indexOf(SqlManager.SUBSTITUTE_TOKEN) == -1) {
throw new IOException("Query [" + query + "] must contain '"
+ SqlManager.SUBSTITUTE_TOKEN + "' in WHERE clause.");
}
colInfo = getColumnInfoForQuery(query);
}
return colInfo;
}
/**
* Return an unordered mapping from colname to sql type name for
* all columns in a table.
*/
public Map<String, String> getColumnTypeNamesForTable(String tableName) {
LOG.error("This database does not support column type names.");
return null;
}
/**
* Return an unordered mapping from colname to sql type name for all columns
* in a procedure.
*/
public Map<String, String> getColumnTypeNamesForProcedure(String callName) {
LOG.error("This database does not support procedure param type names.");
return null;
}
/**
* Return an unordered mapping from colname to sql type name for all columns
* in a query.
*/
public Map<String, String> getColumnTypeNamesForQuery(String query) {
LOG.error("This database does not support free-form query"
+ " column type names.");
return null;
}
/**
* Return an unordered mapping from colname to sql type name for
* all columns in a table or query.
*
* @param tableName the name of the table
* @param sqlQuery the SQL query to use if tableName is null
*/
public Map<String, String> getColumnTypeNames(String tableName,
String sqlQuery) {
return getColumnTypeNames(tableName, null, sqlQuery);
}
/**
* Return an unordered mapping from colname to sql type name for all columns
* in a table or query.
*
* @param tableName
* the name of the table
* @param callName
* the name of the procedure
* @param sqlQuery
* the SQL query to use if tableName is null
*/
public Map<String, String> getColumnTypeNames(String tableName,
String callName, String sqlQuery) {
Map<String, String> columnTypeNames;
if (null != tableName) {
// We're generating a class based on a table import.
columnTypeNames = getColumnTypeNamesForTable(tableName);
} else if (null != callName) {
columnTypeNames = getColumnTypeNamesForProcedure(callName);
} else {
// This is based on an arbitrary query.
String query = sqlQuery;
if (query.indexOf(SqlManager.SUBSTITUTE_TOKEN) == -1) {
throw new RuntimeException("Query [" + query + "] must contain '"
+ SqlManager.SUBSTITUTE_TOKEN + "' in WHERE clause.");
}
columnTypeNames = getColumnTypeNamesForQuery(query);
}
return columnTypeNames;
}
/**
* This method allows various connection managers to indicate if they support
* staging data for export jobs. The managers that do support this must
* override this method and return <tt>true</tt>.
*
* @return true if the connection manager supports staging data for export
* use-case.
*/
public boolean supportsStagingForExport() {
return false;
}
/**
* Returns the count of all rows that exist in the given table.
* @param tableName the name of the table which will be queried.
* @return the number of rows present in the given table.
* @throws SQLException if an error occurs during execution
* @throws UnsupportedOperationException if the connection manager does not
* support this operation.
*/
public long getTableRowCount(String tableName) throws SQLException {
throw new UnsupportedOperationException();
}
/**
* Deletes all records from the given table. This method is invoked during
* and export run when a staging table is specified. The staging table is
* cleaned before the commencement of export job, and after the data has
* been moved to the target table.
* @param tableName name of the table which will be emptied.
* @throws SQLException if an error occurs during execution
* @throws UnsupportedOperationException if the connection manager does not
* support this operation.
*/
public void deleteAllRecords(String tableName) throws SQLException {
throw new UnsupportedOperationException();
}
/**
* Migrates all records from the given <tt>fromTable</tt> to the target
* <tt>toTable</tt>. This method is invoked as a last step of an export
* run where the staging is used to collect data before pushing it into the
* target table.
* @param fromTable the name of the staging table
* @param toTable the name of the target table
* @throws SQLException if an error occurs during execution
* @throws UnsupportedOperationException if the connection manager does not
* support this operation.
*/
public void migrateData(String fromTable, String toTable)
throws SQLException {
throw new UnsupportedOperationException();
}
/**
* Return an unordered mapping from colname to sqltype for
* all columns in a query.
*
* The Integer type id is a constant from java.sql.Types
*/
public Map<String, Integer> getColumnTypesForQuery(String query) {
LOG.error("This database does not support free-form query column types.");
return null;
}
/**
* Execute a SQL statement to read the named set of columns from a table.
* If columns is null, all columns from the table are read. This is a direct
* (non-parallelized) read of the table back to the current client.
* The client is responsible for calling ResultSet.close() when done with the
* returned ResultSet object, and for calling release() after that to free
* internal state.
*/
public abstract ResultSet readTable(String tableName, String [] columns)
throws SQLException;
/**
* @return the actual database connection.
*/
public abstract Connection getConnection() throws SQLException;
/**
* discard the database connection.
*/
public void discardConnection(boolean doClose) {
throw new UnsupportedOperationException("No discard connection support "
+ "for this database");
}
/**
* @return a string identifying the driver class to load for this
* JDBC connection type.
*/
public abstract String getDriverClass();
/**
* Execute a SQL statement 's' and print its results to stdout.
*/
public abstract void execAndPrint(String s);
/**
* Perform an import of a table from the database into HDFS.
*/
public abstract void importTable(
org.apache.sqoop.manager.ImportJobContext context)
throws IOException, ImportException;
/**
* Perform an import of a free-form query from the database into HDFS.
*/
public void importQuery(org.apache.sqoop.manager.ImportJobContext context)
throws IOException, ImportException {
throw new ImportException(
"This database only supports table-based imports.");
}
/**
* When using a column name in a generated SQL query, how (if at all)
* should we escape that column name? e.g., a column named "table"
* may need to be quoted with backtiks: "`table`".
*
* @param colName the column name as provided by the user, etc.
* @return how the column name should be rendered in the sql text.
*/
public String escapeColName(String colName) {
return colName;
}
/**
* Variant of escapeColName() method that will escape whole column name array.
*
* @param colNames Column names as provided by the user, etc.
* @return
*/
public String [] escapeColNames(String ...colNames) {
String [] escaped = new String[colNames.length];
int i = 0;
for(String colName : colNames) {
escaped[i++] = escapeColName(colName);
}
return escaped;
}
/**
* When using a table name in a generated SQL query, how (if at all)
* should we escape that column name? e.g., a table named "table"
* may need to be quoted with backtiks: "`table`".
*
* @param tableName the table name as provided by the user, etc.
* @return how the table name should be rendered in the sql text.
*/
public String escapeTableName(String tableName) {
return tableName;
}
/**
* Return true if Sqoop common code should automatically escape table name
* when saving it to mapreduce configuration object when during export.
*
* @return True if table name should be escaped
*/
public boolean escapeTableNameOnExport() {
return false;
}
/**
* Perform any shutdown operations on the connection.
*/
public abstract void close() throws SQLException;
/**
* Export data stored in HDFS into a table in a database.
* This inserts new rows into the target table.
*/
public void exportTable(org.apache.sqoop.manager.ExportJobContext context)
throws IOException, ExportException {
throw new ExportException("This database does not support exports");
}
/**
* Export data stored in HDFS into a table in a database. This calls a stored
* procedure to insert rows into the target table.
*/
public void callTable(org.apache.sqoop.manager.ExportJobContext context)
throws IOException, ExportException {
throw new ExportException("This database does not support exports "
+ "using stored procedures");
}
/**
* Export updated data stored in HDFS into a database table.
* This updates existing rows in the target table, based on the
* updateKeyCol specified in the context's SqoopOptions.
*/
public void updateTable(org.apache.sqoop.manager.ExportJobContext context)
throws IOException, ExportException {
throw new ExportException("This database does not support updates");
}
/**
* Export data stored in HDFS into a table in a database.
* This may update or insert rows into the target table depending on
* whether rows already exist in the target table or not.
*/
public void upsertTable(org.apache.sqoop.manager.ExportJobContext context)
throws IOException, ExportException {
throw new ExportException("Mixed update/insert is not supported"
+ " against the target database yet");
}
/**
* Configure database output column ordering explicitly for code generator.
* The code generator should generate the DBWritable.write(PreparedStatement)
* method with columns exporting in this order.
*/
public void configureDbOutputColumns(SqoopOptions options) {
// We're in update mode. We need to explicitly set the database output
// column ordering in the codeGenerator. The UpdateKeyCol must come
// last, because the UPDATE-based OutputFormat will generate the SET
// clause followed by the WHERE clause, and the SqoopRecord needs to
// serialize to this layout.
// Check if user specified --columns parameter
Set<String> columns = null;
if (options.getColumns() != null && options.getColumns().length > 0) {
// If so, put all column in uppercase form into our help set
columns = new HashSet<String>();
for(String c : options.getColumns()) {
columns.add(c.toUpperCase());
}
}
Set<String> updateKeys = new LinkedHashSet<String>();
Set<String> updateKeysUppercase = new HashSet<String>();
String updateKeyValue = options.getUpdateKeyCol();
StringTokenizer stok = new StringTokenizer(updateKeyValue, ",");
while (stok.hasMoreTokens()) {
String nextUpdateColumn = stok.nextToken().trim();
if (nextUpdateColumn.length() > 0) {
String upperCase = nextUpdateColumn.toUpperCase();
// We must make sure that --columns is super set of --update-key
if (columns != null && !columns.contains(upperCase)) {
throw new RuntimeException("You must specify all columns from "
+ "--update-key parameter in --columns parameter.");
}
updateKeys.add(nextUpdateColumn);
updateKeysUppercase.add(upperCase);
} else {
throw new RuntimeException("Invalid update key column value specified"
+ ": '" + updateKeyValue + "'");
}
}
String [] allColNames = getColumnNames(options.getTableName());
List<String> dbOutCols = new ArrayList<String>();
for (String col : allColNames) {
if (!updateKeysUppercase.contains(col.toUpperCase())) {
// Skip columns that were not explicitly stated on command line
if (columns != null && !columns.contains(col.toUpperCase())) {
continue;
}
dbOutCols.add(col); // add non-key columns to the output order list.
}
}
// Then add the update key column last.
dbOutCols.addAll(updateKeys);
options.setDbOutputColumns(dbOutCols.toArray(
new String[dbOutCols.size()]));
}
/**
* If a method of this ConnManager has returned a ResultSet to you,
* you are responsible for calling release() after you close the
* ResultSet object, to free internal resources. ConnManager
* implementations do not guarantee the ability to have multiple
* returned ResultSets available concurrently. Requesting a new
* ResultSet from a ConnManager may cause other open ResulSets
* to close.
*/
public abstract void release();
/**
* Return the current time from the perspective of the database server.
* Return null if this cannot be accessed.
*/
public Timestamp getCurrentDbTimestamp() {
LOG.warn("getCurrentDbTimestamp(): Using local system timestamp.");
return new Timestamp(System.currentTimeMillis());
}
/**
* Given a non-null Timestamp, return the quoted string that can
* be inserted into a SQL statement, representing that timestamp.
*/
public String timestampToQueryString(Timestamp ts) {
return "'" + ts + "'";
}
/**
* Given a date/time, return the quoted string that can
* be inserted into a SQL statement, representing that date/time.
*/
public String datetimeToQueryString(String datetime, int columnType) {
if (columnType != Types.TIMESTAMP && columnType != Types.DATE) {
String msg = "Column type is neither timestamp nor date!";
LOG.error(msg);
throw new RuntimeException(msg);
}
return "'" + datetime + "'";
}
/**
* This method allows the ConnManager to override the creation of an
* input-bounds query that is used to create splits when running import
* based on free-form query. Any non-null return value is used, whereas a null
* return value indicates that the default input bounds query should be
* used.
* @param splitByCol the column name to split on.
* @param sanitizedQuery the sanitized input query specified by user.
* @return an input-bounds query or <tt>null</tt> if default query is
* acceptable.
*/
public String getInputBoundsQuery(String splitByCol, String sanitizedQuery) {
return null;
}
/**
* This method allows the ConnManager to override the generation of ORM
* classes if the SQOOP generated classes are not used by it.
* A return value of false from this method means that the SQOOP ORM
* classes are needed to use with the connector.
* A return value of true indicates that the connection manager does not
* use the SQOOP ORM classes. For example, in the Direct mode of some of
* the connectors, the text files are directly processed by DB specific
* facilities without even being passed through the SQOOP process and
* in those circumstances, it makes sense to disable the ORM generation.
*/
public boolean isORMFacilitySelfManaged() {
return false;
}
/**
* Determine if a column is char or a char-variant type.
* @return true if column type is CHAR, VARCHAR, LONGVARCHAR
* or their N version. These are used to store strings.
*/
public boolean isCharColumn(int columnType) {
return (columnType == Types.VARCHAR)
|| (columnType == Types.NVARCHAR)
|| (columnType == Types.CHAR)
|| (columnType == Types.NCHAR)
|| (columnType == Types.LONGVARCHAR)
|| (columnType == Types.LONGNVARCHAR);
}
/**
* Determine if HCat integration from direct mode of the connector is
* allowed. By default direct mode is not compatible with HCat
* @return Whether direct mode is allowed.
*/
public boolean isDirectModeHCatSupported() {
return false;
}
/**
* Determine if HBase operations from direct mode of the connector is
* allowed. By default direct mode is not compatible with HBase
* @return Whether direct mode is allowed.
*/
public boolean isDirectModeHBaseSupported() {
return false;
}
/**
* Determine if Accumulo operations from direct mode of the connector is
* allowed. By default direct mode is not compatible with HBase
* @return Whether direct mode is allowed.
*/
public boolean isDirectModeAccumuloSupported() {
return false;
}
public ParquetJobConfiguratorFactory getParquetJobConfigurator() {
return options.getParquetConfiguratorImplementation().createFactory();
}
}
| 34.104 | 124 | 0.684293 |
638fb1f499d48fa1ad84498c6be866fb2eaf3dea | 23,167 | // Copyright 2000-2021 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.references;
import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupElementRenderer;
import com.intellij.find.FindModel;
import com.intellij.find.impl.FindInProjectUtil;
import com.intellij.ide.presentation.Presentation;
import com.intellij.lang.jvm.JvmModifier;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.patterns.PsiMethodPattern;
import com.intellij.patterns.XmlPatterns;
import com.intellij.patterns.uast.UastPatterns;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceUtil;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.PsiFileReference;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PackageScope;
import com.intellij.psi.search.searches.AllClassesSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.ProjectIconsAccessor;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.usages.FindUsagesProcessPresentation;
import com.intellij.usages.UsageViewPresentation;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.devkit.DevKitBundle;
import org.jetbrains.idea.devkit.util.PsiUtil;
import org.jetbrains.uast.UExpression;
import org.jetbrains.uast.UField;
import org.jetbrains.uast.UastContextKt;
import org.jetbrains.uast.UastUtils;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import static com.intellij.patterns.PsiJavaPatterns.*;
/**
* @author Konstantin Bulenkov
*/
public class IconsReferencesContributor extends PsiReferenceContributor
implements QueryExecutor<PsiReference, ReferencesSearch.SearchParameters> {
@NonNls
private static final String ALL_ICONS_FQN = "com.intellij.icons.AllIcons";
@NonNls
private static final String ALL_ICONS_NAME = "AllIcons";
@NonNls
private static final String PLATFORM_ICONS_MODULE = "intellij.platform.icons";
@NonNls
private static final String ICONS_MODULE = "icons";
@NonNls
private static final String ICONS_PACKAGE_PREFIX = "icons.";
@NonNls
private static final String COM_INTELLIJ_ICONS_PREFIX = "com.intellij.icons.";
@NonNls
private static final String ICONS_CLASSNAME_SUFFIX = "Icons";
@Override
public boolean execute(@NotNull ReferencesSearch.SearchParameters queryParameters,
@NotNull final Processor<? super PsiReference> consumer) {
final PsiElement file = queryParameters.getElementToSearch();
if (file instanceof PsiBinaryFile) {
final Module module = ReadAction.compute(() -> ModuleUtilCore.findModuleForPsiElement(file));
final VirtualFile image = ((PsiBinaryFile)file).getVirtualFile();
if (isImage(image) && isIconsModule(module)) {
final Project project = file.getProject();
final FindModel model = new FindModel();
final String path = getPathToImage(image, module);
model.setStringToFind(path);
model.setCaseSensitive(true);
model.setFindAll(true);
model.setWholeWordsOnly(true);
FindInProjectUtil.findUsages(model, project, usage -> {
ApplicationManager.getApplication().runReadAction(() -> {
final PsiElement element = usage.getElement();
final ProperTextRange textRange = usage.getRangeInElement();
if (element != null && textRange != null) {
final PsiElement start = element.findElementAt(textRange.getStartOffset());
final PsiElement end = element.findElementAt(textRange.getEndOffset());
if (start != null && end != null) {
PsiElement value = PsiTreeUtil.findCommonParent(start, end);
if (value instanceof PsiJavaToken) {
value = value.getParent();
}
if (value != null) {
final PsiFileReference reference = FileReferenceUtil.findFileReference(value);
if (reference != null) {
consumer.process(reference);
}
}
}
}
});
return true;
}, new FindUsagesProcessPresentation(new UsageViewPresentation()));
}
}
return true;
}
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
registerForPresentationAnnotation(registrar);
registerForIconLoaderMethods(registrar);
registerForIconXmlAttribute(registrar);
}
private static void registerForIconXmlAttribute(@NotNull PsiReferenceRegistrar registrar) {
registrar.registerReferenceProvider(XmlPatterns.xmlAttributeValue().withLocalName("icon"), new PsiReferenceProvider() {
@Override
public PsiReference @NotNull [] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) {
if (!PsiUtil.isPluginXmlPsiElement(element)) {
return PsiReference.EMPTY_ARRAY;
}
return new PsiReference[]{
new IconPsiReferenceBase(element) {
@Override
public PsiElement resolve() {
String value = ((XmlAttributeValue)element).getValue();
if (value.startsWith("/")) {
FileReference lastRef = new FileReferenceSet(element).getLastReference();
return lastRef != null ? lastRef.resolve() : null;
}
return resolveIconPath(value, element);
}
@Override
public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException {
PsiElement element = resolve();
PsiElement resultForFile = handleFile(element, lastRef -> lastRef.handleElementRename(newElementName));
if (resultForFile != null) {
return resultForFile;
}
PsiElement resultForField = handleField(element, newElementName);
if (resultForField != null) {
return resultForField;
}
return super.handleElementRename(newElementName);
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
PsiElement resultForFile = handleFile(element, lastRef -> lastRef.bindToElement(element));
if (resultForFile != null) {
return resultForFile;
}
PsiElement resultForField = handleField(element, null);
if (resultForField != null) {
return resultForField;
}
return super.bindToElement(element);
}
private PsiElement handleFile(PsiElement element, Function<FileReference, PsiElement> callback) {
if (element instanceof PsiFile) {
FileReference lastRef = new FileReferenceSet(element).getLastReference();
if (lastRef != null) {
return callback.apply(lastRef);
}
}
return null;
}
@Nullable
private PsiElement handleField(PsiElement element, @Nullable String newElementName) {
if (element instanceof PsiField) {
PsiClass containingClass = ((PsiField)element).getContainingClass();
if (containingClass != null) {
String classQualifiedName = containingClass.getQualifiedName();
if (classQualifiedName != null) {
if (newElementName == null) {
newElementName = ((PsiField)element).getName();
}
if (classQualifiedName.startsWith(COM_INTELLIJ_ICONS_PREFIX)) {
return replace(classQualifiedName, newElementName, COM_INTELLIJ_ICONS_PREFIX);
}
if (classQualifiedName.startsWith(ICONS_PACKAGE_PREFIX)) {
return replace(classQualifiedName, newElementName, ICONS_PACKAGE_PREFIX);
}
return ElementManipulators.handleContentChange(myElement, classQualifiedName + "." + newElementName);
}
}
}
return null;
}
private PsiElement replace(@NonNls String fqn, @NonNls String newName, @NonNls String pckg) {
XmlAttribute parent = (XmlAttribute)getElement().getParent();
parent.setValue(fqn.substring(pckg.length()) + "." + newName);
return parent.getValueElement();
}
}
};
}
});
}
private static void registerForIconLoaderMethods(@NotNull PsiReferenceRegistrar registrar) {
final PsiMethodPattern method = psiMethod().withName("load").definedInClass(ALL_ICONS_FQN);
final PsiJavaElementPattern.Capture<PsiLiteralExpression> findGetIconPattern
= literalExpression().and(psiExpression().methodCallParameter(0, method));
registrar.registerReferenceProvider(findGetIconPattern, new PsiReferenceProvider() {
@Override
public PsiReference @NotNull [] getReferencesByElement(@NotNull final PsiElement element, @NotNull ProcessingContext context) {
if (!PsiUtil.isIdeaProject(element.getProject())) return PsiReference.EMPTY_ARRAY;
return new FileReferenceSet(element) {
@Override
protected Collection<PsiFileSystemItem> getExtraContexts() {
Module iconsModule = ModuleManager.getInstance(element.getProject()).findModuleByName(PLATFORM_ICONS_MODULE);
if (iconsModule == null) {
iconsModule = ModuleManager.getInstance(element.getProject()).findModuleByName(ICONS_MODULE);
}
if (iconsModule == null) {
return super.getExtraContexts();
}
final List<PsiFileSystemItem> result = new SmartList<>();
final VirtualFile[] roots = ModuleRootManager.getInstance(iconsModule).getSourceRoots();
final PsiManager psiManager = element.getManager();
for (VirtualFile root : roots) {
final PsiDirectory directory = psiManager.findDirectory(root);
ContainerUtil.addIfNotNull(result, directory);
}
return result;
}
}.getAllReferences();
}
}, PsiReferenceRegistrar.HIGHER_PRIORITY);
}
private static void registerForPresentationAnnotation(@NotNull PsiReferenceRegistrar registrar) {
UastReferenceRegistrar.registerUastReferenceProvider(
registrar,
UastPatterns.injectionHostUExpression()
.sourcePsiFilter(psi -> PsiUtil.isPluginProject(psi.getProject()))
.annotationParam(Presentation.class.getName(), "icon"),
UastReferenceRegistrar.uastInjectionHostReferenceProvider((uElement, referencePsiElement) -> new PsiReference[]{
new IconPsiReferenceBase(referencePsiElement) {
@Override
public PsiElement resolve() {
String value = UastUtils.evaluateString(uElement);
return resolveIconPath(value, referencePsiElement);
}
@Override
public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException {
PsiElement field = resolve();
PsiElement result = handleElement(field, newElementName);
if (result != null) {
return result;
}
return super.handleElementRename(newElementName);
}
@Nullable
private PsiElement handleElement(PsiElement element, @Nullable String newElementName) {
if (element instanceof PsiField) {
PsiClass containingClass = ((PsiField)element).getContainingClass();
if (containingClass != null) {
String classQualifiedName = containingClass.getQualifiedName();
if (classQualifiedName != null) {
if (newElementName == null) {
newElementName = ((PsiField)element).getName();
}
if (classQualifiedName.startsWith(COM_INTELLIJ_ICONS_PREFIX)) {
return replace(newElementName, classQualifiedName, COM_INTELLIJ_ICONS_PREFIX);
}
if (classQualifiedName.startsWith(ICONS_PACKAGE_PREFIX)) {
return replace(newElementName, classQualifiedName, ICONS_PACKAGE_PREFIX);
}
return ElementManipulators.handleContentChange(myElement, classQualifiedName + "." + newElementName);
}
}
}
return null;
}
private PsiElement replace(@NonNls String newElementName, @NonNls String fqn, @NonNls String packageName) {
String newValue = fqn.substring(packageName.length()) + "." + newElementName;
return ElementManipulators.handleContentChange(getElement(), newValue);
}
}
}), PsiReferenceRegistrar.HIGHER_PRIORITY);
}
@NotNull
@NonNls
private static String getPathToImage(VirtualFile image, Module module) {
final String path = ModuleRootManager.getInstance(module).getSourceRoots()[0].getPath();
return "/" + FileUtil.getRelativePath(path, image.getPath(), '/');
}
private static boolean isIconsModule(Module module) {
return module != null && (ICONS_MODULE.equals(module.getName()) || PLATFORM_ICONS_MODULE.equals(module.getName()))
&& ModuleRootManager.getInstance(module).getSourceRoots().length == 1;
}
private static boolean isImage(VirtualFile image) {
final FileTypeManager mgr = FileTypeManager.getInstance();
return image != null && mgr.getFileTypeByFile(image) == mgr.getFileTypeByExtension("png");
}
/**
* Name of class containing icons must end with {@code Icons}.
* <p>
* Valid icon paths:
* <ul>
* <li>AllIcons.IconFieldName (=com.intellij.icons.AllIcons)</li>
* <li>MyIcons.IconFieldName (implicitly in 'icons' package)</li>
* <li>MyIcons.InnerClass.IconFieldName ("")</li>
* </ul>
* Using FQN notation:
* <ul>
* <li>com.company.MyIcons.IconFieldName</li>
* <li>com.company.MyIcons.InnerClass.IconFieldName</li>
* </ul>
*/
@Nullable
private static PsiField resolveIconPath(@NonNls @Nullable String path, PsiElement element) {
if (path == null) return null;
@NonNls List<String> pathElements = StringUtil.split(path, ".");
if (pathElements.size() < 2) return null;
final int iconsClassNameIdx = ContainerUtil.lastIndexOf(pathElements, s -> s.endsWith(ICONS_CLASSNAME_SUFFIX));
if (iconsClassNameIdx == -1) return null;
Module module = ModuleUtilCore.findModuleForPsiElement(element);
if (module == null) return null;
PsiClass iconClass = findIconClass(module,
StringUtil.join(ContainerUtil.getFirstItems(pathElements, iconsClassNameIdx + 1), "."),
iconsClassNameIdx != 0);
if (iconClass == null) return null;
for (int i = iconsClassNameIdx + 1; i < pathElements.size() - 1; i++) {
iconClass = iconClass.findInnerClassByName(pathElements.get(i), false);
if (iconClass == null) return null;
}
return iconClass.findFieldByName(pathElements.get(pathElements.size() - 1), false);
}
@Nullable
private static PsiClass findIconClass(Module module, @NonNls @NotNull String iconClass, boolean isQualifiedFqn) {
final String adjustedIconClassFqn;
if (isQualifiedFqn) {
adjustedIconClassFqn = iconClass;
}
else {
adjustedIconClassFqn = ALL_ICONS_NAME.equals(iconClass) ? ALL_ICONS_FQN : ICONS_PACKAGE_PREFIX + iconClass;
}
GlobalSearchScope iconSearchScope = isQualifiedFqn ? GlobalSearchScope.moduleRuntimeScope(module, false) :
GlobalSearchScope.allScope(module.getProject());
return JavaPsiFacade.getInstance(module.getProject()).findClass(adjustedIconClassFqn, iconSearchScope);
}
private static abstract class IconPsiReferenceBase extends PsiReferenceBase<PsiElement> implements EmptyResolveMessageProvider {
IconPsiReferenceBase(@NotNull PsiElement element) {
super(element, true);
}
@Override
public Object @NotNull [] getVariants() {
Module module = ModuleUtilCore.findModuleForPsiElement(myElement);
if (module == null) return ArrayUtilRt.EMPTY_OBJECT_ARRAY;
final Project project = module.getProject();
final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
GlobalSearchScope productionScope = GlobalSearchScope.moduleRuntimeScope(module, false);
List<LookupElement> variants = new ArrayList<>();
// AllIcons
addIconVariants(variants, javaPsiFacade.findClass(ALL_ICONS_FQN, productionScope), false, Collections.emptyList());
// icons.*Icons
final PsiPackage iconsPackage = javaPsiFacade.findPackage("icons");
if (iconsPackage != null) {
for (PsiClass psiClass : iconsPackage.getClasses(productionScope)) {
final String className = psiClass.getName();
if (className == null || !StringUtil.endsWith(className, ICONS_CLASSNAME_SUFFIX)) continue;
addIconVariants(variants, psiClass, false, Collections.emptyList());
}
}
// FQN *Icons
GlobalSearchScope notIconsPackageScope =
iconsPackage != null ? PackageScope.packageScope(iconsPackage, false) : GlobalSearchScope.EMPTY_SCOPE;
final Query<PsiClass> allIconsSearch =
AllClassesSearch.search(productionScope.intersectWith(GlobalSearchScope.notScope(notIconsPackageScope)),
project, s -> StringUtil.endsWith(s, ICONS_CLASSNAME_SUFFIX) && !s.equals(ICONS_CLASSNAME_SUFFIX));
allIconsSearch.forEach(psiClass -> {
if (ALL_ICONS_FQN.equals(psiClass.getQualifiedName()) ||
psiClass.isInterface() ||
psiClass.getContainingClass() != null ||
!psiClass.hasModifier(JvmModifier.PUBLIC)) {
return;
}
addIconVariants(variants, psiClass, true, Collections.emptyList());
});
return variants.toArray();
}
private static void addIconVariants(List<LookupElement> variants,
@Nullable PsiClass iconClass,
boolean useFqn,
List<PsiClass> containingClasses) {
if (iconClass == null) return;
String classNamePrefix;
if (useFqn) {
classNamePrefix = containingClasses.isEmpty() ? iconClass.getQualifiedName() :
ContainerUtil.getLastItem(containingClasses).getQualifiedName() + "." + iconClass.getName();
}
else {
classNamePrefix = containingClasses.isEmpty() ? iconClass.getName() :
StringUtil.join(containingClasses, aClass -> aClass.getName(), ".") + "." + iconClass.getName();
}
for (PsiField field : iconClass.getFields()) {
if (!ProjectIconsAccessor.isIconClassType(field.getType())) continue;
String iconPath = classNamePrefix + "." + field.getName();
LookupElementBuilder builder = LookupElementBuilder.create(field, iconPath)
.withRenderer(IconPathLookupElementRenderer.INSTANCE);
variants.add(builder);
}
final List<PsiClass> parents = new SmartList<>(containingClasses);
parents.add(iconClass);
for (PsiClass innerClass : iconClass.getInnerClasses()) {
addIconVariants(variants, innerClass, useFqn, parents);
}
}
@SuppressWarnings("UnresolvedPropertyKey")
@NotNull
@Override
public String getUnresolvedMessagePattern() {
return DevKitBundle.message("inspections.presentation.cannot.resolve.icon");
}
private static class IconPathLookupElementRenderer extends LookupElementRenderer<LookupElement> {
private static final IconPathLookupElementRenderer INSTANCE = new IconPathLookupElementRenderer();
@Override
public void renderElement(LookupElement element, LookupElementPresentation presentation) {
final PsiField field = ObjectUtils.tryCast(element.getPsiElement(), PsiField.class);
assert field != null;
final String iconPath = element.getLookupString();
presentation.setItemText(iconPath);
presentation.setStrikeout(field.isDeprecated());
final Icon resolveIcon = resolveIcon(field, iconPath);
if (resolveIcon != null) {
if (ProjectIconsAccessor.hasProperSize(resolveIcon)) {
presentation.setIcon(resolveIcon);
}
else {
presentation.setTailText(" (" + resolveIcon.getIconWidth() + "x" + resolveIcon.getIconHeight() + ")", true);
}
}
}
@Nullable
private static Icon resolveIcon(PsiField field, @NotNull String iconPath) {
UField uField = UastContextKt.toUElement(field, UField.class);
assert uField != null;
UExpression expression = uField.getUastInitializer();
if (expression == null) {
return IconLoader.findIcon(iconPath, IconPsiReferenceBase.class, false, false);
}
ProjectIconsAccessor iconsAccessor = ProjectIconsAccessor.getInstance(field.getProject());
VirtualFile iconFile = iconsAccessor.resolveIconFile(expression);
return iconFile == null ? null : iconsAccessor.getIcon(iconFile);
}
}
}
}
| 43.546992 | 140 | 0.673587 |
65bd2ad6915fceff8c8e06302177a3a58fd84a9e | 4,903 | /*
* Copyright (c) 2010-2014. Axon Framework
*
* 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.axonframework.commandhandling.gateway;
import org.axonframework.commandhandling.CommandBus;
import org.axonframework.commandhandling.CommandCallback;
import org.axonframework.commandhandling.CommandMessage;
import org.axonframework.common.lock.DeadlockException;
import org.axonframework.messaging.unitofwork.CurrentUnitOfWork;
import java.util.ArrayList;
import java.util.List;
/**
* Callback implementation that will invoke a retry scheduler if a command results in a runtime exception.
* <p/>
* Generally, it is not necessary to use this class directly. It is used by CommandGateway implementations to support
* retrying of commands.
*
* @param <R> The type of return value expected by the callback
* @param <C> The type of payload of the dispatched command
* @author Allard Buijze
* @see DefaultCommandGateway
* @since 2.0
*/
public class RetryingCallback<C, R> implements CommandCallback<C, R> {
private final CommandCallback<C, R> delegate;
private final RetryScheduler retryScheduler;
private final CommandBus commandBus;
private final List<Class<? extends Throwable>[]> history;
/**
* Initialize the RetryingCallback with the given {@code delegate}, representing the actual callback passed as
* a parameter to dispatch, the given {@code commandMessage}, {@code retryScheduler} and
* {@code commandBus}.
*
* @param delegate The callback to invoke when the command succeeds, or when retries are rejected.
* @param retryScheduler The scheduler that decides if and when a retry should be scheduled
* @param commandBus The commandBus on which the command must be dispatched
*/
public RetryingCallback(CommandCallback<C, R> delegate,
RetryScheduler retryScheduler,
CommandBus commandBus) {
this.delegate = delegate;
this.retryScheduler = retryScheduler;
this.commandBus = commandBus;
this.history = new ArrayList<>();
}
@Override
public void onSuccess(CommandMessage<? extends C> commandMessage, R result) {
delegate.onSuccess(commandMessage, result);
}
@Override
public void onFailure(CommandMessage<? extends C> commandMessage, Throwable cause) {
history.add(simplify(cause));
try {
// we fail immediately when the exception is checked,
// or when it is a Deadlock Exception and we have an active unit of work
if (!(cause instanceof RuntimeException)
|| (isCausedBy(cause, DeadlockException.class) && CurrentUnitOfWork.isStarted())
|| !retryScheduler.scheduleRetry(commandMessage, (RuntimeException) cause,
new ArrayList<>(history),
new RetryDispatch(commandMessage))) {
delegate.onFailure(commandMessage, cause);
}
} catch (Exception e) {
delegate.onFailure(commandMessage, e);
}
}
private boolean isCausedBy(Throwable exception, Class<? extends Throwable> causeType) {
return causeType.isInstance(exception)
|| (exception.getCause() != null && isCausedBy(exception.getCause(), causeType));
}
@SuppressWarnings("unchecked")
private Class<? extends Throwable>[] simplify(Throwable cause) {
List<Class<? extends Throwable>> types = new ArrayList<>();
types.add(cause.getClass());
Throwable rootCause = cause;
while (rootCause.getCause() != null) {
rootCause = rootCause.getCause();
types.add(rootCause.getClass());
}
return types.toArray(new Class[0]);
}
private class RetryDispatch implements Runnable {
private final CommandMessage<? extends C> commandMessage;
private RetryDispatch(CommandMessage<? extends C> commandMessage) {
this.commandMessage = commandMessage;
}
@Override
public void run() {
try {
commandBus.dispatch(commandMessage, RetryingCallback.this);
} catch (Exception e) {
RetryingCallback.this.onFailure(commandMessage, e);
}
}
}
}
| 39.861789 | 117 | 0.664287 |
2d85107566f27783cd2462d5c3b8e0487274a01b | 2,114 | package softuni.angular.services.impl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.modelmapper.ModelMapper;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import softuni.angular.exception.GlobalServiceException;
import softuni.angular.repositories.NInsObjectTypeRepository;
import softuni.angular.services.NInsObjectTypeService;
import softuni.angular.data.views.nomenclature.NomenclatureOutView;
import java.util.List;
import java.util.stream.Collectors;
/**
* Project: backend
* Created by: GKirilov
* On: 11/8/2021
*/
@Service
public class NInsObjectTypeServiceImpl implements NInsObjectTypeService {
private final Logger logger = LogManager.getLogger(this.getClass());
private final ModelMapper modelMapper;
private final NInsObjectTypeRepository nInsObjectTypeRepository;
public NInsObjectTypeServiceImpl(ModelMapper modelMapper,
NInsObjectTypeRepository nInsObjectTypeRepository) {
this.modelMapper = modelMapper;
this.nInsObjectTypeRepository = nInsObjectTypeRepository;
}
@Override
public List<NomenclatureOutView> getAll() throws GlobalServiceException {
UserDetailsImpl currentUser =
(UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String logId = currentUser.getRequestId();
try {
logger.info(String.format("%s: Start getAll service", logId));
return this.nInsObjectTypeRepository.findAll()
.stream()
.map(e -> this.modelMapper.map(e, NomenclatureOutView.class))
.collect(Collectors.toList());
} catch (Exception exc) {
logger.error(String.format("%s: Unexpected error: %s", logId, exc.getMessage()));
throw new GlobalServiceException("Грешка при работа с базата данни!", exc);
} finally {
logger.info(String.format("%s: Finished getAll service", logId));
}
}
}
| 40.653846 | 104 | 0.71334 |
7f2bbc538c436d45997ff7265d8140e4711cb302 | 124 | package com.faforever.commons.api.dto;
public enum ModerationReportStatus {
AWAITING, PROCESSING, COMPLETED, DISCARDED
}
| 20.666667 | 44 | 0.806452 |
49091047235d5267c67a73888c442ed36cd866c8 | 5,045 | package io.github.vampirestudios.gadget.programs.system.layout;
import io.github.vampirestudios.gadget.api.AppInfo;
import io.github.vampirestudios.gadget.api.ApplicationManager;
import io.github.vampirestudios.gadget.api.app.Dialog;
import io.github.vampirestudios.gadget.api.app.Layout;
import io.github.vampirestudios.gadget.api.app.component.Button;
import io.github.vampirestudios.gadget.api.app.component.ItemList;
import io.github.vampirestudios.gadget.api.app.component.TextField;
import io.github.vampirestudios.gadget.api.app.emojie_packs.Icons;
import io.github.vampirestudios.gadget.api.app.renderer.ListItemRenderer;
import io.github.vampirestudios.gadget.api.utils.RenderUtil;
import io.github.vampirestudios.gadget.programs.system.ApplicationAppStore;
import io.github.vampirestudios.gadget.programs.system.object.LocalAppEntry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.text.TextFormatting;
import org.apache.commons.lang3.StringUtils;
import java.awt.*;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class LayoutSearchApps extends StandardLayout {
private static final Color ITEM_BACKGROUND = Color.decode("0x9E9E9E");
private static final Color ITEM_SELECTED = Color.decode("0x757575");
private long lastClick = 0;
private ApplicationAppStore appStore;
public LayoutSearchApps(ApplicationAppStore appStore, Layout previous)
{
super("Search", ApplicationAppStore.LAYOUT_WIDTH, ApplicationAppStore.LAYOUT_HEIGHT, appStore, previous);
this.appStore = appStore;
}
@Override
public void init()
{
super.init();
ItemList<AppInfo> itemListResults = new ItemList<>(5, 48, ApplicationAppStore.LAYOUT_WIDTH - 10, 5, true);
itemListResults.setItems(ApplicationManager.getAllApplications());
itemListResults.sortBy(AppInfo.SORT_NAME);
itemListResults.setListItemRenderer(new ListItemRenderer<AppInfo>(18)
{
@Override
public void render(AppInfo info, Gui gui, Minecraft mc, int x, int y, int width, int height, boolean selected)
{
Gui.drawRect(x, y, x + width, y + height, selected ? ITEM_SELECTED.getRGB() : ITEM_BACKGROUND.getRGB());
GlStateManager.color(1.0F, 1.0F, 1.0F);
RenderUtil.drawApplicationIcon(info, x + 2, y + 2);
RenderUtil.drawStringClipped(info.getName() + TextFormatting.GRAY + " - " + TextFormatting.DARK_GRAY + info.getDescription(), x + 20, y + 5, itemListResults.getWidth() - 22, Color.WHITE.getRGB(), false);
}
});
itemListResults.setItemClickListener((info, index, mouseButton) ->
{
if(mouseButton == 0)
{
if(System.currentTimeMillis() - this.lastClick <= 200)
{
openApplication(info);
}
else
{
this.lastClick = System.currentTimeMillis();
}
}
});
this.addComponent(itemListResults);
TextField textFieldSearch = new TextField(5, 26, ApplicationAppStore.LAYOUT_WIDTH - 10);
textFieldSearch.setIcon(Icons.SEARCH);
textFieldSearch.setPlaceholder("...");
textFieldSearch.setKeyListener(c ->
{
Predicate<AppInfo> FILTERED = info -> StringUtils.containsIgnoreCase(info.getName(), textFieldSearch.getText()) || StringUtils.containsIgnoreCase(info.getDescription(), textFieldSearch.getText());
List<AppInfo> filteredItems = ApplicationManager.getAvailableApplications().stream().filter(FILTERED).collect(Collectors.toList());
itemListResults.setItems(filteredItems);
return false;
});
this.addComponent(textFieldSearch);
}
private void openApplication(AppInfo info)
{
Layout layout = new LayoutAppPage(appStore.getLaptop(), new LocalAppEntry(info), appStore);
app.setCurrentLayout(layout);
Button btnPrevious = new Button(2, 2, Icons.ARROW_LEFT);
btnPrevious.setClickListener((mouseX1, mouseY1, mouseButton1) -> app.setCurrentLayout(this));
if(info.hasContributors()){
String contrbstr = "Contributors";
Button contribbutton = new Button(this.width - Minecraft.getMinecraft().fontRenderer.getStringWidth(contrbstr) + 3, 10, contrbstr);
contribbutton.setClickListener((x, y, b)->{
StringBuilder sb = new StringBuilder();
for(String c : info.getContributors()){
sb.append(c);
sb.append("\n");
}
Dialog.Message message = new Dialog.Message(sb.toString());
app.openDialog(message);
});
layout.addComponent(contribbutton);
}
layout.addComponent(btnPrevious);
}
} | 44.254386 | 219 | 0.672547 |
9920fefac7ef5b5c6b3b7dda8f00a3e7f88aa417 | 446 | package io.freefair.gradle.plugins;
import lombok.Data;
import org.gradle.api.Project;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import javax.inject.Inject;
@Data
public class AspectJExtension {
private final Property<String> version;
@Inject
public AspectJExtension(ObjectFactory objectFactory) {
this.version = objectFactory.property(String.class).convention("1.9.2");
}
}
| 22.3 | 80 | 0.757848 |
55bcd26c27a023109109bdfff48ee468a76f182b | 12,732 | /**
* 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.atlas.model.typedef;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.Serializable;
import java.util.*;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import org.apache.atlas.model.PList;
import org.apache.atlas.model.SearchFilter.SortType;
import org.apache.atlas.model.TypeCategory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.hadoop.util.StringUtils;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
/**
* class that captures details of an enum-type.
*/
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class AtlasEnumDef extends AtlasBaseTypeDef implements Serializable {
private static final long serialVersionUID = 1L;
private List<AtlasEnumElementDef> elementDefs;
private String defaultValue;
public AtlasEnumDef() {
this(null, null, null, null, null, null);
}
public AtlasEnumDef(String name) {
this(name, null, null, null, null, null);
}
public AtlasEnumDef(String name, String description) {
this(name, description, null, null, null, null);
}
public AtlasEnumDef(String name, String description, String typeVersion) {
this(name, description, typeVersion, null, null, null);
}
public AtlasEnumDef(String name, String description, List<AtlasEnumElementDef> elementDefs) {
this(name, description, null, elementDefs, null, null);
}
public AtlasEnumDef(String name, String description, String typeVersion, List<AtlasEnumElementDef> elementDefs) {
this(name, description, typeVersion, elementDefs, null, null);
}
public AtlasEnumDef(String name, String description, String typeVersion, List<AtlasEnumElementDef> elementDefs,
String defaultValue) {
this(name, description, typeVersion, elementDefs, defaultValue, null);
}
public AtlasEnumDef(String name, String description, String typeVersion, List<AtlasEnumElementDef> elementDefs,
String defaultValue, Map<String, String> options) {
this(name, description, typeVersion, elementDefs, defaultValue, null, options);
}
public AtlasEnumDef(String name, String description, String typeVersion, List<AtlasEnumElementDef> elementDefs,
String defaultValue, String serviceType, Map<String, String> options) {
super(TypeCategory.ENUM, name, description, typeVersion, serviceType, options);
setElementDefs(elementDefs);
setDefaultValue(defaultValue);
}
public AtlasEnumDef(AtlasEnumDef other) {
super(other);
if (other != null) {
setElementDefs(other.getElementDefs());
setDefaultValue(other.getDefaultValue());
}
}
public List<AtlasEnumElementDef> getElementDefs() {
return elementDefs;
}
public void setElementDefs(List<AtlasEnumElementDef> elementDefs) {
if (elementDefs != null && this.elementDefs == elementDefs) {
return;
}
if (CollectionUtils.isEmpty(elementDefs)) {
this.elementDefs = new ArrayList<>();
} else {
// if multiple elements with same value are present, keep only the last entry
List<AtlasEnumElementDef> tmpList = new ArrayList<>(elementDefs.size());
Set<String> elementValues = new HashSet<>();
ListIterator<AtlasEnumElementDef> iter = elementDefs.listIterator(elementDefs.size());
while (iter.hasPrevious()) {
AtlasEnumElementDef elementDef = iter.previous();
String elementValue = elementDef != null ? elementDef.getValue() : null;
if (elementValue != null) {
elementValue = elementValue.toLowerCase();
if (!elementValues.contains(elementValue)) {
tmpList.add(new AtlasEnumElementDef(elementDef));
elementValues.add(elementValue);
}
}
}
Collections.reverse(tmpList);
this.elementDefs = tmpList;
}
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String value) {
this.defaultValue = value;
}
public AtlasEnumElementDef getElement(String elemValue) {
return findElement(this.elementDefs, elemValue);
}
public void addElement(AtlasEnumElementDef elementDef) {
List<AtlasEnumElementDef> e = this.elementDefs;
List<AtlasEnumElementDef> tmpList = new ArrayList<>();
if (CollectionUtils.isNotEmpty(e)) {
// copy existing elements, except ones having same value as the element being added
for (AtlasEnumElementDef existingElem : e) {
if (!StringUtils.equalsIgnoreCase(existingElem.getValue(), elementDef.getValue())) {
tmpList.add(existingElem);
}
}
}
tmpList.add(new AtlasEnumElementDef(elementDef));
this.elementDefs = tmpList;
}
public void removeElement(String elemValue) {
List<AtlasEnumElementDef> e = this.elementDefs;
// if element doesn't exist, no need to create the tmpList below
if (hasElement(e, elemValue)) {
List<AtlasEnumElementDef> tmpList = new ArrayList<>();
// copy existing elements, except ones having same value as the element being removed
for (AtlasEnumElementDef existingElem : e) {
if (!StringUtils.equalsIgnoreCase(existingElem.getValue(), elemValue)) {
tmpList.add(existingElem);
}
}
this.elementDefs = tmpList;
}
}
public boolean hasElement(String elemValue) {
return getElement(elemValue) != null;
}
private static boolean hasElement(List<AtlasEnumElementDef> elementDefs, String elemValue) {
return findElement(elementDefs, elemValue) != null;
}
private static AtlasEnumElementDef findElement(List<AtlasEnumElementDef> elementDefs, String elemValue) {
AtlasEnumElementDef ret = null;
if (CollectionUtils.isNotEmpty(elementDefs)) {
for (AtlasEnumElementDef elementDef : elementDefs) {
if (StringUtils.equalsIgnoreCase(elementDef.getValue(), elemValue)) {
ret = elementDef;
break;
}
}
}
return ret;
}
@Override
public StringBuilder toString(StringBuilder sb) {
if (sb == null) {
sb = new StringBuilder();
}
sb.append("AtlasEnumDef{");
super.toString(sb);
sb.append(", elementDefs=[");
dumpObjects(elementDefs, sb);
sb.append("]");
sb.append(", defaultValue {");
sb.append(defaultValue);
sb.append('}');
sb.append('}');
return sb;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
AtlasEnumDef that = (AtlasEnumDef) o;
return Objects.equals(elementDefs, that.elementDefs) &&
Objects.equals(defaultValue, that.defaultValue);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), elementDefs, defaultValue);
}
@Override
public String toString() {
return toString(new StringBuilder()).toString();
}
/**
* class that captures details of an enum-element.
*/
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public static class AtlasEnumElementDef implements Serializable {
private static final long serialVersionUID = 1L;
private String value;
private String description;
private Integer ordinal;
public AtlasEnumElementDef() {
this(null, null, null);
}
public AtlasEnumElementDef(String value, String description, Integer ordinal) {
setValue(value);
setDescription(description);
setOrdinal(ordinal);
}
public AtlasEnumElementDef(AtlasEnumElementDef other) {
if (other != null) {
setValue(other.getValue());
setDescription(other.getDescription());
setOrdinal(other.getOrdinal());
}
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getOrdinal() {
return ordinal;
}
public void setOrdinal(Integer ordinal) {
this.ordinal = ordinal;
}
public StringBuilder toString(StringBuilder sb) {
if (sb == null) {
sb = new StringBuilder();
}
sb.append("AtlasEnumElementDef{");
sb.append("value='").append(value).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", ordinal=").append(ordinal);
sb.append('}');
return sb;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AtlasEnumElementDef that = (AtlasEnumElementDef) o;
return Objects.equals(value, that.value) &&
Objects.equals(description, that.description) &&
Objects.equals(ordinal, that.ordinal);
}
@Override
public int hashCode() {
return Objects.hash(value, description, ordinal);
}
@Override
public String toString() {
return toString(new StringBuilder()).toString();
}
}
/**
* REST serialization friendly list.
*/
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlSeeAlso(AtlasEnumDef.class)
public static class AtlasEnumDefs extends PList<AtlasEnumDef> {
private static final long serialVersionUID = 1L;
public AtlasEnumDefs() {
super();
}
public AtlasEnumDefs(List<AtlasEnumDef> list) {
super(list);
}
public AtlasEnumDefs(List list, long startIndex, int pageSize, long totalCount,
SortType sortType, String sortBy) {
super(list, startIndex, pageSize, totalCount, sortType, sortBy);
}
}
}
| 34.134048 | 117 | 0.636192 |
5ffe2e551583a16bddcd4ae42a7bbd015b1555bf | 567 | package com.cloud.tao.callback;
import android.view.View;
/**
* 防止过快多次点击
* Created by zeda on 16/3/2.
*/
public abstract class NoDoubleClickListener implements View.OnClickListener {
private static final long CLICK_SPACE = 500 ;
private long lastClickTime = 0;
@Override
public synchronized void onClick(View v) {
long time = System.currentTimeMillis();
if (time - lastClickTime < CLICK_SPACE)
return;
lastClickTime = time;
noDoubleClick(v);
}
public abstract void noDoubleClick(View v);
}
| 21.807692 | 77 | 0.670194 |
34ed9d9968618f7d67dd49b95666e74d0c1eebb2 | 356 | package softuni.heroes.services.models.heroes;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import softuni.heroes.data.models.enums.Gender;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class HeroCreateServiceModel {
private String name;
private Gender gender;
}
| 19.777778 | 47 | 0.817416 |
ec0553b86894da89c5b51b8038b39ce9a29de4f5 | 740 | package visualfamilyclassifier;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class VisualFamilyClassifier extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
// Definição do XML da janela
Parent root = FXMLLoader.load(getClass().getResource("view/VisualClassifier.fxml"));
// Inicializando a Scene
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| 25.517241 | 92 | 0.672973 |
30c86c3afb7ab9d1faa63e34f2c6503dfc0af495 | 933 | package com.nukkitx.protocol.genoa.v425.serializer;
import com.nukkitx.protocol.bedrock.BedrockPacketHelper;
import com.nukkitx.protocol.bedrock.BedrockPacketSerializer;
import com.nukkitx.protocol.genoa.packet.GenoaEventFlatbufferPacket;
import io.netty.buffer.ByteBuf;
import java.util.UUID;
public class GenoaEventFlatbufferPacketSerializer implements BedrockPacketSerializer<GenoaEventFlatbufferPacket> {
public static final GenoaEventFlatbufferPacketSerializer INSTANCE = new GenoaEventFlatbufferPacketSerializer();
@Override
public void serialize(ByteBuf buffer, BedrockPacketHelper helper, GenoaEventFlatbufferPacket packet) {
// TODO: Array
//helper.writeByteArray(buffer,packet.getByteArr());
}
@Override
public void deserialize(ByteBuf buffer, BedrockPacketHelper helper, GenoaEventFlatbufferPacket packet) {
//packet.setByteArr(helper.readByteArray(buffer));
}
}
| 35.884615 | 115 | 0.800643 |
7338523b3f4d57a2c73deae2ef5156cc2d0c922a | 928 | package br.com.pict.model;
import java.util.Date;
/**
*
* @author Iarley
*/
public class Logs {
// ============== Campos =================
private Integer id;
private Date dataEntrada;
private Date dataSaida;
// ================ Relações 1 para N =======================
private Pessoa pessoa;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDataEntrada() {
return dataEntrada;
}
public void setDataEntrada(Date dataEntrada) {
this.dataEntrada = dataEntrada;
}
public Date getDataSaida() {
return dataSaida;
}
public void setDataSaida(Date dataSaida) {
this.dataSaida = dataSaida;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
}
| 17.509434 | 61 | 0.539871 |
8c523e20c196b02b5721d51bfbb75787775db6e5 | 2,908 | package seedu.address.storage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.note.Content;
import seedu.address.model.note.Note;
import seedu.address.model.note.Title;
import seedu.address.model.tag.Tag;
/**
* Jackson-friendly version of {@link Note}.
*/
class JsonAdaptedNote {
public static final String MISSING_FIELD_MESSAGE_FORMAT = "Note's %s field is missing!";
private final String title;
private final String content;
private final List<JsonAdaptedTag> tagged = new ArrayList<>();
/**
* Constructs a {@code JsonAdaptedNote} with the given person details.
*/
@JsonCreator
public JsonAdaptedNote(@JsonProperty("title") String title, @JsonProperty("content") String content,
@JsonProperty("tagged") List<JsonAdaptedTag> tagged) {
this.title = title;
this.content = content;
if (tagged != null) {
this.tagged.addAll(tagged);
}
}
/**
* Converts a given {@code Note} into this class for Jackson use.
*/
public JsonAdaptedNote(Note source) {
title = source.getTitle().fullTitle;
content = source.getContent().fullContent;
tagged.addAll(source.getTags().stream()
.map(JsonAdaptedTag::new)
.collect(Collectors.toList()));
}
/**
* Converts this Jackson-friendly adapted note object into the model's {@code Note} object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted note.
*/
public Note toModelType() throws IllegalValueException {
final List<Tag> noteTags = new ArrayList<>();
for (JsonAdaptedTag tag : tagged) {
noteTags.add(tag.toModelType());
}
if (title == null) {
throw new IllegalValueException(
String.format(MISSING_FIELD_MESSAGE_FORMAT, Title.class.getSimpleName()));
}
if (!Title.isValidTitle(title)) {
throw new IllegalValueException(Title.MESSAGE_CONSTRAINTS);
}
final Title modelTitle = new Title(title);
if (content == null) {
throw new IllegalValueException(
String.format(MISSING_FIELD_MESSAGE_FORMAT, Content.class.getSimpleName()));
}
if (!Content.isValidContent(content)) {
throw new IllegalValueException(Content.MESSAGE_CONSTRAINTS);
}
final Content modelContent = new Content(content);
final Set<Tag> modelTags = new HashSet<>(noteTags);
return new Note(modelTitle, modelContent, modelTags);
}
}
| 33.425287 | 104 | 0.656465 |
d218b8bcf89eb9c1f7348bf04acef7cc6531634e | 6,413 | package ezvcard.property;
import static ezvcard.property.PropertySensei.assertCopy;
import static ezvcard.property.PropertySensei.assertEqualsMethod;
import static ezvcard.property.PropertySensei.assertNothingIsEqual;
import static ezvcard.property.PropertySensei.assertValidate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import ezvcard.VCardVersion;
import ezvcard.parameter.TelephoneType;
import ezvcard.util.TelUri;
/*
Copyright (c) 2012-2020, Michael Angstadt
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
/**
* @author Michael Angstadt
*/
public class TelephoneTest {
@Test
public void constructors() throws Exception {
Telephone property = new Telephone((String) null);
assertNull(property.getText());
assertNull(property.getUri());
assertEquals(Arrays.asList(), property.getTypes());
property = new Telephone("text");
assertEquals("text", property.getText());
assertNull(property.getUri());
assertEquals(Arrays.asList(), property.getTypes());
property = new Telephone(new TelUri.Builder("+1").build());
assertNull(property.getText());
assertEquals(new TelUri.Builder("+1").build(), property.getUri());
assertEquals(Arrays.asList(), property.getTypes());
}
@Test
public void set_value() {
Telephone property = new Telephone((String) null);
property.setText("text");
assertEquals("text", property.getText());
assertNull(property.getUri());
assertEquals(Arrays.asList(), property.getTypes());
property.setUri(new TelUri.Builder("+1").build());
assertNull(property.getText());
assertEquals(new TelUri.Builder("+1").build(), property.getUri());
assertEquals(Arrays.asList(), property.getTypes());
property.setText("text");
assertEquals("text", property.getText());
assertNull(property.getUri());
assertEquals(Arrays.asList(), property.getTypes());
property.getTypes().add(TelephoneType.WORK);
assertEquals("text", property.getText());
assertNull(property.getUri());
assertEquals(Arrays.asList(TelephoneType.WORK), property.getTypes());
property.getTypes().add(TelephoneType.HOME);
assertEquals("text", property.getText());
assertNull(property.getUri());
assertEquals(Arrays.asList(TelephoneType.WORK, TelephoneType.HOME), property.getTypes());
property.getTypes().remove(TelephoneType.HOME);
assertEquals("text", property.getText());
assertNull(property.getUri());
assertEquals(Arrays.asList(TelephoneType.WORK), property.getTypes());
}
@Test
public void validate() {
Telephone empty = new Telephone((String) null);
assertValidate(empty).run(8);
Telephone withText = new Telephone("(800) 555-5555");
assertValidate(withText).run();
Telephone withUri = new Telephone(new TelUri.Builder("+1-800-555-5555").extension("101").build());
assertValidate(withUri).versions(VCardVersion.V2_1).run(19);
assertValidate(withUri).versions(VCardVersion.V3_0).run(19);
assertValidate(withUri).versions(VCardVersion.V4_0).run();
Telephone withTypes = new Telephone("(800) 555-5555");
withTypes.getTypes().add(TelephoneType.TEXTPHONE);
withTypes.getTypes().add(TelephoneType.PREF);
assertValidate(withTypes).versions(VCardVersion.V2_1, VCardVersion.V3_0).run(9);
assertValidate(withTypes).versions(VCardVersion.V4_0).run();
}
@Test
public void toStringValues() {
Telephone property = new Telephone("text");
assertFalse(property.toStringValues().isEmpty());
}
@Test
public void copy() {
Telephone original = new Telephone((String) null);
assertCopy(original);
original = new Telephone("text");
assertCopy(original);
original = new Telephone(new TelUri.Builder("+1").build());
assertCopy(original);
original = new Telephone("text");
original.getTypes().add(TelephoneType.HOME);
assertCopy(original);
}
@Test
public void equals() {
List<VCardProperty> properties = new ArrayList<VCardProperty>();
Telephone property = new Telephone((String) null);
properties.add(property);
property = new Telephone("text");
properties.add(property);
property = new Telephone("text");
property.getTypes().add(TelephoneType.HOME);
properties.add(property);
property = new Telephone("text2");
properties.add(property);
property = new Telephone(new TelUri.Builder("+1").build());
properties.add(property);
property = new Telephone(new TelUri.Builder("+1").build());
property.getTypes().add(TelephoneType.HOME);
properties.add(property);
property = new Telephone(new TelUri.Builder("+2").build());
properties.add(property);
assertNothingIsEqual(properties);
//@formatter:off
assertEqualsMethod(Telephone.class, "text")
.constructor(new Class<?>[]{String.class}, (String)null).test()
.constructor("text").test()
.constructor(new TelUri.Builder("+1").build()).test();
//@formatter:on
}
}
| 34.478495 | 100 | 0.752534 |
c91cc3d1d02329d3af99a7535acd39359cb9debe | 2,090 | package com.cloud.api.command.admin.vm;
import com.cloud.api.APICommand;
import com.cloud.api.APICommandGroup;
import com.cloud.api.ApiErrorCode;
import com.cloud.api.ResponseObject.ResponseView;
import com.cloud.api.ServerApiException;
import com.cloud.api.command.user.vm.RestoreVMCmd;
import com.cloud.api.response.UserVmResponse;
import com.cloud.context.CallContext;
import com.cloud.legacymodel.exceptions.ConcurrentOperationException;
import com.cloud.legacymodel.exceptions.InsufficientCapacityException;
import com.cloud.legacymodel.exceptions.ResourceAllocationException;
import com.cloud.legacymodel.exceptions.ResourceUnavailableException;
import com.cloud.legacymodel.vm.VirtualMachine;
import com.cloud.uservm.UserVm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@APICommand(name = "restoreVirtualMachine", group = APICommandGroup.VirtualMachineService, description = "Restore a VM to original template/ISO or new template/ISO", responseObject = UserVmResponse
.class, since = "3.0.0",
responseView = ResponseView.Full, entityType = {VirtualMachine.class},
requestHasSensitiveInfo = false,
responseHasSensitiveInfo = true)
public class RestoreVMCmdByAdmin extends RestoreVMCmd {
public static final Logger s_logger = LoggerFactory.getLogger(RestoreVMCmdByAdmin.class);
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException {
final UserVm result;
CallContext.current().setEventDetails("Vm Id: " + getVmId());
result = _userVmService.restoreVM(this);
if (result != null) {
final UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", result).get(0);
response.setResponseName(getCommandName());
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to restore vm " + getVmId());
}
}
}
| 47.5 | 197 | 0.767943 |
08ac45fd8f6675fc9c3abd010b5e41227e7317c2 | 3,891 | /*
* 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.knox.gateway.websockets;
import java.io.IOException;
import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import org.eclipse.jetty.util.BlockingArrayQueue;
/**
* A Test websocket client
*
*/
@ClientEndpoint
public class WebsocketClient {
private Session session = null;
public CloseReason close = null;
public MessageQueue messageQueue = new MessageQueue();
public LinkedList<Throwable> errors = new LinkedList<>();
public CountDownLatch closeLatch = new CountDownLatch(1);
public boolean onError = false;
public String errorMessage = null;
@OnClose
public void onWebSocketClose(CloseReason reason) {
this.close = reason;
closeLatch.countDown();
}
@OnMessage
public void onMessage(String message) {
this.messageQueue.offer(message);
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
}
@OnError
public void onError(Session session, Throwable thr) {
errors.add(thr);
this.onError = true;
this.errorMessage = thr.toString();
}
public void sendText(String text) throws IOException {
if (session != null) {
session.getBasicRemote().sendText(text);
}
}
/**
* Check whether we have expected close code
*
* @param expectedCloseCode code to expect on close
* @param timeoutDuration duration to wait
* @param timeoutUnit duration unit
* @throws TimeoutException if waiting too long to close
*/
public void awaitClose(int expectedCloseCode, int timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException {
long msDur = TimeUnit.MILLISECONDS.convert(timeoutDuration, timeoutUnit);
long now = System.currentTimeMillis();
long expireOn = now + msDur;
while (close == null) {
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException ignore) {
/* ignore */
}
if ((System.currentTimeMillis() > expireOn)) {
throw new TimeoutException("Timed out reading message from queue");
}
}
}
public class MessageQueue extends BlockingArrayQueue<String> {
public void awaitMessages(int expectedMessageCount, int timeoutDuration,
TimeUnit timeoutUnit) throws TimeoutException {
long msDur = TimeUnit.MILLISECONDS.convert(timeoutDuration, timeoutUnit);
long now = System.currentTimeMillis();
long expireOn = now + msDur;
while (this.size() < expectedMessageCount) {
try {
TimeUnit.MILLISECONDS.sleep(20);
} catch (InterruptedException ignore) {
/* ignore */
}
if ((System.currentTimeMillis() > expireOn)) {
throw new TimeoutException("Timed out reading message from queue");
}
}
}
}
}
| 29.477273 | 90 | 0.711899 |
38233cbdc8c543efdc24c868c9f46229d3451cef | 1,934 | package py.com.volpe.cotizacion;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
@EnableScheduling
@EnableCaching
@EnableWebMvc
public class Cotizacion {
public static void main(String[] args) {
SpringApplication.run(Cotizacion.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/index.html")
.resourceChain(false);
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/public/");
}
}
};
}
@Bean
@Profile("production")
public TaskScheduler taskScheduler() {
return new ConcurrentTaskScheduler();
}
}
| 36.490566 | 118 | 0.713547 |
1b80951784c867ec8a5b4bd81f3746772f9a7f8b | 3,182 | /*
* Copyright 2017-2022 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.micronaut.tracing.opentelemetry.instrument.http.client;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.http.annotation.Filter;
import io.micronaut.http.filter.ClientFilterChain;
import io.micronaut.http.filter.HttpClientFilter;
import io.micronaut.tracing.opentelemetry.instrument.http.AbstractOpenTelemetryFilter;
import io.micronaut.tracing.opentelemetry.instrument.util.OpenTelemetryExclusionsConfiguration;
import io.micronaut.tracing.opentelemetry.instrument.util.OpenTelemetryPublisherUtils;
import io.opentelemetry.context.Context;
import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter;
import jakarta.inject.Named;
import org.reactivestreams.Publisher;
import static io.micronaut.tracing.opentelemetry.instrument.http.client.OpenTelemetryClientFilter.CLIENT_PATH;
/**
* An HTTP client instrumentation filter that uses Open Telemetry.
*
* @author Nemanja Mikic
* @since 4.1.0
*/
@Filter(CLIENT_PATH)
public class OpenTelemetryClientFilter extends AbstractOpenTelemetryFilter implements HttpClientFilter {
private final Instrumenter<MutableHttpRequest<?>, Object> instrumenter;
/**
* Initialize the open tracing client filter with tracer and exclusion configuration.
*
* @param exclusionsConfig The {@link OpenTelemetryExclusionsConfiguration}
* @param instrumenter The {@link OpenTelemetryHttpClientConfig}
*/
public OpenTelemetryClientFilter(@Nullable OpenTelemetryExclusionsConfiguration exclusionsConfig, @Named("micronautHttpClientTelemetryInstrumenter") Instrumenter<MutableHttpRequest<?>, Object> instrumenter) {
super(exclusionsConfig == null ? null : exclusionsConfig.exclusionTest());
this.instrumenter = instrumenter;
}
@Override
public Publisher<? extends HttpResponse<?>> doFilter(MutableHttpRequest<?> request,
ClientFilterChain chain) {
Publisher<? extends HttpResponse<?>> requestPublisher = chain.proceed(request);
if (shouldExclude(request.getPath())) {
return requestPublisher;
}
Context parentContext = Context.current();
if (!instrumenter.shouldStart(parentContext, request)) {
return requestPublisher;
}
Context newContext = instrumenter.start(parentContext, request);
return OpenTelemetryPublisherUtils.createOpenTelemetryPublisher(requestPublisher, instrumenter, newContext, request);
}
}
| 41.324675 | 212 | 0.761157 |
22c4790e249a82674def474cac7e355fc9c18ea7 | 1,738 | package cn.ucloud.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @description: java model 工具
* @author: codezhang
* @date: 2018-09-17 16:06
**/
public class GetAndSetUtil {
private static Logger logger = LoggerFactory.getLogger(GetAndSetUtil.class.getName());
/**
* java反射bean的get方法
*
* @param objectClass
* @param fieldName
* @return
*/
@SuppressWarnings("unchecked")
public static Method getGetMethod(Class objectClass, String fieldName) {
StringBuilder sb = new StringBuilder();
sb.append("get");
sb.append(fieldName.substring(0, 1).toUpperCase());
sb.append(fieldName.substring(1));
try {
return objectClass.getMethod(sb.toString());
} catch (Exception e) {
logger.error(e.getMessage());
}
return null;
}
/**
* java反射bean的set方法
*
* @param objectClass
* @param fieldName
* @return
*/
@SuppressWarnings("unchecked")
public static Method getSetMethod(Class objectClass, String fieldName) {
try {
Class[] parameterTypes = new Class[1];
Field field = objectClass.getDeclaredField(fieldName);
parameterTypes[0] = field.getType();
StringBuilder sb = new StringBuilder();
sb.append("set");
sb.append(fieldName.substring(0, 1).toUpperCase());
sb.append(fieldName.substring(1));
return objectClass.getMethod(sb.toString(), parameterTypes);
} catch (Exception e) {
logger.error(e.getMessage());
}
return null;
}
}
| 26.333333 | 90 | 0.605869 |
91c8bceef6acc5719a3b5b53c7bb88a0ac3c0038 | 3,964 | /*
* Copyright 2018 Murat Artim (muratartim@gmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package write;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import analysis.Structure;
import element.*;
/**
* Class for writing element information to output file.
*
* @author Murat
*
*/
public class ElementInfo extends Writer {
/** Buffered writer. */
private BufferedWriter bwriter_;
/**
* Writes element information to output file.
*
* @param structure
* The structure to be printed.
* @param output
* The output file.
*/
protected void write(Structure structure, File output) {
try {
// create file writer with appending option
FileWriter writer = new FileWriter(output, true);
// create buffered writer
bwriter_ = new BufferedWriter(writer);
// write tables
writeTable1(structure);
writeTable2(structure);
// close writer
bwriter_.close();
}
// exception occured
catch (Exception excep) {
exceptionHandler("Exception occured during writing output file!");
}
}
/**
* Writes table part 1.
*
*/
private void writeTable1(Structure structure) {
try {
// pass to new line
bwriter_.newLine();
// write header for first part of table
bwriter_.write(header("Element Information, 1"));
// pass two lines
bwriter_.newLine();
bwriter_.newLine();
// write headers
String[] table = { "Element", "Type", "Volume", "Mass", "Weight" };
bwriter_.write(table(table));
// pass two lines
bwriter_.newLine();
bwriter_.newLine();
// write element info
for (int i = 0; i < structure.getNumberOfElements(); i++) {
// get element
Element e = structure.getElement(i);
// get properties
table[0] = Integer.toString(i);
table[1] = Integer.toString(e.getType());
table[2] = formatter(e.getVolume());
table[3] = formatter(e.getMass());
table[4] = formatter(e.getWeight());
// write
bwriter_.write(table(table));
bwriter_.newLine();
}
}
// exception occured
catch (Exception excep) {
exceptionHandler("Exception occured during writing output file!");
}
}
/**
* Writes table part 2.
*
*/
private void writeTable2(Structure structure) {
try {
// pass to new line
bwriter_.newLine();
// write header for first part of table
bwriter_.write(header("Element Information, 2"));
// pass two lines
bwriter_.newLine();
bwriter_.newLine();
// write headers
String[] table = { "Element", "Length", "Area" };
bwriter_.write(table(table));
// pass two lines
bwriter_.newLine();
bwriter_.newLine();
// write element info
for (int i = 0; i < structure.getNumberOfElements(); i++) {
// get element
Element e = structure.getElement(i);
// get properties
table[0] = Integer.toString(i);
if (e.getDimension() == ElementLibrary.oneDimensional_) {
Element1D e1D = (Element1D) e;
table[1] = formatter(e1D.getLength());
} else
table[1] = " ";
if (e.getDimension() == ElementLibrary.twoDimensional_) {
Element2D e2D = (Element2D) e;
table[2] = formatter(e2D.getArea());
} else
table[2] = " ";
// write
bwriter_.write(table(table));
bwriter_.newLine();
}
}
// exception occured
catch (Exception excep) {
exceptionHandler("Exception occured during writing output file!");
}
}
}
| 22.39548 | 75 | 0.650605 |
34afed7d5af9a167d24de8a00e90b0484122f397 | 4,911 | /*
* Copyright (c) 2008-2015, Esri(China), Inc. All Rights Reserved.
* @author chenhao
* @email chenh@esrichina.com.cn
* @since 2015.09.29
*/
package cn.com.esrichina.adapter.openstack;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.esrichina.adapter.AdapterException;
import cn.com.esrichina.adapter.CloudErrorType;
public class NovaException extends AdapterException {
private static final long serialVersionUID = -9188123825416917437L;
private static Logger logger = (Logger) LoggerFactory.getLogger(NovaException.class);
static public class ExceptionItems {
public CloudErrorType type;
public int code;
public String message;
public String details;
}
//{"badRequest": {"message": "AddressLimitExceeded: Address quota exceeded. You cannot allocate any more addresses", "code": 400}}
static public ExceptionItems parseException(int code, String json) {
ExceptionItems items = new ExceptionItems();
items.code = code;
items.type = CloudErrorType.GENERAL;
items.message = "unknown";
items.details = "The cloud returned an error code with explanation: ";
if (items.code == HttpStatus.SC_UNAUTHORIZED) {
items.type = CloudErrorType.AUTHENTICATION;
}
if( json != null ) {
try {
JSONObject ob = new JSONObject(json);
if( code == 400 && ob.has("badRequest") ) {
ob = ob.getJSONObject("badRequest");
}
if( code == 413 && ob.has("overLimit") ) {
ob = ob.getJSONObject("overLimit");
}
if( ob.has("message") ) {
items.message = ob.getString("message");
if( items.message == null ) {
items.message = "unknown";
}
else {
items.message = items.message.trim();
}
}
if (items.message.equals("unknown")) {
String[] names = JSONObject.getNames(ob);
for (String key : names) {
try {
JSONObject msg = ob.getJSONObject(key);
if (msg.has("message") && !msg.isNull("message")) {
items.message = msg.getString("message");
}
}
catch (JSONException e) {
items.message = ob.getString(key);
}
}
}
if( ob.has("details") ) {
items.details = items.details + ob.getString("details");
}
else {
items.details = items.details + "[" + code + "] " + items.message;
}
String t = items.message.toLowerCase().trim();
if( code == 413 ) {
items.type = CloudErrorType.THROTTLING;
}
else if( t.startsWith("addresslimitexceeded") || t.startsWith("ramlimitexceeded")) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("unauthorized") ) {
items.type = CloudErrorType.AUTHENTICATION;
}
else if( t.equals("serviceunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("badrequest") || t.equals("badmediatype") || t.equals("badmethod") || t.equals("notimplemented") ) {
items.type = CloudErrorType.COMMUNICATION;
}
else if( t.equals("overlimit") ) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("servercapacityunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("itemnotfound") ) {
return null;
}
}
catch( JSONException e ) {
logger.error("parseException(): Invalid JSON in cloud response: " + json);
items.details = items.details+" "+json;
}
}
return items;
}
public NovaException(ExceptionItems items) {
super(items.type, items.code, items.message, items.details);
}
public NovaException(CloudErrorType type, int code, String message, String details) {
super(type, code, message, details);
}
}
| 39.926829 | 135 | 0.495011 |
e35117f712303fa0eefbb1fef291be6e19383194 | 2,090 | package net.jforum.util.legacy.clickstream;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import net.jforum.util.legacy.clickstream.config.ClickstreamConfig;
import net.jforum.util.legacy.clickstream.config.ConfigLoader;
/**
* Determines if a request is actually a bot or spider.
*
* @author <a href="plightbo@hotmail.com">Patrick Lightbody</a>
* @author Rafael Steil (little hacks for JForum)
* @version $Id: BotChecker.java,v 1.6 2005/12/18 02:12:54 rafaelsteil Exp $
*/
public class BotChecker
{
/**
* Checks if we have a bot
* @param request the request
* @return <code>null</code> if there is no bots in the current request,
* or the bot's name otherwise
*/
public static String isBot(HttpServletRequest request)
{
if (request.getRequestURI().indexOf("robots.txt") != -1) {
// there is a specific request for the robots.txt file, so we assume
// it must be a robot (only robots request robots.txt)
return "Unknown (asked for robots.txt)";
}
String userAgent = request.getHeader("User-Agent");
ClickstreamConfig config = ConfigLoader.instance().getConfig();
if (userAgent != null && config != null) {
List agents = config.getBotAgents();
userAgent = userAgent.toLowerCase();
for (Iterator iterator = agents.iterator(); iterator.hasNext(); ) {
String agent = (String) iterator.next();
if (agent == null) {
continue;
}
if (userAgent.indexOf(agent) != -1) {
return userAgent;
}
}
}
String remoteHost = request.getRemoteHost(); // requires a DNS lookup
if (remoteHost != null && remoteHost.length() > 0 && remoteHost.charAt(remoteHost.length() - 1) > 64) {
List hosts = config.getBotHosts();
remoteHost = remoteHost.toLowerCase();
for (Iterator iterator = hosts.iterator(); iterator.hasNext(); ) {
String host = (String) iterator.next();
if (host == null) {
continue;
}
if (remoteHost.indexOf(host) != -1) {
return remoteHost;
}
}
}
return null;
}
} | 26.794872 | 105 | 0.662201 |
428c9ab00e41989bc8f20234929f73d7e7d2eaf9 | 1,293 | package codebot.commands.random;
import codebot.Command;
import net.dv8tion.jda.core.entities.Message;
import java.util.Random;
class EightBall extends Command {
EightBall() {
name = "8ball";
info = "Predicts the future (don't drink the blue liquid)";
usage.add("");
usage.add("question");
}
@Override
public String run(Message message, String[] args, byte perms, String id) {
String[] answers = {
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
};
return send(message.getTextChannel(), id, answers[new Random().nextInt(answers.length)]);
}
}
| 30.069767 | 97 | 0.490333 |
0e9da14562600a3d85f38c684d4f52128d43dc9d | 1,788 | package com.td.admin.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.td.admin.entity.SysParam;
import com.td.admin.mapper.SysParamMapper;
@Service
public class ParamService {
@Autowired
private SysParamMapper finSystemParamMapper;
/**
* 获取所有的参数(密码设置为空)
* @return
*/
public Map<String,Object> getParams(SysParam param){
Long total = finSystemParamMapper.findTotal(param);
Map<String,Object> returnMap = new HashMap<String,Object>();
returnMap.put("total", total);
returnMap.put("rows", finSystemParamMapper.findParams(param));
return returnMap;
// String gridJson = UIUtil.getEasyUiGridJson(total,UIUtil.getJSONFromList(finSystemParamMapper.findParams(param)));
// return gridJson;
}
/**
* 获取所有的参数(密码不做处理)
* @return
*/
public List<SysParam> getAllParamsWithPW(){
return finSystemParamMapper.selectAllParamsWithPW();
}
/**
* 修改系统参数
* @param record
* @return
*/
public int updateParam(SysParam record){
return finSystemParamMapper.updateByPrimaryKeySelective(record);
}
/**
* 根据ID获取参数信息
* @param id
* @return
*/
public SysParam getParamById(Long id){
return finSystemParamMapper.selectByPrimaryKey(id);
}
/**
* 根据param key获取参数信息
* @param key
* @return
*/
public SysParam getParamByKey(String key){
return finSystemParamMapper.selectByParamKey(key);
}
/**
* 修改系统参数
* @param record
* @return
*/
public int updateParamByMap(Map<String,Object> params){
return finSystemParamMapper.updateParamByMap(params);
}
public List<SysParam> selectExcludePW(SysParam param) {
return finSystemParamMapper.selectExcludePW(param);
}
}
| 22.074074 | 117 | 0.733781 |
158fe28feb502ce0340224afe3ac71d1098ffd32 | 291 | package com.github.jiahaowen.spring.assistant.component.rule.model;
/**
* @author jiahaowen.jhw
* @version $Id: RuleCondition.java, v 0.1 2016-12-07 下午6:53 jiahaowen.jhw Exp $
*/
public interface RuleCondition {
String description();
boolean condition();
String code();
}
| 19.4 | 80 | 0.701031 |
b2e2d71c5137a5408ae62a7a5240d900cc49dafd | 1,029 | package com.playernguyen.optecoprime.utils;
import com.playernguyen.optecoprime.utils.NumberUtil.FlexibleNumber;
import com.playernguyen.optecoprime.utils.NumberUtil.NumberFilter;
import org.junit.Assert;
import org.junit.Test;
public class NumberUtilTest {
@Test
public void shouldReturnAsNumberDouble() {
// Convert to a number
NumberFilter filter = new NumberFilter("15.2");
Assert.assertEquals(15.2, filter.asNumber(), 0.1);
}
@Test
public void shouldIsNumber() {
// True
NumberFilter filter = new NumberFilter("150");
Assert.assertTrue(filter.isNumber());
}
@Test
public void shouldNotANumber() {
// False
NumberFilter filter1 = new NumberFilter("150x");
Assert.assertFalse(filter1.isNumber());
}
@Test
public void shouldReturnInitInFlexNumber() {
// int number
FlexibleNumber intNumber = new FlexibleNumber(16.0000000);
Assert.assertEquals("16", intNumber.toString());
}
}
| 27.078947 | 68 | 0.670554 |
d09164667cfd583e4299bc397b30d5f1f24e82d5 | 1,170 | package com.fun.mybatis.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.fun.mybatis.dto.MybatisTestAccDto;
import com.fun.mybatis.model.MybatisTestAcc;
import com.fun.mybatis.service.MybatisTestAccService;
import com.fun.mybatis.support.DataPage;
import com.fun.mybatis.support.Page;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@EnableAutoConfiguration
public class MybatisTestApplicationTests {
@Autowired
private MybatisTestAccService mybatisTestAccService;
@Test
public void testQueryPage() {
Page<MybatisTestAcc> page = new Page<>(1, 100);
page.setNeedTotalCount(true); //是否count查询
page.setOrder("desc");
page.setSort("created_date");
MybatisTestAccDto dto = new MybatisTestAccDto();
//dto.setAccount("funName1");
DataPage<MybatisTestAcc> dataPage = mybatisTestAccService.queryPage(page, dto);
System.out.println(dataPage);
}
}
| 30 | 81 | 0.808547 |
db30ed529809b75acf241a1d489b4d59e6016ffb | 1,382 | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dto;
import com.google.collide.dtogen.shared.RoutingType;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.shared.JsonArray;
/**
* Response with a set of projects.
*/
@RoutingType(type = RoutingTypes.GETPROJECTSRESPONSE)
public interface GetProjectsResponse extends ServerToClientDto {
JsonArray<ProjectInfo> getProjects();
/**
* Returns the IDs of hidden projects.
*/
JsonArray<String> getHiddenProjectIds();
/**
* Returns the ID of the last project that the user viewed.
*/
String getActiveProjectId();
/**
* Returns the next version of the tango object representing this user's
* membership change events.
*/
String getUserMembershipChangeNextVersion();
}
| 30.711111 | 75 | 0.74602 |
a66bffc39001298d422ce999f300037f099257e9 | 1,376 | package rules.entities.conditions.lookup;
import org.json.JSONObject;
import rules.entities.conditions.ConditionLookup;
import rules.entities.conditions.ConditionParameter;
/**
* Created by christopher on 10.08.16.
*/
public class ConditionLookupTable {
String tableId;
ConditionParameter row;
ConditionParameter column;
public String getTableId() {
return tableId;
}
public ConditionParameter getRow() {
return row;
}
public ConditionParameter getColumn() {
return column;
}
public ConditionLookupTable(String tableId, ConditionParameter row, ConditionParameter column) {
this.tableId = tableId;
this.row = row;
this.column = column;
}
public JSONObject toJSON() throws Exception {
JSONObject json = new JSONObject();
json.put("tableId", tableId);
json.put("row", row.toJSON());
json.put("column", column.toJSON());
return json;
}
public static ConditionLookupTable fromJSON(JSONObject json) throws Exception {
String tableId = json.getString("tableId");
ConditionParameter row = ConditionParameter.fromJSON(json.getJSONObject("row"));
ConditionParameter column = ConditionParameter.fromJSON(json.getJSONObject("column"));
return new ConditionLookupTable(tableId, row, column);
}
}
| 26.980392 | 100 | 0.68314 |
ae49033dcfbf41e1f6a26c69fb075a9a26fce630 | 2,052 | package demo.metrics;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.Builder;
import lombok.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Set;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableSet;
import static java.util.stream.Collectors.toList;
@RestController
@RequestMapping(path = "query/tasks")
public class TaskQueryController {
private final TaskRepository taskRepository;
private final Counter queryCounter;
public TaskQueryController(MeterRegistry registry, TaskRepository taskRepository) {
this.taskRepository = taskRepository;
this.queryCounter = Counter.builder("app.query.count")
.baseUnit("count")
.register(registry);
}
@GetMapping
TaskListResponse taskList() {
this.queryCounter.increment();
return TaskListResponse.builder()
.tasks(this.taskRepository.findAll().stream()
.map(task -> TaskListResponseItem.builder()
.id(task.getId())
.title(task.getTitle())
.tags(task.tagsAsSet())
.build()
)
.collect(toList())
)
.build();
}
@Value @Builder
public static class TaskListResponse {
List<TaskListResponseItem> tasks;
public List<TaskListResponseItem> getTasks() {
return unmodifiableList(tasks);
}
}
@Value @Builder
public static class TaskListResponseItem {
String id;
String title;
Set<String> tags;
public Set<String> getTags() {
return unmodifiableSet(tags);
}
}
}
| 29.73913 | 87 | 0.625244 |
6b231f1c592e66128334686ea1d6eb4a41ad2b60 | 5,700 | package org.lared.desinventar.dbase;
import java.sql.*;
import java.io.*;
import org.lared.desinventar.dbase.*;
/**
* Class to handle DBase IV memo fields.
*
* @since 2.01
*/
public class DBASEIVMemoHandler extends MemoHandler
{
/**
* Mysterious bytes written to the start of each memo record.
*/
private final byte std[] = { (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x00 };
/**
* Standard field naming the DBASE IV database.
* This field must be present in all MemoHandler extenders
* so that the list of supported databases can be handled
* as well as the list of classes for creating the instances.
*/
public static String MEMO_HANDLER = "DBASE IV";
/**
* Default constructor.
*/
public DBASEIVMemoHandler()
{
// Create the default empty block based on the assumed block size.
emptyBlock = new byte[ (int) blockSize];
}
/**
* Set block size for the memo data.
* @param blockSize Block size for the memo blocks, usually 512 bytes.
*/
public void setBlockSize(long blockSize)
{
if (blockSize != emptyBlock.length)
{
emptyBlock = new byte[ (int) blockSize];
this.blockSize = blockSize;
}
}
/**
* Retrieve the memo field from the database.
*
* @param dbt RandomAccessFile object for the memo database.
* @param block Block to start reading memo data.
* @return the memo data or null if something went wrong.
* @throws SQLException if the field doesn't contain memo data,
* or the memo data block doesn't exist.
*/
public ByteArrayOutputStream getMemoData(RandomAccessFile dbt, long block) throws SQLException
{
byte memoData[]; // Storage for partial raw memo data.
ByteArrayOutputStream memo = new ByteArrayOutputStream();
try {
// Get the block size the first time we read or write.
if (firstReadWrite)
{
getBlockSize(dbt);
firstReadWrite = false;
}
// NOTE: Actually we seek to the given position from the memo field.
// Then the first 4 bytes are always FF FF 08 00 followed four bytes of
// intel int giving the size of the data block.
// Seek to the block and 8 bytes of DBT header on the first record.
// The memo data size includes the header.
dbt.seek(block * blockSize + 4L);
int dataSize = Intel.readShort(dbt) - 8;
if (dataSize < 0)
{
System.out.println("Data size is " + dataSize);
dbt.seek(block * blockSize + 4L);
byte tmp[] = new byte[8];
dbt.read(tmp);
System.out.println("Bad data: " + new ByteIterator(tmp).dump(0, 8));
System.exit(0);
}
//System.out.println("Data size is " + dataSize);
memoData = new byte[dataSize];
int br = dbt.read(memoData);
//System.out.println("Data: length " + br);
memo.write(memoData);
//System.out.println("Data is : " + new ByteIterator(memoData).dump(0, memoData.length));
} catch (IOException ioe) {
throw new SQLException("Error reading memo field: " + DBase.getStackTrace(ioe));
}
return memo;
}
/**
* Write a memo.
*
* @param dbt RandomAccessFile object for the memo database.
* @param buf data to write.
* @return the block number where the memo starts.
* @throws SQLException
*/
public int writeMemoData(RandomAccessFile dbt, byte buf[], String tableName) throws SQLException
{
try {
// Read header to find out where to write next block.
long fLen = dbt.length(); // Seek to end of file to add bytes.
int lastBlock;
// If the file is empty, write the header. Update the file length as we write.
if (fLen == 0)
{
// New file - create the first empty block and set up lastBlock to be one.
// The lastBlock value will be written later.
lastBlock = 1;
dbt.seek(0L);
if (emptyBlock.length < HEADERSIZE)
dbt.write(emptyBlock, 0, HEADERSIZE);
else
dbt.write(emptyBlock);
// Write the table name.
dbt.seek(8L);
byte tblName[] = new byte[8];
System.arraycopy(tableName.getBytes(), 0, tblName, 0, tblName.length);
dbt.write(tblName);
System.out.println("Writing header for new file with table name." + new String(tblName));
} else {
// Determine where we should write the new data (last block in file).
dbt.seek(0L);
lastBlock = Intel.readShort(dbt);
// Get the block size the first time we read or write.
if (firstReadWrite)
{
getBlockSize(dbt);
firstReadWrite = false;
}
int likelyLastBlock = (int) ((fLen + blockSize - 1) / blockSize);
// See if this make sense.
if (lastBlock > likelyLastBlock)
{
lastBlock = likelyLastBlock;
}
}
// The block may not be fleshed out with data. Write the remainder of the data with zeros
dbt.seek(fLen);
int resid = (int) ((blockSize * lastBlock) - fLen);
if (resid > 0)
dbt.write(emptyBlock, 0, resid);
// Write memo header, length, and data.
dbt.write(std);
Intel.writeShort(dbt, buf.length + 8);
dbt.write(buf);
// Now rewrite the header with the new end position.
dbt.seek(0L);
int writtenBlock = lastBlock + (buf.length + (int) blockSize - 1) / (int) blockSize;
Intel.writeShort(dbt, writtenBlock);
return lastBlock;
} catch (IOException ioe) {
throw new SQLException("Error writing memo file (.dbt): " + ioe.toString());
}
}
public String getDatabaseName()
{
return MEMO_HANDLER;
}
/**
* Get the block size from the file.
* The file is assumed to exist as a memo file complete with header.
* @param dbt Memo file handle.
* @return block size.
* @throws IOException if there's a problem reading the file.
*/
protected long getBlockSize(RandomAccessFile dbt) throws IOException
{
dbt.seek(4L);
blockSize = (long) Intel.readShort(dbt);
if (blockSize == 0)
blockSize = HEADERSIZE;
return blockSize;
}
} | 28.217822 | 97 | 0.675263 |
83a363ef246d815966e2001adf59a420ef20a42f | 2,537 | /*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.mainnet;
import java.util.List;
import java.util.Optional;
import org.hyperledger.besu.ethereum.BlockValidator;
import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockImporter;
import org.hyperledger.besu.ethereum.core.TransactionReceipt;
public class MainnetBlockImporter implements BlockImporter {
final BlockValidator blockValidator;
public MainnetBlockImporter(final BlockValidator blockValidator) {
this.blockValidator = blockValidator;
}
@Override
public synchronized boolean
importBlock(final ProtocolContext context, final Block block,
final HeaderValidationMode headerValidationMode,
final HeaderValidationMode ommerValidationMode) {
if (context.getBlockchain().contains(block.getHash())) {
return true;
}
final Optional<BlockValidator.BlockProcessingOutputs> outputs =
blockValidator.validateAndProcessBlock(
context, block, headerValidationMode, ommerValidationMode);
outputs.ifPresent(processingOutputs
-> context.getBlockchain().appendBlock(
block, processingOutputs.receipts));
return outputs.isPresent();
}
@Override
public boolean
fastImportBlock(final ProtocolContext context, final Block block,
final List<TransactionReceipt> receipts,
final HeaderValidationMode headerValidationMode,
final HeaderValidationMode ommerValidationMode) {
if (blockValidator.fastBlockValidation(context, block, receipts,
headerValidationMode,
ommerValidationMode)) {
context.getBlockchain().appendBlock(block, receipts);
return true;
}
return false;
}
}
| 34.753425 | 80 | 0.712653 |
3de0962e1ea2c5cc19709c58eba826e827f75a36 | 3,777 | /*
* 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.eds.bean;
import java.util.ArrayList;
import com.eds.Helpers.QueryStringParameterHelper;
public class SearchResponse {
private ArrayList<QueryWithAction> queryList = new ArrayList<QueryWithAction>();
private QueryWithAction query;
private String queryString;
private String hits;
private String searchTime;
private ApiErrorMessage apierrormessage;
private ArrayList<Result> resultsList = new ArrayList<Result>();
private ArrayList<Facet> facetsList = new ArrayList<Facet>();
private ArrayList<LimiterWithAction> selectedLimiterList = new ArrayList<LimiterWithAction>();
private ArrayList<ExpandersWithAction> expanderwithActionList = new ArrayList<ExpandersWithAction>();
private ArrayList<FacetFilterWithAction> facetfiltersList = new ArrayList<FacetFilterWithAction>();
public ApiErrorMessage getApierrormessage() {
return apierrormessage;
}
public void setApierrormessage(ApiErrorMessage apierrormessage) {
this.apierrormessage = apierrormessage;
}
public ArrayList<LimiterWithAction> getSelectedLimiterList() {
return selectedLimiterList;
}
public void setSelectedLimiterList(
ArrayList<LimiterWithAction> selectedLimiterList) {
this.selectedLimiterList = selectedLimiterList;
}
public ArrayList<ExpandersWithAction> getExpanderwithActionList() {
return expanderwithActionList;
}
public void setExpanderwithActionList(
ArrayList<ExpandersWithAction> expanderwithActionList) {
this.expanderwithActionList = expanderwithActionList;
}
public ArrayList<FacetFilterWithAction> getFacetfiltersList() {
return facetfiltersList;
}
public void setFacetfiltersList(
ArrayList<FacetFilterWithAction> facetfiltersList) {
this.facetfiltersList = facetfiltersList;
}
public QueryWithAction getQuery() {
return query;
}
public void setQuery(QueryWithAction query) {
this.query = query;
}
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getHits() {
return hits;
}
public String getSearchTime() {
return searchTime;
}
public void setSearchTime(String searchTime) {
this.searchTime = searchTime;
}
public void setHits(String hits) {
this.hits = hits;
}
public ArrayList<Result> getResultsList() {
return resultsList;
}
public void setResultsList(ArrayList<Result> resultsList) {
this.resultsList = resultsList;
}
public ArrayList<Facet> getFacetsList() {
return facetsList;
}
public void setFacetsList(ArrayList<Facet> facetsList) {
this.facetsList = facetsList;
}
public ArrayList<QueryWithAction> getQueryList() {
return this.queryList;
}
public void setQueryList(ArrayList<QueryWithAction> queryList) {
this.queryList = queryList;
}
public String getSelectedPageNumber() {
return QueryStringParameterHelper.GetPageNumber(this.queryString);
}
public String getSelectedResultsPerPage() {
return QueryStringParameterHelper.GetResultPerPage(this.queryString);
}
public String getSelectedView() {
return QueryStringParameterHelper.GetView(this.queryString);
}
public String getSelectedSort() {
return QueryStringParameterHelper.GetSort(this.queryString);
}
}
| 26.787234 | 102 | 0.780514 |
364915ceee940f221cbd89125d6eab1690dfd83e | 2,982 | package pwe.planner.logic.commands;
import static pwe.planner.logic.commands.CommandTestUtil.assertCommandSuccess;
import static pwe.planner.testutil.TypicalDegreePlanners.getTypicalDegreePlannerList;
import static pwe.planner.testutil.TypicalModules.getTypicalModuleList;
import static pwe.planner.testutil.TypicalRequirementCategories.getTypicalRequirementCategoriesList;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import pwe.planner.commons.exceptions.IllegalValueException;
import pwe.planner.commons.util.StringUtil;
import pwe.planner.logic.CommandHistory;
import pwe.planner.model.Model;
import pwe.planner.model.ModelManager;
import pwe.planner.model.UserPrefs;
import pwe.planner.model.module.Code;
import pwe.planner.model.module.Credits;
import pwe.planner.model.tag.Tag;
import pwe.planner.storage.JsonSerializableApplication;
/**
* Contains unit tests for PlannerSuggestCommand.
*/
public class PlannerSuggestCommandTest {
private Model model;
private CommandHistory commandHistory = new CommandHistory();
@Before
public void setUp() throws IllegalValueException {
model = new ModelManager(new JsonSerializableApplication(getTypicalModuleList(), getTypicalDegreePlannerList(),
getTypicalRequirementCategoriesList()).toModelType(), new UserPrefs());
}
@Test
public void execute_modulesWithoutMatchingTagsAndCredits_recommendedModulesFound() {
Credits bestCredits = new Credits("3");
Set<Tag> tagsToFind = Set.of(new Tag("nonexistent"));
List<Code> recommendedCodes = List.of(new Code("CS2101"), new Code("CS2105"));
String recommendedCodesString = StringUtil.joinStreamAsString(recommendedCodes.stream().sorted());
String expectedMessage = String.format(PlannerSuggestCommand.MESSAGE_SUCCESS, recommendedCodesString, "None",
"None");
assertCommandSuccess(new PlannerSuggestCommand(bestCredits, tagsToFind), model, commandHistory,
expectedMessage, model);
}
@Test
public void execute_modulesWithMatchingCredits_recommendedModulesFound() {
Credits bestCredits = new Credits("4");
Set<Tag> tagsToFind = Set.of(new Tag("nonexistent"));
List<Code> recommendedCodes = List.of(new Code("CS2101"), new Code("CS2105"));
List<Code> codesWithMatchingCredits = List.of(new Code("CS2101"));
String matchingCreditCodesString = StringUtil.joinStreamAsString(codesWithMatchingCredits.stream().sorted());
String recommendedCodesString = StringUtil.joinStreamAsString(recommendedCodes.stream().sorted());
String expectedMessage = String.format(PlannerSuggestCommand.MESSAGE_SUCCESS, recommendedCodesString, "None",
matchingCreditCodesString);
assertCommandSuccess(new PlannerSuggestCommand(bestCredits, tagsToFind), model, commandHistory,
expectedMessage, model);
}
}
| 41.416667 | 119 | 0.756204 |
b4d0005d5c473080d3e351853435926f7e921785 | 20,737 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Properties;
import org.compiere.util.Env;
/** Generated Model for T_Aging
* @author Adempiere (generated)
* @version Release 3.5.4a - $Id$ */
public class X_T_Aging extends PO implements I_T_Aging, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_T_Aging (Properties ctx, int T_Aging_ID, String trxName)
{
super (ctx, T_Aging_ID, trxName);
/** if (T_Aging_ID == 0)
{
setAD_PInstance_ID (0);
setC_BPartner_ID (0);
setC_BP_Group_ID (0);
setC_Currency_ID (0);
setDue0 (Env.ZERO);
setDue0_30 (Env.ZERO);
setDue0_7 (Env.ZERO);
setDue1_7 (Env.ZERO);
setDue31_60 (Env.ZERO);
setDue31_Plus (Env.ZERO);
setDue61_90 (Env.ZERO);
setDue61_Plus (Env.ZERO);
setDue8_30 (Env.ZERO);
setDue91_Plus (Env.ZERO);
setDueAmt (Env.ZERO);
setDueDate (new Timestamp( System.currentTimeMillis() ));
setInvoicedAmt (Env.ZERO);
setIsListInvoices (false);
setIsSOTrx (false);
setOpenAmt (Env.ZERO);
setPastDue1_30 (Env.ZERO);
setPastDue1_7 (Env.ZERO);
setPastDue31_60 (Env.ZERO);
setPastDue31_Plus (Env.ZERO);
setPastDue61_90 (Env.ZERO);
setPastDue61_Plus (Env.ZERO);
setPastDue8_30 (Env.ZERO);
setPastDue91_Plus (Env.ZERO);
setPastDueAmt (Env.ZERO);
setStatementDate (new Timestamp( System.currentTimeMillis() ));
} */
}
/** Load Constructor */
public X_T_Aging (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_T_Aging[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_PInstance getAD_PInstance() throws RuntimeException
{
return (I_AD_PInstance)MTable.get(getCtx(), I_AD_PInstance.Table_Name)
.getPO(getAD_PInstance_ID(), get_TrxName()); }
/** Set Process Instance.
@param AD_PInstance_ID
Instance of the process
*/
public void setAD_PInstance_ID (int AD_PInstance_ID)
{
if (AD_PInstance_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PInstance_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PInstance_ID, Integer.valueOf(AD_PInstance_ID));
}
/** Get Process Instance.
@return Instance of the process
*/
public int getAD_PInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Activity getC_Activity() throws RuntimeException
{
return (I_C_Activity)MTable.get(getCtx(), I_C_Activity.Table_Name)
.getPO(getC_Activity_ID(), get_TrxName()); }
/** Set Activity.
@param C_Activity_ID
Business Activity
*/
public void setC_Activity_ID (int C_Activity_ID)
{
if (C_Activity_ID < 1)
set_Value (COLUMNNAME_C_Activity_ID, null);
else
set_Value (COLUMNNAME_C_Activity_ID, Integer.valueOf(C_Activity_ID));
}
/** Get Activity.
@return Business Activity
*/
public int getC_Activity_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Activity_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_BPartner getC_BPartner() throws RuntimeException
{
return (I_C_BPartner)MTable.get(getCtx(), I_C_BPartner.Table_Name)
.getPO(getC_BPartner_ID(), get_TrxName()); }
/** Set Business Partner .
@param C_BPartner_ID
Identifies a Business Partner
*/
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Business Partner .
@return Identifies a Business Partner
*/
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_BP_Group getC_BP_Group() throws RuntimeException
{
return (I_C_BP_Group)MTable.get(getCtx(), I_C_BP_Group.Table_Name)
.getPO(getC_BP_Group_ID(), get_TrxName()); }
/** Set Business Partner Group.
@param C_BP_Group_ID
Business Partner Group
*/
public void setC_BP_Group_ID (int C_BP_Group_ID)
{
if (C_BP_Group_ID < 1)
set_Value (COLUMNNAME_C_BP_Group_ID, null);
else
set_Value (COLUMNNAME_C_BP_Group_ID, Integer.valueOf(C_BP_Group_ID));
}
/** Get Business Partner Group.
@return Business Partner Group
*/
public int getC_BP_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Campaign getC_Campaign() throws RuntimeException
{
return (I_C_Campaign)MTable.get(getCtx(), I_C_Campaign.Table_Name)
.getPO(getC_Campaign_ID(), get_TrxName()); }
/** Set Campaign.
@param C_Campaign_ID
Marketing Campaign
*/
public void setC_Campaign_ID (int C_Campaign_ID)
{
if (C_Campaign_ID < 1)
set_Value (COLUMNNAME_C_Campaign_ID, null);
else
set_Value (COLUMNNAME_C_Campaign_ID, Integer.valueOf(C_Campaign_ID));
}
/** Get Campaign.
@return Marketing Campaign
*/
public int getC_Campaign_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Campaign_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Currency getC_Currency() throws RuntimeException
{
return (I_C_Currency)MTable.get(getCtx(), I_C_Currency.Table_Name)
.getPO(getC_Currency_ID(), get_TrxName()); }
/** Set Currency.
@param C_Currency_ID
The Currency for this record
*/
public void setC_Currency_ID (int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Currency_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID));
}
/** Get Currency.
@return The Currency for this record
*/
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Invoice getC_Invoice() throws RuntimeException
{
return (I_C_Invoice)MTable.get(getCtx(), I_C_Invoice.Table_Name)
.getPO(getC_Invoice_ID(), get_TrxName()); }
/** Set Invoice.
@param C_Invoice_ID
Invoice Identifier
*/
public void setC_Invoice_ID (int C_Invoice_ID)
{
if (C_Invoice_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID));
}
/** Get Invoice.
@return Invoice Identifier
*/
public int getC_Invoice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_InvoicePaySchedule getC_InvoicePaySchedule() throws RuntimeException
{
return (I_C_InvoicePaySchedule)MTable.get(getCtx(), I_C_InvoicePaySchedule.Table_Name)
.getPO(getC_InvoicePaySchedule_ID(), get_TrxName()); }
/** Set Invoice Payment Schedule.
@param C_InvoicePaySchedule_ID
Invoice Payment Schedule
*/
public void setC_InvoicePaySchedule_ID (int C_InvoicePaySchedule_ID)
{
if (C_InvoicePaySchedule_ID < 1)
set_Value (COLUMNNAME_C_InvoicePaySchedule_ID, null);
else
set_Value (COLUMNNAME_C_InvoicePaySchedule_ID, Integer.valueOf(C_InvoicePaySchedule_ID));
}
/** Get Invoice Payment Schedule.
@return Invoice Payment Schedule
*/
public int getC_InvoicePaySchedule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoicePaySchedule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Project getC_Project() throws RuntimeException
{
return (I_C_Project)MTable.get(getCtx(), I_C_Project.Table_Name)
.getPO(getC_Project_ID(), get_TrxName()); }
/** Set Project.
@param C_Project_ID
Financial Project
*/
public void setC_Project_ID (int C_Project_ID)
{
if (C_Project_ID < 1)
set_Value (COLUMNNAME_C_Project_ID, null);
else
set_Value (COLUMNNAME_C_Project_ID, Integer.valueOf(C_Project_ID));
}
/** Get Project.
@return Financial Project
*/
public int getC_Project_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Project_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Account Date.
@param DateAcct
Accounting Date
*/
public void setDateAcct (boolean DateAcct)
{
set_Value (COLUMNNAME_DateAcct, Boolean.valueOf(DateAcct));
}
/** Get Account Date.
@return Accounting Date
*/
public boolean isDateAcct ()
{
Object oo = get_Value(COLUMNNAME_DateAcct);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Days due.
@param DaysDue
Number of days due (negative: due in number of days)
*/
public void setDaysDue (int DaysDue)
{
set_Value (COLUMNNAME_DaysDue, Integer.valueOf(DaysDue));
}
/** Get Days due.
@return Number of days due (negative: due in number of days)
*/
public int getDaysDue ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DaysDue);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Due Today.
@param Due0 Due Today */
public void setDue0 (BigDecimal Due0)
{
set_Value (COLUMNNAME_Due0, Due0);
}
/** Get Due Today.
@return Due Today */
public BigDecimal getDue0 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due0);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due Today-30.
@param Due0_30 Due Today-30 */
public void setDue0_30 (BigDecimal Due0_30)
{
set_Value (COLUMNNAME_Due0_30, Due0_30);
}
/** Get Due Today-30.
@return Due Today-30 */
public BigDecimal getDue0_30 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due0_30);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due Today-7.
@param Due0_7 Due Today-7 */
public void setDue0_7 (BigDecimal Due0_7)
{
set_Value (COLUMNNAME_Due0_7, Due0_7);
}
/** Get Due Today-7.
@return Due Today-7 */
public BigDecimal getDue0_7 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due0_7);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due 1-7.
@param Due1_7 Due 1-7 */
public void setDue1_7 (BigDecimal Due1_7)
{
set_Value (COLUMNNAME_Due1_7, Due1_7);
}
/** Get Due 1-7.
@return Due 1-7 */
public BigDecimal getDue1_7 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due1_7);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due 31-60.
@param Due31_60 Due 31-60 */
public void setDue31_60 (BigDecimal Due31_60)
{
set_Value (COLUMNNAME_Due31_60, Due31_60);
}
/** Get Due 31-60.
@return Due 31-60 */
public BigDecimal getDue31_60 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due31_60);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due > 31.
@param Due31_Plus Due > 31 */
public void setDue31_Plus (BigDecimal Due31_Plus)
{
set_Value (COLUMNNAME_Due31_Plus, Due31_Plus);
}
/** Get Due > 31.
@return Due > 31 */
public BigDecimal getDue31_Plus ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due31_Plus);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due 61-90.
@param Due61_90 Due 61-90 */
public void setDue61_90 (BigDecimal Due61_90)
{
set_Value (COLUMNNAME_Due61_90, Due61_90);
}
/** Get Due 61-90.
@return Due 61-90 */
public BigDecimal getDue61_90 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due61_90);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due > 61.
@param Due61_Plus Due > 61 */
public void setDue61_Plus (BigDecimal Due61_Plus)
{
set_Value (COLUMNNAME_Due61_Plus, Due61_Plus);
}
/** Get Due > 61.
@return Due > 61 */
public BigDecimal getDue61_Plus ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due61_Plus);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due 8-30.
@param Due8_30 Due 8-30 */
public void setDue8_30 (BigDecimal Due8_30)
{
set_Value (COLUMNNAME_Due8_30, Due8_30);
}
/** Get Due 8-30.
@return Due 8-30 */
public BigDecimal getDue8_30 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due8_30);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due > 91.
@param Due91_Plus Due > 91 */
public void setDue91_Plus (BigDecimal Due91_Plus)
{
set_Value (COLUMNNAME_Due91_Plus, Due91_Plus);
}
/** Get Due > 91.
@return Due > 91 */
public BigDecimal getDue91_Plus ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Due91_Plus);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Amount due.
@param DueAmt
Amount of the payment due
*/
public void setDueAmt (BigDecimal DueAmt)
{
set_Value (COLUMNNAME_DueAmt, DueAmt);
}
/** Get Amount due.
@return Amount of the payment due
*/
public BigDecimal getDueAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DueAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Due Date.
@param DueDate
Date when the payment is due
*/
public void setDueDate (Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
/** Get Due Date.
@return Date when the payment is due
*/
public Timestamp getDueDate ()
{
return (Timestamp)get_Value(COLUMNNAME_DueDate);
}
/** Set Invoiced Amount.
@param InvoicedAmt
The amount invoiced
*/
public void setInvoicedAmt (BigDecimal InvoicedAmt)
{
set_Value (COLUMNNAME_InvoicedAmt, InvoicedAmt);
}
/** Get Invoiced Amount.
@return The amount invoiced
*/
public BigDecimal getInvoicedAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InvoicedAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set List Invoices.
@param IsListInvoices
Include List of Invoices
*/
public void setIsListInvoices (boolean IsListInvoices)
{
set_Value (COLUMNNAME_IsListInvoices, Boolean.valueOf(IsListInvoices));
}
/** Get List Invoices.
@return Include List of Invoices
*/
public boolean isListInvoices ()
{
Object oo = get_Value(COLUMNNAME_IsListInvoices);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Open Amount.
@param OpenAmt
Open item amount
*/
public void setOpenAmt (BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Open Amount.
@return Open item amount
*/
public BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due 1-30.
@param PastDue1_30 Past Due 1-30 */
public void setPastDue1_30 (BigDecimal PastDue1_30)
{
set_Value (COLUMNNAME_PastDue1_30, PastDue1_30);
}
/** Get Past Due 1-30.
@return Past Due 1-30 */
public BigDecimal getPastDue1_30 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue1_30);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due 1-7.
@param PastDue1_7 Past Due 1-7 */
public void setPastDue1_7 (BigDecimal PastDue1_7)
{
set_Value (COLUMNNAME_PastDue1_7, PastDue1_7);
}
/** Get Past Due 1-7.
@return Past Due 1-7 */
public BigDecimal getPastDue1_7 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue1_7);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due 31-60.
@param PastDue31_60 Past Due 31-60 */
public void setPastDue31_60 (BigDecimal PastDue31_60)
{
set_Value (COLUMNNAME_PastDue31_60, PastDue31_60);
}
/** Get Past Due 31-60.
@return Past Due 31-60 */
public BigDecimal getPastDue31_60 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue31_60);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due > 31.
@param PastDue31_Plus Past Due > 31 */
public void setPastDue31_Plus (BigDecimal PastDue31_Plus)
{
set_Value (COLUMNNAME_PastDue31_Plus, PastDue31_Plus);
}
/** Get Past Due > 31.
@return Past Due > 31 */
public BigDecimal getPastDue31_Plus ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue31_Plus);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due 61-90.
@param PastDue61_90 Past Due 61-90 */
public void setPastDue61_90 (BigDecimal PastDue61_90)
{
set_Value (COLUMNNAME_PastDue61_90, PastDue61_90);
}
/** Get Past Due 61-90.
@return Past Due 61-90 */
public BigDecimal getPastDue61_90 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue61_90);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due > 61.
@param PastDue61_Plus Past Due > 61 */
public void setPastDue61_Plus (BigDecimal PastDue61_Plus)
{
set_Value (COLUMNNAME_PastDue61_Plus, PastDue61_Plus);
}
/** Get Past Due > 61.
@return Past Due > 61 */
public BigDecimal getPastDue61_Plus ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue61_Plus);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due 8-30.
@param PastDue8_30 Past Due 8-30 */
public void setPastDue8_30 (BigDecimal PastDue8_30)
{
set_Value (COLUMNNAME_PastDue8_30, PastDue8_30);
}
/** Get Past Due 8-30.
@return Past Due 8-30 */
public BigDecimal getPastDue8_30 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue8_30);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due > 91.
@param PastDue91_Plus Past Due > 91 */
public void setPastDue91_Plus (BigDecimal PastDue91_Plus)
{
set_Value (COLUMNNAME_PastDue91_Plus, PastDue91_Plus);
}
/** Get Past Due > 91.
@return Past Due > 91 */
public BigDecimal getPastDue91_Plus ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue91_Plus);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due.
@param PastDueAmt Past Due */
public void setPastDueAmt (BigDecimal PastDueAmt)
{
set_Value (COLUMNNAME_PastDueAmt, PastDueAmt);
}
/** Get Past Due.
@return Past Due */
public BigDecimal getPastDueAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDueAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Statement date.
@param StatementDate
Date of the statement
*/
public void setStatementDate (Timestamp StatementDate)
{
set_Value (COLUMNNAME_StatementDate, StatementDate);
}
/** Get Statement date.
@return Date of the statement
*/
public Timestamp getStatementDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StatementDate);
}
} | 24.001157 | 92 | 0.681969 |
dfc87ff4142c74a94b113aa56f3dbc4d7066eb77 | 3,272 | package com.mycompany.customerservice.model;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.util.Date;
import java.util.Objects;
@Entity
@Table(name = "customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotNull(message = "First Name cannot be null")
@NotEmpty(message = "First Name cannot be empty")
@Size(max = 15, message = "First Name cannot be greater than 15 characters")
@Column(name = "first_name", length = 15, nullable = false)
private String firstName;
@NotNull(message = "Last Name cannot be null")
@NotEmpty(message = "Last Name cannot be empty")
@Size(max = 20, message = "Last Name cannot be greater than 20 characters")
@Column(name = "last_name", length = 20, nullable = false)
private String lastName;
@Past(message = "DOB must be in the past")
@Column(name = "date_of_birth")
private Date dateOfBirth;
@Email(message = "Email cannot be null")
@Column(name = "email", length = 30, nullable = false)
private String email;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return id == customer.id &&
firstName.equals(customer.firstName) &&
lastName.equals(customer.lastName) &&
dateOfBirth.equals(customer.dateOfBirth) &&
email.equals(customer.email) &&
address.equals(customer.address);
}
@Override
public int hashCode() {
return Objects.hash(id, firstName, lastName, dateOfBirth, email, address);
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Customer{");
sb.append("id=").append(id);
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", dateOfBirth=").append(dateOfBirth);
sb.append(", email='").append(email).append('\'');
sb.append(", address=").append(address);
sb.append('}');
return sb.toString();
}
}
| 27.495798 | 82 | 0.61522 |
2b816094015cb110aeb5b2d80474d66e2feccf6e | 2,252 |
package com.gp.health.ui.member_profile.member_ads;
import androidx.lifecycle.MutableLiveData;
import com.gp.health.data.DataManager;
import com.gp.health.data.models.AdAndOrderModel;
import com.gp.health.data.models.PagDataWrapperModel;
import com.gp.health.ui.base.BaseViewModel;
import com.gp.health.utils.rx.SchedulerProvider;
import java.util.List;
public class MemberAdsViewModel extends BaseViewModel<MemberAdsNavigator> {
private MutableLiveData<PagDataWrapperModel<List<AdAndOrderModel>>> userAdsLiveData;
public MemberAdsViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
super(dataManager, schedulerProvider);
userAdsLiveData = new MutableLiveData<>();
}
public MutableLiveData<PagDataWrapperModel<List<AdAndOrderModel>>> getUserAdsLiveData() {
return userAdsLiveData;
}
public void getUserAds(int userId, int type, int page) {
getCompositeDisposable().add(getDataManager()
.getUserAdsOrOrdersApiCall(userId, type, page)
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(response -> {
if (response.getCode() == 200 || response.getCode() == 206)
userAdsLiveData.setValue(response);
else
getNavigator().showMyApiMessage(response.getMessage());
}, throwable -> {
getNavigator().handleError(throwable);
}));
}
public void favoriteOrUnFavorite(int itemId, int position) {
getCompositeDisposable().add(getDataManager()
.favoriteOrUnFavoriteApiCall(itemId)
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(response -> {
if (response.getCode() == 200)
getNavigator().favoriteDone(response.getData(), position);
else
getNavigator().showMyApiMessage(response.getMessage());
}, throwable -> {
getNavigator().handleError(throwable);
}));
}
}
| 35.1875 | 93 | 0.624334 |
afb309880fb68b8e0136f254bf66a19c60e2bd32 | 3,093 | package de.metas.dunning.api.impl;
/*
* #%L
* de.metas.dunning
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import org.compiere.util.Util;
import de.metas.dunning.exception.DunningException;
import de.metas.dunning.model.I_C_Dunning_Candidate;
import de.metas.dunning.spi.IDunningAggregator;
import de.metas.dunning.spi.IDunningAggregator.Result;
public class CompositeDunningAggregator
{
private final List<IDunningAggregator> dunningAggregators = new ArrayList<IDunningAggregator>();
private final IDunningAggregator defaultDunningAggregator = new DefaultDunningAggregator();
public void addAggregator(IDunningAggregator aggregator)
{
dunningAggregators.add(aggregator);
}
public boolean isNewDunningDoc(I_C_Dunning_Candidate candidate)
{
Result finalResult = null;
for (IDunningAggregator agg : dunningAggregators)
{
final Result result = agg.isNewDunningDoc(candidate);
if (result == Result.I_FUCKING_DONT_CARE)
{
continue;
}
if (result == null)
{
finalResult = result;
}
if (!Util.same(result, finalResult))
{
throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators);
}
}
if (finalResult == null)
{
finalResult = defaultDunningAggregator.isNewDunningDoc(candidate);
}
return toBoolean(finalResult);
}
public boolean isNewDunningDocLine(I_C_Dunning_Candidate candidate)
{
if (dunningAggregators.isEmpty())
{
throw new DunningException("No child " + IDunningAggregator.class + " registered");
}
Result finalResult = null;
for (IDunningAggregator agg : dunningAggregators)
{
final Result result = agg.isNewDunningDocLine(candidate);
if (result == Result.I_FUCKING_DONT_CARE)
{
continue;
}
if (result == null)
{
finalResult = result;
}
if (!Util.same(result, finalResult))
{
throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators);
}
}
if (finalResult == null)
{
finalResult = defaultDunningAggregator.isNewDunningDocLine(candidate);
}
return toBoolean(finalResult);
}
private static final boolean toBoolean(final Result result)
{
if (result == Result.YES)
{
return true;
}
else if (result == Result.NO)
{
return false;
}
else
{
throw new IllegalArgumentException("Result shall be YES or NO: " + result);
}
}
}
| 24.354331 | 97 | 0.722599 |
08bbbb2caeee7ff59937db934c2415f0d4e90b7a | 752 | package de.felixklauke.avalance.core;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import de.felixklauke.avalance.core.config.AvalanceCoreConfig;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
/**
* @author Felix Klauke <info@felix-klauke.de>
*/
public class AvalanceFactoryTest {
@Test
public void createAvalance() {
AvalanceCoreConfig coreConfig = new AvalanceCoreConfig();
Avalance avalance = AvalanceFactory.createAvalance(coreConfig);
assertNotNull(avalance);
}
@Test
public void testInit() {
Executable executable = AvalanceFactory::new;
assertThrows(AssertionError.class, executable);
}
}
| 25.931034 | 67 | 0.771277 |
a8adace4eb249d4cef0f2ea4a94a227a5db862d4 | 2,320 | /*
* Copyright 2019 Albert Tregnaghi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
*
*/
package de.jcup.asciidoctoreditor.codeassist;
import de.jcup.asciidoctoreditor.document.keywords.PlantUMLColorDocumentKeywords;
import de.jcup.asciidoctoreditor.document.keywords.PlantUMLKeywordDocumentKeywords;
import de.jcup.asciidoctoreditor.document.keywords.PlantUMLMissingKeywordDocumentKeywords;
import de.jcup.asciidoctoreditor.document.keywords.PlantUMLPreprocessorDocumentKeywords;
import de.jcup.asciidoctoreditor.document.keywords.PlantUMLSkinparameterDocumentKeywords;
import de.jcup.asciidoctoreditor.document.keywords.PlantUMLTypeDocumentKeywords;
import de.jcup.eclipse.commons.PluginContextProvider;
import de.jcup.eclipse.commons.keyword.DocumentKeyWord;
public class PlantUMLKeywordContentAssistSupport extends AsciidocKeywordContentAssistSupport{
public PlantUMLKeywordContentAssistSupport(PluginContextProvider provider) {
super(provider);
}
protected void addAllAsciiDoctorKeyWords() {
for (DocumentKeyWord keyword : PlantUMLColorDocumentKeywords.values()) {
addKeyWord(keyword);
}
for (DocumentKeyWord keyword : PlantUMLKeywordDocumentKeywords.values()) {
addKeyWord(keyword);
}
for (DocumentKeyWord keyword : PlantUMLMissingKeywordDocumentKeywords.values()) {
addKeyWord(keyword);
}
for (DocumentKeyWord keyword : PlantUMLPreprocessorDocumentKeywords.values()) {
addKeyWord(keyword);
}
for (DocumentKeyWord keyword : PlantUMLSkinparameterDocumentKeywords.values()) {
addKeyWord(keyword);
}
for (DocumentKeyWord keyword : PlantUMLTypeDocumentKeywords.values()) {
addKeyWord(keyword);
}
}
} | 41.428571 | 93 | 0.751724 |
514ff25df43bcf4171118f75d8ec80f147c0a8c1 | 11,070 | package com.cncounter.druid.web.util;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.HeaderGroup;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.BitSet;
import java.util.Enumeration;
import java.util.Formatter;
/**
* Http 代理请求工具
*/
public class HttpProxyUtil {
public static final String ATTR_STAT_NODE = "HttpProxyUtil.STAT_NODE";
/**
* 代理获取内容...
* @param servletRequest
* @param targetUri
* @return
* @throws Exception
*/
public static String proxy(HttpServletRequest servletRequest, String targetUri)
throws Exception {
String result = "";
URI targetUriObj = new URI(targetUri);
HttpHost targetHost = URIUtils.extractHost(targetUriObj);
HttpParams hcParams = new BasicHttpParams();
hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
hcParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); // See #70
HttpClient proxyClient = createHttpClient(hcParams);
// Make the Request
String method = servletRequest.getMethod();
String proxyRequestUri = rewriteUrlFromRequest(servletRequest, targetUri);
HttpRequest proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
copyRequestHeaders(servletRequest, proxyRequest, targetHost);
setXForwardedForHeader(servletRequest, proxyRequest);
HttpResponse proxyResponse = null;
try {
proxyResponse = proxyClient.execute(targetHost, proxyRequest);
HttpEntity entity = proxyResponse.getEntity();
if (entity != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
entity.writeTo(byteArrayOutputStream);
result = byteArrayOutputStream.toString("UTF-8");
//
closeQuietly(byteArrayOutputStream);
}
} finally {
// make sure the entire entity was consumed, so the connection is released
if (proxyResponse != null){
consumeQuietly(proxyResponse.getEntity());
}
}
return result;
}
public static HttpClient createHttpClient(HttpParams hcParams) {
try {
//as of HttpComponents v4.2, this class is better since it uses System
// Properties:
Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
return (HttpClient) constructor.newInstance(hcParams);
} catch (ClassNotFoundException e) {
//no problem; use v4.1 below
} catch (Exception e) {
throw new RuntimeException(e);
}
//Fallback on using older client:
return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}
public static void closeQuietly(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
}
}
public static void consumeQuietly(HttpEntity entity) {
try {
EntityUtils.consume(entity);
} catch (IOException e) {//ignore
}
}
/** These are the "hop-by-hop" headers that should not be copied.
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
* I use an HttpClient HeaderGroup class instead of Set<String> because this
* approach does case insensitive lookup faster.
*/
public static final HeaderGroup hopByHopHeaders;
static {
hopByHopHeaders = new HeaderGroup();
String[] headers = new String[] {
"Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
"TE", "Trailers", "Transfer-Encoding", "Upgrade" };
for (String header : headers) {
hopByHopHeaders.addHeader(new BasicHeader(header, null));
}
}
/** Copy request headers from the servlet client to the proxy request. */
public static void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest,HttpHost targetHost) {
// Get an Enumeration of all of the header names sent by the client
@SuppressWarnings("unchecked")
Enumeration<String> enumerationOfHeaderNames = servletRequest.getHeaderNames();
while (enumerationOfHeaderNames.hasMoreElements()) {
String headerName = enumerationOfHeaderNames.nextElement();
copyRequestHeader(servletRequest, proxyRequest, headerName, targetHost);
}
// 增加 处理头
Object _statNodeHeaderName = servletRequest.getAttribute(ATTR_STAT_NODE);
if(null != _statNodeHeaderName){
String statNodeHeaderName = _statNodeHeaderName.toString();
Object statNodeHeaderValue = servletRequest.getAttribute(statNodeHeaderName);
proxyRequest.addHeader(statNodeHeaderName, String.valueOf(statNodeHeaderValue));
}
}
/**
* Copy a request header from the servlet client to the proxy request.
* This is easily overwritten to filter out certain headers if desired.
*/
public static void copyRequestHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest,
String headerName,HttpHost targetHost) {
//Instead the content-length is effectively set via InputStreamEntity
if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH))
return;
if (hopByHopHeaders.containsHeader(headerName))
return;
@SuppressWarnings("unchecked")
Enumeration<String> headers = servletRequest.getHeaders(headerName);
while (headers.hasMoreElements()) {//sometimes more than one value
String headerValue = headers.nextElement();
// In case the proxy host is running multiple virtual servers,
// rewrite the Host header to ensure that we get content from
// the correct virtual server
if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) {
HttpHost host = targetHost;
headerValue = host.getHostName();
if (host.getPort() != -1)
headerValue += ":"+host.getPort();
}
proxyRequest.addHeader(headerName, headerValue);
}
}
private static void setXForwardedForHeader(HttpServletRequest servletRequest,
HttpRequest proxyRequest) {
String headerName = "X-Forwarded-For";
String newHeader = servletRequest.getHeader(headerName);
if(null != newHeader && newHeader.trim().isEmpty()){
newHeader = servletRequest.getRemoteAddr();
}
proxyRequest.setHeader(headerName, newHeader);
}
public static String rewriteUrlFromRequest(HttpServletRequest servletRequest,String targetUri) {
StringBuilder uri = new StringBuilder(500);
uri.append(targetUri);
// Handle the path given to the servlet
final String SLASH = "/";
String pathInfo = servletRequest.getPathInfo();
if (pathInfo != null) {//ex: /my/path.html
if(targetUri.endsWith(SLASH) && pathInfo.startsWith(SLASH)){
pathInfo = pathInfo.substring(1);
}
uri.append(encodeUriQuery(pathInfo));
}
// Handle the query string & fragment
String queryString = servletRequest.getQueryString();//ex:(following '?'): name=value&foo=bar#fragment
String fragment = null;
//split off fragment from queryString, updating queryString if found
if (queryString != null) {
int fragIdx = queryString.indexOf('#');
if (fragIdx >= 0) {
fragment = queryString.substring(fragIdx + 1);
queryString = queryString.substring(0,fragIdx);
}
}
if (queryString != null && queryString.length() > 0) {
uri.append('?');
uri.append(encodeUriQuery(queryString));
}
if (fragment != null) {
uri.append('#');
uri.append(encodeUriQuery(fragment));
}
return uri.toString();
}
public static CharSequence encodeUriQuery(CharSequence in) {
//Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things.
StringBuilder outBuf = null;
Formatter formatter = null;
for(int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
boolean escape = true;
if (c < 128) {
if (asciiQueryChars.get((int)c)) {
escape = false;
}
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii
escape = false;
}
if (!escape) {
if (outBuf != null)
outBuf.append(c);
} else {
//escape
if (outBuf == null) {
outBuf = new StringBuilder(in.length() + 5*3);
outBuf.append(in,0,i);
formatter = new Formatter(outBuf);
}
//leading %, 0 padded, width 2, capital hex
formatter.format("%%%02X",(int)c);//TODO
}
}
return outBuf != null ? outBuf : in;
}
public static final BitSet asciiQueryChars;
static {
char[] c_unreserved = "_-!.~'()*".toCharArray();//plus alphanum
char[] c_punct = ",;:$&+=".toCharArray();
char[] c_reserved = "?/[]@".toCharArray();//plus punct
asciiQueryChars = new BitSet(128);
for(char c = 'a'; c <= 'z'; c++) asciiQueryChars.set((int)c);
for(char c = 'A'; c <= 'Z'; c++) asciiQueryChars.set((int)c);
for(char c = '0'; c <= '9'; c++) asciiQueryChars.set((int)c);
for(char c : c_unreserved) asciiQueryChars.set((int)c);
for(char c : c_punct) asciiQueryChars.set((int)c);
for(char c : c_reserved) asciiQueryChars.set((int)c);
asciiQueryChars.set((int)'%');//leave existing percent escapes in place
}
}
| 39.255319 | 124 | 0.624119 |
e116c6365d29cb14e06946331c812377060ff057 | 432 | package com.eletter.gr.springboot;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.logging.Logger;
@Controller
public class IndexController {
private final Logger logger = Logger.getLogger(this.getClass().getName());
@GetMapping("/")
public String index(Model model) {
return "index";
}
}
| 24 | 78 | 0.75 |
e8757e5958d9ce24be1a232736d5e711b4df3343 | 589 | /*
* Copyright 2019 YugaByte, Inc. and Contributors
*
* Licensed under the Polyform Free Trial License 1.0.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://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt
*/
package com.yugabyte.yw.common.utils;
import lombok.Data;
@Data
public class Pair<U, V> {
private final U first;
private final V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
}
| 23.56 | 105 | 0.701188 |
23c01ce454e044cefd3bca7eec52a163471c99ca | 1,798 | package com.web.cost.entity;
import com.app.base.entity.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 客户BOM附件关联
*/
@Entity(name = "CustomerBomFile")
@Table(name = CustomerBomFile.TABLE_NAME)
@DynamicUpdate
@ApiModel
public class CustomerBomFile extends BaseEntity {
private static final long serialVersionUID = -7618382242181528812L;
public static final String TABLE_NAME = "t_customer_bom_file";
/**
* 文件ID(作为某一个客户BOM的唯一标识)
*/
@ApiModelProperty(name = "fileId", value = "文件ID")
@Column
protected Long bsFileId;
/**
* 客户BOM表ID(标题列)
*/
@ApiModelProperty(name = "bsCusBomId", value = "客户BOM表ID")
@Column
protected Long bsCusBomId;
/**
* 关联附件ID
*/
@ApiModelProperty(name = "bsDocId", value = "关联附件ID")
@Column
protected Long bsDocId;
/**
* 关联附件名称
*/
@ApiModelProperty(name = "bsDocName", value = "关联附件名称")
@Column(length = 220)
protected String bsDocName;
public Long getBsFileId() {
return bsFileId;
}
public void setBsFileId(Long bsFileId) {
this.bsFileId = bsFileId;
}
public Long getBsCusBomId() {
return bsCusBomId;
}
public void setBsCusBomId(Long bsCusBomId) {
this.bsCusBomId = bsCusBomId;
}
public Long getBsDocId() {
return bsDocId;
}
public void setBsDocId(Long bsDocId) {
this.bsDocId = bsDocId;
}
public String getBsDocName() {
return bsDocName;
}
public void setBsDocName(String bsDocName) {
this.bsDocName = bsDocName;
}
}
| 21.662651 | 71 | 0.659066 |
a0c9bc5b44349acc37ae93bdcefc53baf0842ba3 | 19,439 | import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.nio.charset.Charset;
import java.util.Date;
import com.pi4j.io.gpio.*;
import com.pi4j.io.serial.*;
import com.pi4j.wiringpi.SoftPwm;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;
public class Rover extends JFrame implements ActionListener, ChangeListener {
private static final long serialVersionUID = 7035088961629706287L;
/**
* GPIO pins for light, alarm, speed and camera
*/
private static final byte LIGHT_SWITCH = 0, ALARM_SWITCH = 1, CAM_SWITCH = 2, SPEED_PIN = 1;
/**
* GUI variables
*/
private Container container;
private JButton lightBut, camBut, alarmBut, autoManBut, forwardBut, backBut, leftBut,
rightBut, stopBut;
private JLabel tempLabel, lightLabel, CdisLabel, LdisLabel, RdisLabel, alarmLabel,
driveDirection, camLabel;
private JSlider speedSlide;
/**
* serial handler
*/
private final com.pi4j.io.serial.Serial SERIAL = SerialFactory.createInstance();
/**
* Threads that control camera and auto-avoidance
*/
private final Thread camera, avoidance;
private final GpioController GPIO = GpioFactory.getInstance();
private final GpioPinDigitalOutput motorLeft1, motorLeft2, motorRight1, motorRight2;
/**
* instruction code to control camera
*/
private final String startInstruction = "/usr/bin/raspivid -t 0 -h 720 -w 1280 -o /home/pi/Videos/";
private final String endInstruction = "killall raspivid";
/**
* if the avoidance function is on
*/
private boolean onAvoid = true;
/**
* variables that indicates temperature and surrounding distances
*/
private int temperature, Cdistance, Ldistance, Rdistance;
public static void main(String[] args) {
// initiate the program
try {
new Rover();
} catch (IOException io) {
io.printStackTrace();
}
}
private Rover() throws IOException {
// add shutdown hook
shutDown();
// initiate GUI
speedSlide = new JSlider(SwingConstants.VERTICAL, 0, 5, 5);
speedSlide.setPaintTicks(true);
speedSlide.setMajorTickSpacing(1);
speedSlide.setSnapToTicks(true);
speedSlide.addChangeListener(this);
speedSlide.setEnabled(false);
autoManBut = new JButton("AUTO/MANUAL");
autoManBut.addActionListener(this);
alarmBut = new JButton("ON/OFF");
alarmBut.addActionListener(this);
lightBut = new JButton("ON/OFF");
lightBut.addActionListener(this);
camBut = new JButton("ON/OFF");
camBut.addActionListener(this);
forwardBut = new JButton("FORWARD");
forwardBut.addActionListener(this);
forwardBut.setEnabled(false);
backBut = new JButton("BACK");
backBut.addActionListener(this);
backBut.setEnabled(false);
leftBut = new JButton("LEFT");
leftBut.addActionListener(this);
leftBut.setEnabled(false);
rightBut = new JButton("RIGHT");
rightBut.addActionListener(this);
rightBut.setEnabled(false);
stopBut = new JButton("STOP");
stopBut.addActionListener(this);
stopBut.setEnabled(false);
tempLabel = new JLabel("Temperature: ");
lightLabel = new JLabel("Light OFF");
alarmLabel = new JLabel("Alarm OFF");
CdisLabel = new JLabel("Center Distance: ");
LdisLabel = new JLabel("Left Distance: ");
RdisLabel = new JLabel("Right Distance: ");
driveDirection = new JLabel("STOP");
driveDirection.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
camLabel = new JLabel("Camera Rotation ON");
Box drive = Box.createVerticalBox(), distance = Box.createVerticalBox(),
status = Box.createVerticalBox(), environment = Box.createVerticalBox();
Box controlBox = Box.createHorizontalBox();
JPanel directionPanel = new JPanel(new GridLayout(3, 3));
directionPanel.add(new JLabel());
directionPanel.add(forwardBut);
directionPanel.add(new JLabel());
directionPanel.add(leftBut);
directionPanel.add(stopBut);
directionPanel.add(rightBut);
directionPanel.add(new JLabel());
directionPanel.add(backBut);
directionPanel.add(new JLabel());
controlBox.add(speedSlide);
controlBox.add(Box.createHorizontalStrut(10));
controlBox.add(directionPanel);
controlBox.add(Box.createHorizontalStrut(10));
drive.add(autoManBut);
drive.add(Box.createVerticalStrut(10));
drive.add(controlBox);
drive.add(Box.createVerticalStrut(10));
drive.add(driveDirection);
drive.add(Box.createVerticalStrut(10));
distance.add(Box.createVerticalStrut(10));
distance.add(CdisLabel);
distance.add(Box.createVerticalStrut(10));
distance.add(LdisLabel);
distance.add(Box.createVerticalStrut(10));
distance.add(RdisLabel);
JPanel alarmPanel = new JPanel(new FlowLayout(10)),
lightPanel = new JPanel(new FlowLayout(10)),
camPanel = new JPanel(new FlowLayout(10));
alarmPanel.add(alarmBut);
alarmPanel.add(alarmLabel);
lightPanel.add(lightBut);
lightPanel.add(lightLabel);
camPanel.add(camBut);
camPanel.add(camLabel);
status.add(Box.createVerticalStrut(10));
status.add(alarmPanel);
status.add(Box.createVerticalStrut(10));
status.add(lightPanel);
status.add(Box.createVerticalStrut(10));
status.add(camPanel);
environment.add(tempLabel);
environment.add(Box.createVerticalStrut(10));
container = this.getContentPane();
GridLayout layout = new GridLayout(2, 2);
layout.setHgap(20);
layout.setVgap(20);
container.setLayout(layout);
container.add(status);
container.add(distance);
container.add(environment);
container.add(drive);
// start serial receive
SERIAL.addListener(new ReceiveData());
SerialConfig config = new SerialConfig();
config.device("/dev/ttyACM0")
.baud(Baud._9600)
.dataBits(DataBits._8)
.parity(Parity.NONE)
.stopBits(StopBits._1)
.flowControl(FlowControl.NONE);
SERIAL.open(config);
// configure motor driver
motorLeft1 = GPIO.provisionDigitalOutputPin(RaspiPin.GPIO_22, PinState.LOW);
motorLeft2 = GPIO.provisionDigitalOutputPin(RaspiPin.GPIO_21, PinState.LOW);
motorRight1 = GPIO.provisionDigitalOutputPin(RaspiPin.GPIO_27, PinState.LOW);
motorRight2 = GPIO.provisionDigitalOutputPin(RaspiPin.GPIO_25, PinState.LOW);
SoftPwm.softPwmCreate(SPEED_PIN, 0, 255);
SoftPwm.softPwmWrite(SPEED_PIN, 255);
// start camera thread
camera = new Thread(new Camera());
camera.start();
// start auto avoidance thread
avoidance = new Thread(new Avoidance());
avoidance.start();
// start GUI
this.setSize(new Dimension(700, 700));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setFocusable(true);
this.setVisible(true);
}
/**
* change motor to turn right position and wait 0.5 second
*
* @throws InterruptedException
*/
private final void turnRight() {
motorRight1.low();
motorRight2.high();
motorLeft1.high();
motorLeft2.low();
driveDirection.setText("RIGHT");
}
/**
* change motor to turn left position and wait 0.5 second
*
* @throws InterruptedException
*/
private final void turnLeft() {
motorRight1.high();
motorRight2.low();
motorLeft1.low();
motorLeft2.high();
driveDirection.setText("LEFT");
}
/**
* change motor to drive forward position
*/
private final void forward() {
motorRight1.high();
motorRight2.low();
motorLeft1.high();
motorLeft2.low();
driveDirection.setText("FORWARD");
}
/**
* change motor to back off position and wait 0.5 second
*
* @throws InterruptedException
*/
private final void backOff() {
motorRight1.low();
motorRight2.high();
motorLeft1.low();
motorLeft2.high();
driveDirection.setText("BACKOFF");
}
/**
* stop the motor
*/
private final void stop() {
motorRight1.low();
motorRight2.low();
motorLeft1.low();
motorLeft2.low();
driveDirection.setText("STOP");
}
/**
* change motor speed (0-255)
*
* @param speed target motor speed level (0-5)
*/
private final void changeSpeed(int level) {
SoftPwm.softPwmWrite(SPEED_PIN, level * 51);
}
/**
* execute the given command
*
* @param cmd the command to be executed
*/
private final void executeCommand(String cmd) {
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException io) {
io.printStackTrace();
}
}
/**
* send specified data through serial
*
* @param data data to be sent
*/
private final void sendData(byte data) {
try {
SERIAL.write(data);
} catch (IOException io) {
io.printStackTrace();
}
}
/**
* Receive data from serial port
*/
private final class ReceiveData implements SerialDataEventListener {
/**
* 0: center distance
* 1: front-left distance
* 2: front-right distance
* 3: temperature
*/
private String[] data;
@Override
public void dataReceived(SerialDataEvent event) {
try {
// receive data
data = event.getString(Charset.defaultCharset()).trim().replaceAll("\\s", "").split(":");
for (int n = 0; n < data.length; n++) {
switch (data[n]) {
// distance data
case "d":
Cdistance = Integer.parseInt(data[n + 1]);
Ldistance = Integer.parseInt(data[n + 2]);
Rdistance = Integer.parseInt(data[n + 3]);
CdisLabel.setText("Center Distance: " + Cdistance);
LdisLabel.setText("Left Distance: " + Ldistance);
RdisLabel.setText("Right Distance: " + Rdistance);
n += 3;
break;
// temperature data
case "t":
temperature = Integer.parseInt(data[n + 1]);
tempLabel.setText("Temperature: " + temperature);
n++;
break;
// front light status
case "L":
int litStatus = Integer.parseInt(data[n + 1]);
if (litStatus == 0) {
lightLabel.setText("Light OFF");
} else if (litStatus == 1) {
lightLabel.setText("Light ON");
}
n++;
break;
// alarm status
case "A":
int alarmStatus = Integer.parseInt(data[n + 1]);
if (alarmStatus == 0) {
alarmLabel.setText("Alarm OFF");
} else if (alarmStatus == 1) {
alarmLabel.setText("Alarm ON");
}
n++;
break;
// camera rotation status
case "C":
int camStatus = Integer.parseInt(data[n + 1]);
if (camStatus == 0) {
camLabel.setText("Camera Rotation OFF");
} else if (camStatus == 1) {
camLabel.setText("Camera Rotation ON");
}
n++;
break;
}
}
} catch (IOException io) {
io.printStackTrace();
} catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
}
}
}
private final class Camera implements Runnable {
@Override
public void run() {
ArrayList<String> fileNames = new ArrayList<String>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
Date date;
String fileName;
try {
while (true) {
// name video file with date and time
date = new Date();
fileName = "vid-" + dateFormat.format(date) + ".h264";
// start recording
executeCommand(startInstruction + fileName);
fileNames.add(fileName);
// wait 30 minutes
Thread.sleep(1800000);
// end recording
executeCommand(endInstruction);
// if there is more than 10 files, delete the earliest one
if (fileNames.size() > 10) {
executeCommand("rm -rf /home/pi/Videos/" + fileNames.get(0));
}
Thread.sleep(100);
}
} catch (InterruptedException itr) {
executeCommand(endInstruction);
}
}
} // end Camera
private final class Avoidance implements Runnable {
@Override
public void run() {
try {
while (true) {
while (onAvoid) {
// if obstacle in front, check other route
if (Cdistance < 15 || Ldistance <= 2 || Rdistance <= 2) {
stop();
// if no way to go, back off
if (!checkRoute()) {
back();
}
} else {
// forward if there is no obstacle in front
forward();
}
Thread.sleep(50);
}
Thread.sleep(50);
}
} catch (InterruptedException itr) {
}
}
private final boolean checkRoute() throws InterruptedException {
boolean left = false, right = false;
// check left status
if (Ldistance >= 5 && Ldistance <= 2000) {
left = true;
}
// check right status
if (Rdistance >= 5 && Rdistance <= 2000) {
right = true;
}
// if right available, turn right
if (left && Rdistance <= Ldistance) {
turnRight();
Thread.sleep(500);
}
// if only left available, turn left
else if (right && Ldistance <= Rdistance) {
turnLeft();
Thread.sleep(500);
}
// if no available direction to turn
else {
return false;
}
return true;
}
private final void back() throws InterruptedException {
while (true) {
// start back off
backOff();
Thread.sleep(200);
// if there is a way to go in front, stop backing off
if (checkRoute()) {
break;
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// actions when press different buttons
if (e.getSource() == lightBut) {
sendData(LIGHT_SWITCH);
} else if (e.getSource() == camBut) {
sendData(CAM_SWITCH);
} else if (e.getSource() == alarmBut) {
sendData(ALARM_SWITCH);
} else if (e.getSource() == autoManBut) {
if (onAvoid == true) {
onAvoid = false;
stop();
forwardBut.setEnabled(true);
backBut.setEnabled(true);
leftBut.setEnabled(true);
rightBut.setEnabled(true);
stopBut.setEnabled(true);
speedSlide.setEnabled(true);
} else {
onAvoid = true;
forwardBut.setEnabled(false);
backBut.setEnabled(false);
leftBut.setEnabled(false);
rightBut.setEnabled(false);
stopBut.setEnabled(false);
speedSlide.setEnabled(false);
}
} else if (e.getSource() == forwardBut) {
forward();
} else if (e.getSource() == backBut) {
backOff();
} else if (e.getSource() == leftBut) {
turnLeft();
} else if (e.getSource() == rightBut) {
turnRight();
} else if (e.getSource() == stopBut) {
stop();
}
}
/**
* handle shut down operations, shut down GPIO controls
*/
private final void shutDown() {
Runtime run = Runtime.getRuntime();
run.addShutdownHook(new Thread() {
@Override
public void run() {
motorLeft1.low();
motorLeft2.low();
motorRight1.low();
motorRight2.low();
SoftPwm.softPwmStop(SPEED_PIN);
camera.interrupt();
avoidance.interrupt();
GPIO.shutdown();
}
});
}
@Override
public void stateChanged(ChangeEvent e) {
if (e.getSource() == speedSlide) {
changeSpeed(speedSlide.getValue());
}
}
}
| 29.542553 | 106 | 0.499357 |
3be4dd8dc0d4147680f28d285b61dc11e064ee52 | 4,026 | package com.github.fromi.chess.material;
import static com.github.fromi.chess.material.Piece.Color.BLACK;
import static com.github.fromi.chess.material.Piece.Color.WHITE;
import static com.github.fromi.chess.material.util.Squares.*;
import org.junit.Rule;
import org.junit.Test;
import com.github.fromi.chess.material.util.Boards;
@SuppressWarnings("JavacQuirks")
public class PawnTest {
// Pawn position
private static final Boolean O = false;
// Invalid moves
private static final Boolean _ = false;
// Valid moves
private static final Boolean X = true;
@Rule
public final MoveRule moveRule = new MoveRule();
@Test
public void pawn_can_move_one_step_forward() {
Pawn pawn = new Pawn(WHITE, Boards.empty(), D4);
Boolean[] rank8 = {_, _, _, _, _, _, _, _};
Boolean[] rank7 = {_, _, _, _, _, _, _, _};
Boolean[] rank6 = {_, _, _, _, _, _, _, _};
Boolean[] rank5 = {_, _, _, X, _, _, _, _};
Boolean[] rank4 = {_, _, _, O, _, _, _, _};
Boolean[] rank3 = {_, _, _, _, _, _, _, _};
Boolean[] rank2 = {_, _, _, _, _, _, _, _};
Boolean[] rank1 = {_, _, _, _, _, _, _, _};
Boolean[][] validMoves = {rank1, rank2, rank3, rank4, rank5, rank6, rank7, rank8};
moveRule.with(pawn).expect(validMoves);
}
@Test
public void for_black_pawn_forward_is_the_other_way() {
Pawn pawn = new Pawn(BLACK, Boards.empty(), D4);
Boolean[] rank8 = {_, _, _, _, _, _, _, _};
Boolean[] rank7 = {_, _, _, _, _, _, _, _};
Boolean[] rank6 = {_, _, _, _, _, _, _, _};
Boolean[] rank5 = {_, _, _, _, _, _, _, _};
Boolean[] rank4 = {_, _, _, O, _, _, _, _};
Boolean[] rank3 = {_, _, _, X, _, _, _, _};
Boolean[] rank2 = {_, _, _, _, _, _, _, _};
Boolean[] rank1 = {_, _, _, _, _, _, _, _};
Boolean[][] validMoves = {rank1, rank2, rank3, rank4, rank5, rank6, rank7, rank8};
moveRule.with(pawn).expect(validMoves);
}
@Test
public void white_pawn_can_move_twice_on_first_move() {
Pawn pawn = new Pawn(WHITE, Boards.empty(), B2);
Boolean[] rank8 = {_, _, _, _, _, _, _, _};
Boolean[] rank7 = {_, _, _, _, _, _, _, _};
Boolean[] rank6 = {_, _, _, _, _, _, _, _};
Boolean[] rank5 = {_, _, _, _, _, _, _, _};
Boolean[] rank4 = {_, X, _, _, _, _, _, _};
Boolean[] rank3 = {_, X, _, _, _, _, _, _};
Boolean[] rank2 = {_, O, _, _, _, _, _, _};
Boolean[] rank1 = {_, _, _, _, _, _, _, _};
Boolean[][] validMoves = {rank1, rank2, rank3, rank4, rank5, rank6, rank7, rank8};
moveRule.with(pawn).expect(validMoves);
}
@Test
public void black_pawn_can_move_twice_on_first_move() {
Pawn pawn = new Pawn(BLACK, Boards.empty(), C7);
Boolean[] rank8 = {_, _, _, _, _, _, _, _};
Boolean[] rank7 = {_, _, O, _, _, _, _, _};
Boolean[] rank6 = {_, _, X, _, _, _, _, _};
Boolean[] rank5 = {_, _, X, _, _, _, _, _};
Boolean[] rank4 = {_, _, _, _, _, _, _, _};
Boolean[] rank3 = {_, _, _, _, _, _, _, _};
Boolean[] rank2 = {_, _, _, _, _, _, _, _};
Boolean[] rank1 = {_, _, _, _, _, _, _, _};
Boolean[][] validMoves = {rank1, rank2, rank3, rank4, rank5, rank6, rank7, rank8};
moveRule.with(pawn).expect(validMoves);
}
/*
@Test
public void pawn_only_attack_forward_diagonally() {
assertTrue(whitePawn.attackAllowed(E2, D3));
assertTrue(whitePawn.attackAllowed(E2, F3));
assertFalse(whitePawn.attackAllowed(E2, D1));
assertFalse(whitePawn.attackAllowed(E2, F1));
assertFalse(whitePawn.attackAllowed(E2, E3));
assertFalse(whitePawn.attackAllowed(E2, E4));
assertFalse(whitePawn.attackAllowed(E2, D2));
assertFalse(whitePawn.attackAllowed(E2, F2));
}
@Test
public void test_to_string() {
assertThat(whitePawn.toString(), equalTo("WHITE PAWN"));
}
*/
} | 39.470588 | 90 | 0.5539 |
cbf41c5f56061ac693faa4a147542e88b4907976 | 294 | package algo.tzashinorpu.SecondRound.Chapter07;
import org.junit.jupiter.api.Test;
class permute_047Test {
@Test
void permuteUnique() {
permute_047 instance = new permute_047();
int[] ints = {1, 2, 1};
System.out.println(instance.permuteUnique(ints));
}
} | 22.615385 | 57 | 0.663265 |
d3be570d4a0df85640343d967a8781e04c607736 | 7,265 | /*
* Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
*
* License for BK-BASE 蓝鲸基础平台:
* --------------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tencent.bk.base.dataflow.udf.tests.hive;
import com.klarna.hiverunner.HiveShell;
import com.klarna.hiverunner.StandaloneHiveRunner;
import com.klarna.hiverunner.annotations.HiveSQL;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@Ignore
@RunWith(StandaloneHiveRunner.class)
public class HiveSqlTests {
@HiveSQL(files = {})
private HiveShell shell;
@Before
public void setupSourceDatabase() {
shell.execute("CREATE DATABASE source_db");
shell.execute(new StringBuilder()
.append("CREATE TABLE source_db.test_table (")
.append("year STRING, value INT")
.append(")")
.toString());
}
@Test
public void testMax() {
shell.insertInto("source_db", "test_table")
.withColumns("year", "value")
.addRow("2014", 3)
.addRow("2014", 4)
.addRow("2015", 2)
.addRow("2015", 5)
.commit();
List<Object[]> result = shell.executeStatement("select max(value) as cc from source_db.test_table");
Assert.assertArrayEquals(new Object[]{5}, result.get(0));
}
@Test
public void testUdf() {
shell.insertInto("source_db", "test_table")
.withColumns("year", "value")
.addRow("2014", 3)
.addRow("2014", 4)
.addRow("2015", 2)
.addRow("2015", 5)
.commit();
shell.execute(
"CREATE TEMPORARY FUNCTION test_udf "
+ "AS 'com.tencent.bk.base.dataflow.udf.codegen.hive.HiveJavaTestUdf'");
List<Object[]> result = shell.executeStatement("select test_udf(year, year) as cc from source_db.test_table");
Assert.assertArrayEquals(new Object[]{"test___2014___2014"}, result.get(0));
Assert.assertArrayEquals(new Object[]{"test___2015___2015"}, result.get(2));
}
@Test
public void testPyUdf() {
shell.insertInto("source_db", "test_table")
.withColumns("year", "value")
.addRow("2014", 3)
.addRow("2014", 4)
.addRow("2015", 2)
.addRow("2015", 5)
.commit();
shell.execute(
"CREATE TEMPORARY FUNCTION test_udf AS 'com.tencent.bk.base.dataflow.udf.codegen.hive.HivePyTestUdf'");
List<Object[]> result = shell.executeStatement("select test_udf(year, year) as cc from source_db.test_table");
Assert.assertArrayEquals(new Object[]{"test___2014___2014"}, result.get(0));
Assert.assertArrayEquals(new Object[]{"test___2015___2015"}, result.get(2));
}
@Test
public void testUdtf() {
shell.insertInto("source_db", "test_table")
.withColumns("year", "value")
.addRow("this is a simple string.", 3)
.commit();
shell.execute(
"CREATE TEMPORARY FUNCTION test_udtf "
+ "AS 'com.tencent.bk.base.dataflow.udf.codegen.hive.HiveJavaTestUdtf'");
List<Object[]> result = shell
.executeStatement("select test_udtf(year, ' ') as (cc, dd) from source_db.test_table");
Assert.assertArrayEquals(new Object[]{"this", 4}, result.get(0));
}
@Test
public void testPyUdtf() {
shell.insertInto("source_db", "test_table")
.withColumns("year", "value")
.addRow("this is a simple string.", 3)
.commit();
shell.execute(
"CREATE TEMPORARY FUNCTION test_udtf "
+ "AS 'com.tencent.bk.base.dataflow.udf.codegen.hive.HivePyTestUdtf'");
List<Object[]> result = shell
.executeStatement("select test_udtf(year, ' ') as (cc, dd) from source_db.test_table");
Assert.assertArrayEquals(new Object[]{"this", 4}, result.get(0));
}
@Test
public void testUdaf() {
shell.execute(new StringBuilder()
.append("CREATE TABLE source_db.test_table2 (")
.append("year STRING, value1 bigint, value2 INT")
.append(")")
.toString());
shell.insertInto("source_db", "test_table2")
.withColumns("year", "value1", "value2")
.addRow("this is a simple string.", 10L, 3)
.addRow("ddd", 11L, 5)
.commit();
shell.execute(
"CREATE TEMPORARY FUNCTION test_udaf "
+ "AS 'com.tencent.bk.base.dataflow.udf.codegen.hive.HiveJavaTestUdaf'");
List<Object[]> result = shell
.executeStatement("select test_udaf(value1, value2) as cc from source_db.test_table2");
Assert.assertArrayEquals(new Object[]{10.625}, result.get(0));
}
@Test
public void testPyUdaf() {
shell.execute(new StringBuilder()
.append("CREATE TABLE source_db.test_table2 (")
.append("year STRING, value1 bigint, value2 INT")
.append(")")
.toString());
shell.insertInto("source_db", "test_table2")
.withColumns("year", "value1", "value2")
.addRow("this is a simple string.", 10L, 3)
.addRow("ddd", 11L, 5)
.commit();
shell.execute(
"CREATE TEMPORARY FUNCTION test_udaf "
+ "AS 'com.tencent.bk.base.dataflow.udf.codegen.hive.HivePyTestUdaf'");
List<Object[]> result = shell
.executeStatement("select test_udaf(value1, value2) as cc from source_db.test_table2");
Assert.assertArrayEquals(new Object[]{10.625}, result.get(0));
}
}
| 40.814607 | 119 | 0.596696 |
492e6a35e8488332c474aaafe323a2b9998bf355 | 3,174 | package com.ferg.awful.user;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.SimpleHtmlSerializer;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import android.util.Log;
import java.util.HashMap;
import com.ferg.awful.constants.Constants;
import com.ferg.awful.network.NetworkUtils;
public class Profile {
public static final String TAG = "Profile";
private static final String USERNAME = "//dt[@class='author']";
private static final String REGISTERED = "//dd[@class='registered']";
private static final String AVATAR = "//dd[@class='title']//img";
private static final String INFO = "//td[@class='info']";
private String mUsername;
private String mRegistered;
private String mAvatar;
private String mInfo;
public String getUsername() {
return mUsername;
}
public void setUsername(String aUsername) {
mUsername = aUsername;
}
public String getRegistered() {
return mRegistered;
}
public void setRegistered(String aRegistered) {
mRegistered = aRegistered;
}
public String getAvatar() {
return mAvatar;
}
public void setAvatar(String aAvatar) {
mAvatar = aAvatar;
}
public String getInfo() {
return mInfo;
}
public void setInfo(String aInfo) {
mInfo = aInfo;
}
public static Profile withId(String aUserId) {
long time = System.currentTimeMillis();
Profile result = new Profile();
HashMap<String, String> params = new HashMap<String, String>();
params.put(Constants.PARAM_ACTION, "getinfo");
params.put(Constants.PARAM_USER_ID, aUserId);
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties properties = cleaner.getProperties();
properties.setOmitComments(true);
try {
TagNode response = NetworkUtils.get(Constants.FUNCTION_MEMBER, params);
Object[] nodeList = response.evaluateXPath(USERNAME);
if (nodeList.length > 0) {
result.setUsername(((TagNode) nodeList[0]).getText().toString().trim());
}
nodeList = response.evaluateXPath(REGISTERED);
if (nodeList.length > 0) {
result.setRegistered(((TagNode) nodeList[0]).getText().toString().trim());
}
nodeList = response.evaluateXPath(AVATAR);
if (nodeList.length > 0) {
result.setRegistered(((TagNode) nodeList[0]).getAttributeByName("src"));
}
nodeList = response.evaluateXPath(INFO);
if (nodeList.length > 0) {
SimpleHtmlSerializer serializer =
new SimpleHtmlSerializer(cleaner.getProperties());
result.setInfo(serializer.getAsString((TagNode) nodeList[0]));
}
} catch (XPatherException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Process Time: "+ (System.currentTimeMillis() - time));
return result;
}
}
| 29.943396 | 90 | 0.624134 |
923f5d510970247d55329da2dc5ff5dea2102588 | 260 | package org.sif.beans;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "org.sif.beans")
public class ApplicationContextTestConfigurer {
}
| 23.636364 | 60 | 0.838462 |
a7fd73b4e2ba34cbdccf39c48d380e3b124f345c | 510 | package drlc.generate.drc1.instruction.address;
import drlc.generate.drc1.DataInfo;
public abstract class InstructionALU extends InstructionAddress {
public InstructionALU(DataInfo info) {
super(info);
}
@Override
public boolean isCurrentRegisterValueModified() {
return true;
}
@Override
public boolean isCurrentRegisterValueUsed() {
return false;
}
@Override
public boolean isDataFromMemory() {
return true;
}
@Override
public boolean isDataToMemory() {
return false;
}
}
| 16.451613 | 65 | 0.74902 |
6156a17d7e2bde97b77a9dd17ace70d7ef12aeec | 362 | package net.schattenkind.androidLove.utils;
public class Rectangle {
public float left;
public float top;
public float width;
public float height;
public Rectangle() {
this(0f, 0f, 0f, 0f);
}
public Rectangle(float left, float top, float width, float height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
}
| 18.1 | 69 | 0.696133 |
6d3dc5f02a5e655300207a92e301aab661d8864b | 949 | /**
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* https://github.com/javaee/tutorial-examples/LICENSE.txt
*/
package javaeetutorial.checkoutmodule;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
/**
* Backing bean for index page.
*/
@Named
@SessionScoped
public class CheckoutBean implements Serializable {
private static final long serialVersionUID = 1L;
int numItems = 3;
double cost = 101.25;
public int getNumItems() {
return numItems;
}
public void setNumItems(int numItems) {
this.numItems = numItems;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
}
| 23.146341 | 77 | 0.658588 |
5423a19fb152973625461b6c1784c1d340cf0b79 | 1,735 | package org.amv.vertx.spring.mqtt;
import io.vertx.mqtt.MqttServerOptions;
import io.vertx.rxjava.core.Vertx;
import io.vertx.rxjava.mqtt.MqttServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static java.util.Objects.requireNonNull;
@Slf4j
@Configuration
@ConditionalOnClass(MqttServer.class)
@EnableConfigurationProperties(VertxMqttProperties.class)
@ConditionalOnProperty(value = "vertx.mqtt.enabled", havingValue = "true")
public class VertxMqttServerAutoConfig {
private final VertxMqttProperties properties;
@Autowired
public VertxMqttServerAutoConfig(VertxMqttProperties properties) {
this.properties = requireNonNull(properties);
}
@Bean(destroyMethod = "close")
@ConditionalOnBean(Vertx.class)
@ConditionalOnMissingBean(MqttServer.class)
public MqttServer rxMqttServer(Vertx vertx) {
return MqttServer.create(vertx, mqttServerOptions());
}
@Bean
@ConditionalOnMissingBean(MqttServerOptions.class)
public MqttServerOptions mqttServerOptions() {
return new MqttServerOptions()
.setHost(properties.getHost())
.setPort(properties.getPort());
}
}
| 36.145833 | 81 | 0.794813 |
3030e5c53ddad9a8347bd5ed264fef5a74612d85 | 576 | package org.logspin.extendChartForJava;
import com.github.abel533.echarts.series.Line;
import org.logspin.data.DataResource;
@SuppressWarnings("unused")
public class ELine extends Line implements SeriesExtend {
private DataResource dataResource = DataResource.Spin;
private String key = null;
@Override
public String getKey() {
return key;
}
public void key(String key) {
this.key = key;
dataResource = DataResource.Log;
}
@Override
public DataResource getDateResource() {
return dataResource;
}
}
| 21.333333 | 58 | 0.689236 |
35962eeb5ad98a3863fee1e02144acfd6175e710 | 474 | /*
Copyright 2019 - 2021 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
*/
package bootjson.session.gemfire;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.geode.config.annotation.EnableClusterAware;
@SpringBootApplication
@EnableClusterAware
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| 22.571429 | 70 | 0.812236 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.