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
31f14d6f00ed29961ecbd2c0607864bfafa22647
2,086
package com.sdw.soft.cocoim.cli; import com.google.common.base.Splitter; import com.sdw.soft.cocoim.protocol.ChatRequestPacket; import com.sdw.soft.cocoim.protocol.LoginRequestPacket; import com.sdw.soft.cocoim.protocol.Packet; import com.sdw.soft.cocoim.utils.LoginHelper; import io.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Scanner; /** * @author shangyd * @version 1.0.0 * @date 2019-11-03 15:49 * @description **/ public class ClientEndpoint implements Runnable{ private static final Logger logger = LoggerFactory.getLogger(ClientEndpoint.class); private Channel channel; public ClientEndpoint(Channel channel) { this.channel = channel; } public enum MsgCommand { LOGIN("login"),CHAT("chat"); private String cmd; MsgCommand(String cmd) { this.cmd = cmd; } } @Override public void run() { Scanner sc = new Scanner(System.in, "UTF-8"); while (!Thread.interrupted()) { // if (LoginHelper.isLogin(channel)) { String line = sc.nextLine(); logger.info("enter:{}", line); List<String> list = Splitter.on("::").omitEmptyStrings().splitToList(line); if (list.size() == 2) { switch (list.get(0)) { case "login": LoginRequestPacket login = new LoginRequestPacket(); login.setUserId(1l); login.setUserName("Admin"); login.setSerialization((byte)1); login.setVersion((byte) 1); channel.writeAndFlush(login); break; case "chat": ChatRequestPacket chat = new ChatRequestPacket(); chat.setContent(list.get(1)); channel.writeAndFlush(chat); break; } } // } } } }
27.813333
87
0.549856
4b14ad9946b9b3d6a79c8880de51f03dd4bdc21e
853
package task_c; import java.util.Random; public class Monk implements Comparable { private Integer energy; private String monastery; public Monk() { Random r = new Random(); energy = r.nextInt(100); monastery = (r.nextInt(2) == 0) ? "Guan-un" : "Guan-yan"; } @Override public String toString() { return "Monk from " + monastery +" with energy: "+energy; } public int compareTo(Object o) { Monk other = (Monk)o; if(this.energy > other.energy) { return 1; } else if (this.energy < other.energy){ return -1; } else { return 0; } } static Monk max(Monk first, Monk second){ if(first.energy > second.energy){ return first; } else { return second; } } }
22.447368
65
0.52755
851f44a43c30b2a3cb876e16079182410cdf171a
3,389
package ca.bc.gov.open.jag.efilingdiligenclientstarter; import ca.bc.gov.open.efilingdiligenclient.diligen.DiligenAuthService; import ca.bc.gov.open.efilingdiligenclient.diligen.DiligenProperties; import ca.bc.gov.open.efilingdiligenclient.diligen.DiligenService; import ca.bc.gov.open.jag.efilingdiligenclient.api.DocumentsApi; import ca.bc.gov.open.jag.efilingdiligenclient.api.HealthCheckApi; import ca.bc.gov.open.jag.efilingdiligenclient.api.handler.ApiClient; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AutoConfigurationTest { private ApplicationContextRunner context; @Test @DisplayName("ok: with valid configuration should produce beans") public void validConfigurationShouldProduceBeans() { context = new ApplicationContextRunner() .withUserConfiguration(AutoConfiguration.class) .withPropertyValues( "jag.efiling.diligen.basePath=http://test.com " + "jag.efiling.diligen.usename=test " + "jag.efiling.diligen.password=test " + "jag.efiling.diligen.projectIdentifier=2") .withUserConfiguration(DiligenProperties.class); context.run(it -> { assertThat(it).hasSingleBean(ApiClient.class); assertThat(it).hasSingleBean(HealthCheckApi.class); assertThat(it).doesNotHaveBean(DiligenHealthIndicator.class); assertThat(it).hasSingleBean(RestTemplate.class); assertThat(it).hasSingleBean(DiligenAuthService.class); assertThat(it).hasSingleBean(DiligenService.class); assertThat(it).hasSingleBean(DocumentsApi.class); }); } @Test @DisplayName("ok: with valid configuration and healthchecks enabled should produce beans") public void validConfigurationPlusHealthCheckShouldProduceBeans() { context = new ApplicationContextRunner() .withUserConfiguration(AutoConfiguration.class) .withPropertyValues( "jag.efiling.diligen.basePath=http://test.com", "jag.efiling.diligen.health.enabled=true") .withUserConfiguration(DiligenProperties.class); context.run(it -> { assertThat(it).hasSingleBean(ApiClient.class); assertThat(it).hasSingleBean(HealthCheckApi.class); assertThat(it).hasSingleBean(DiligenHealthIndicator.class); }); } @Test @DisplayName("error: with invalid configuration should throw configuration exceptions") public void invalidConfigurationShouldThrowDiligenConfigurationException() { context = new ApplicationContextRunner() .withUserConfiguration(AutoConfiguration.class) .withUserConfiguration(DiligenProperties.class); org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, () -> { context.run(it -> { it.getBean(HealthCheckApi.class); }); }); } }
37.241758
94
0.689584
2eb6313046e5be817681a3ead49114259a46cb7b
826
package top.chenqwwq.leetcode.archive.$20200418.common; import lombok.extern.slf4j.Slf4j; /** * @author CheNbXxx * @description * @email chenbxxx@gmail.con * @date 2019/1/11 14:32 */ @Slf4j public class LeetCode746 { public static void main(String[] args) { log.info(new Solution().minCostClimbingStairs(new int[]{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}) + ""); } static class Solution { public int minCostClimbingStairs(int[] cost) { int[] dpSign = new int[cost.length]; dpSign[0] = cost[0]; dpSign[1] = cost[1]; for (int i = 2; i < cost.length; i++) { dpSign[i] = Math.min(dpSign[i - 1], dpSign[i - 2]) + cost[i]; } return Math.min(dpSign[cost.length - 2], dpSign[cost.length - 1]); } } }
25.8125
107
0.558111
7bad1a52fb3325489f10ac6b35a7022b0549478d
135
/** * Created by Ramesh Ponnada on 5/20/15. */ public class HazelcastTest { public void setup(){ // HazelcastIns } }
13.5
40
0.592593
43b423719aee1e064ee64c15e7adcceb57c40726
147
package controllers.getters; public class GetterIssue { public Integer issue; public Integer task; public GetterCommand[] commands; }
18.375
36
0.741497
d6920b24a176e8042f8995b99de7be34c80c65e4
2,418
package dev.arthomnix.spaghettitrees.mixin; import net.minecraft.block.BlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.intprovider.IntProvider; import net.minecraft.world.TestableWorld; import net.minecraft.world.gen.feature.TreeFeature; import net.minecraft.world.gen.feature.TreeFeatureConfig; import net.minecraft.world.gen.foliage.BlobFoliagePlacer; import net.minecraft.world.gen.foliage.BushFoliagePlacer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Random; import java.util.function.BiConsumer; @Mixin(BushFoliagePlacer.class) public class BushFoliagePlacerMixin extends BlobFoliagePlacer { public BushFoliagePlacerMixin(IntProvider radius, IntProvider offset, int height) { super(radius, offset, height); } /** * Default FoliagePlacers get a new BlockState from the BlockStateProvider for every block. * If we want to randomise the block, this means we end up with every block being random, even within the same bush. * This makes BushFoliagePlacer generate the same foliage block for every block in the bush. */ @Redirect(method = "generate", at = @At(value = "INVOKE", target = "net/minecraft/world/gen/foliage/BushFoliagePlacer.generateSquare (Lnet/minecraft/world/TestableWorld;Ljava/util/function/BiConsumer;Ljava/util/Random;Lnet/minecraft/world/gen/feature/TreeFeatureConfig;Lnet/minecraft/util/math/BlockPos;IIZ)V")) private void randomiseFoliageTypePerBush(BushFoliagePlacer instance, TestableWorld testableWorld, BiConsumer<BlockPos, BlockState> replacer, Random random, TreeFeatureConfig treeFeatureConfig, BlockPos blockPos, int r, int y, boolean giantTrunk) { BlockState foliageBlock = treeFeatureConfig.foliageProvider.getBlockState(random, blockPos); BlockPos.Mutable mutable = new BlockPos.Mutable(); for (int j = -r; j <= r + (giantTrunk ? 1 : 0); ++j) { for (int k = -r; k <= r + (giantTrunk ? 1 : 0); ++k) { if (!isPositionInvalid(random, j, y, k, r, giantTrunk)) { mutable.set(blockPos, j, y, k); if (TreeFeature.canReplace(testableWorld, mutable)) { replacer.accept(mutable, foliageBlock); } } } } } }
52.565217
284
0.720844
53872a1bdcf3c762875d06f215d0100dd861f9f0
2,229
package net.spizzer.aoc2019.helpers.maze.keys; import net.spizzer.aoc2019.helpers.maze.GraphNode; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class KeyMazeNode implements GraphNode<KeyMazeNode> { private final List<Character> positions; private final Set<Character> keys; public KeyMazeNode(int count) { this.positions = IntStream.range(0, count) .mapToObj(c -> Character.forDigit(c, 10)) .collect(Collectors.toList()); this.keys = Set.of(); } private KeyMazeNode(List<Character> name, Set<Character> keys) { this.positions = List.copyOf(name); this.keys = Set.copyOf(keys); } boolean canMoveTo(Character newPosition) { return !Character.isUpperCase(newPosition) || keys.contains(Character.toLowerCase(newPosition)); } KeyMazeNode moveTo(int index, Character newPosition) { List<Character> newPositions = new ArrayList<>(positions); newPositions.set(index, newPosition); HashSet<Character> newKeys = new HashSet<>(keys); if(Character.isLowerCase(newPosition)){ newKeys.add(newPosition); } return new KeyMazeNode(newPositions, newKeys); } @Override public KeyMazeNode getKey() { return this; } Character getPosition(int i) { return positions.get(i); } int getPositionSize() { return positions.size(); } Set<Character> getKeys() { return keys; } private boolean equals(KeyMazeNode other) { return this.positions.equals(other.positions) && keys.containsAll(other.keys) && other.keys.containsAll(keys); } @Override public boolean equals(Object other) { return other instanceof KeyMazeNode && equals((KeyMazeNode) other); } @Override public String toString() { return "(" + positions.stream().map(c -> "" + c).collect(Collectors.joining(",")) + ")" + "-" + keys.stream().map(c -> "" + c).collect(Collectors.joining("")); } @Override public int hashCode() { return Objects.hash(positions, keys); } }
27.8625
104
0.62629
7fd61fbe1c59379d5520b4f2c93f4d30e8f8f0b3
2,388
/* * * Copyright 2015 Jonathan Shook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.nosqlbench.virtdata.library.basics.shared.nondeterministic.to_int; import io.nosqlbench.nb.api.metadata.Indexed; import io.nosqlbench.virtdata.api.annotations.Categories; import io.nosqlbench.virtdata.api.annotations.Category; import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper; import java.util.function.LongToIntFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Matches a digit sequence in the current thread name and caches it in a thread local. * This allows you to use any intentionally indexed thread factories to provide an analogue for * concurrency. Note that once the thread number is cached, it will not be refreshed. This means * you can't change the thread name and get an updated value. */ @ThreadSafeMapper @Categories({Category.state}) public class ThreadNum implements LongToIntFunction { private static final Pattern pattern = Pattern.compile("^.*?(\\d+).*$"); private final ThreadLocal<Integer> threadLocalInt = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { if (Thread.currentThread() instanceof Indexed ) { return ((Indexed)Thread.currentThread()).getIndex(); } Matcher matcher = pattern.matcher(Thread.currentThread().getName()); if (matcher.matches()) { return Integer.valueOf(matcher.group(1)); } else { throw new RuntimeException( "Unable to match a digit sequence in thread name:" + Thread.currentThread().getName() ); } } }; @Override public int applyAsInt(long value) { { return threadLocalInt.get(); } } }
35.641791
109
0.681323
60d703d39939399001d3e68af0aa74ece09340d7
695
package p005cm.aptoide.p006pt.comments; import p005cm.aptoide.p006pt.dataprovider.model.p009v7.ListComments; import p005cm.aptoide.p006pt.dataprovider.model.p009v7.Review; import p026rx.p027b.C0132p; /* renamed from: cm.aptoide.pt.comments.a */ /* compiled from: lambda */ public final /* synthetic */ class C2649a implements C0132p { /* renamed from: a */ private final /* synthetic */ Review f5811a; public /* synthetic */ C2649a(Review review) { this.f5811a = review; } public final Object call(Object obj) { Review review = this.f5811a; ListFullReviewsSuccessRequestListener.m7314a(review, (ListComments) obj); return review; } }
28.958333
81
0.703597
c6c62932556714c7a289cec336d5f0d1e0e19de0
705
package es.ujaen.rlc00008.gnbwallet.data.source.net; /** * Created by Ricardo Lechuga on 22/1/16. */ public class Meta { public static final int CODE_OK = 0; private int code = -1; private String errorDetail; private String errorMessage; public Meta() { } ///// GETTERS AND SETTERS ///// public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getErrorDetail() { return errorDetail; } public void setErrorDetail(String errorDetail) { this.errorDetail = errorDetail; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
16.785714
52
0.703546
6cb90325b031835e480ab07284d44441f9191099
5,213
/** * FreightClassType.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.fedex.rate.stub; public class FreightClassType implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected FreightClassType(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _CLASS_050 = "CLASS_050"; public static final java.lang.String _CLASS_055 = "CLASS_055"; public static final java.lang.String _CLASS_060 = "CLASS_060"; public static final java.lang.String _CLASS_065 = "CLASS_065"; public static final java.lang.String _CLASS_070 = "CLASS_070"; public static final java.lang.String _CLASS_077_5 = "CLASS_077_5"; public static final java.lang.String _CLASS_085 = "CLASS_085"; public static final java.lang.String _CLASS_092_5 = "CLASS_092_5"; public static final java.lang.String _CLASS_100 = "CLASS_100"; public static final java.lang.String _CLASS_110 = "CLASS_110"; public static final java.lang.String _CLASS_125 = "CLASS_125"; public static final java.lang.String _CLASS_150 = "CLASS_150"; public static final java.lang.String _CLASS_175 = "CLASS_175"; public static final java.lang.String _CLASS_200 = "CLASS_200"; public static final java.lang.String _CLASS_250 = "CLASS_250"; public static final java.lang.String _CLASS_300 = "CLASS_300"; public static final java.lang.String _CLASS_400 = "CLASS_400"; public static final java.lang.String _CLASS_500 = "CLASS_500"; public static final FreightClassType CLASS_050 = new FreightClassType(_CLASS_050); public static final FreightClassType CLASS_055 = new FreightClassType(_CLASS_055); public static final FreightClassType CLASS_060 = new FreightClassType(_CLASS_060); public static final FreightClassType CLASS_065 = new FreightClassType(_CLASS_065); public static final FreightClassType CLASS_070 = new FreightClassType(_CLASS_070); public static final FreightClassType CLASS_077_5 = new FreightClassType(_CLASS_077_5); public static final FreightClassType CLASS_085 = new FreightClassType(_CLASS_085); public static final FreightClassType CLASS_092_5 = new FreightClassType(_CLASS_092_5); public static final FreightClassType CLASS_100 = new FreightClassType(_CLASS_100); public static final FreightClassType CLASS_110 = new FreightClassType(_CLASS_110); public static final FreightClassType CLASS_125 = new FreightClassType(_CLASS_125); public static final FreightClassType CLASS_150 = new FreightClassType(_CLASS_150); public static final FreightClassType CLASS_175 = new FreightClassType(_CLASS_175); public static final FreightClassType CLASS_200 = new FreightClassType(_CLASS_200); public static final FreightClassType CLASS_250 = new FreightClassType(_CLASS_250); public static final FreightClassType CLASS_300 = new FreightClassType(_CLASS_300); public static final FreightClassType CLASS_400 = new FreightClassType(_CLASS_400); public static final FreightClassType CLASS_500 = new FreightClassType(_CLASS_500); public java.lang.String getValue() { return _value_;} public static FreightClassType fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { FreightClassType enumeration = (FreightClassType) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static FreightClassType fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(FreightClassType.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://fedex.com/ws/rate/v24", "FreightClassType")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
50.61165
111
0.735661
1171e05b5784bbc2279757cad94bdfcf73b4721e
403
package one.innovation.digital.classes.person; import one.innovation.digital.classes.user.SuperUser; public class UserApp { public static void main(String[] args) { final var quackMan = new SuperUser("QuackMan", "1234"); quackMan.getLogin(); // quackMan.getPassword(); // Error: protected access // String clientName = quackMan.name; // Error: not public } }
26.866667
66
0.672457
e71ddb6508681929fffc4741bcc3c4c05ad016f4
1,884
package org.statemach.db.sql.postgres; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.statemach.db.jdbc.Vendor; import org.statemach.db.schema.ColumnInfo; import org.statemach.db.schema.ForeignKey; import org.statemach.db.schema.PrimaryKey; import org.statemach.db.schema.Schema; import io.vavr.collection.List; import io.vavr.collection.Map; @EnabledIfEnvironmentVariable(named = "TEST_DATABASE", matches = "POSTGRES") public class PostgresSchemaAccess_IntegrationTest { final PostgresSchemaAccess subject = new PostgresSchemaAccess(TestDB.jdbc, TestDB.schema); @BeforeAll static void setup() { TestDB.setup(); } @Test void getSchemaName() { // Execute String result = subject.getSchemaName(); // Verify assertEquals(TestDB.schema, result); } @Test void getAllTables() { // Execute Map<String, List<ColumnInfo>> result = subject.getAllTables(); // Verify assertEquals(TestSchema.ALL_TABLES, result); } @Test void getAllPrimaryKeys() { // Execute List<PrimaryKey> result = subject.getAllPrimaryKeys(); // Verify assertEquals(TestSchema.ALL_PRIMARY_KEYS, result.sortBy(p -> p.name)); } @Test void getAllForeignKeys() { // Execute List<ForeignKey> result = subject.getAllForeignKeys(); // Verify assertEquals(TestSchema.ALL_FOREIGN_KEYS, result.sortBy(f -> f.name)); } @Test void schema_from() { // Execute Schema result = Schema.from(subject); // Verify assertEquals(new Schema(Vendor.POSTGRES, TestDB.schema, TestSchema.ALL_TABLE_INFO_MAP), result); } }
25.808219
104
0.679406
37b6af06bfa980250065c9111a76dc669c392302
2,018
package ru.job4j.task; import java.util.Arrays; /** * Class Класс для реализации сортировок. * @author agavrikov * @since 07.07.2017 * @version 1 */ public class Sort { /** * Метод для сортировки массива слиянием. Решил реализовать и его. * * @param array - массив, который нужно отсортировать * @return отсортированный массив array */ public int[] mergeSort(int[] array) { int len = array.length; //получаем длинну массива if (len < 2) { return array; // останавливаем рекурсию } int middle = len / 2; int[] array1 = mergeSort(Arrays.copyOfRange(array, 0, middle)); int[] array2 = mergeSort(Arrays.copyOfRange(array, middle, len)); return mergeSortArrays(array1, array2); } /** * Метод для слияния двух отсортированных массивов в 1 отсортированный. * * @param array1 - первый массив * @param array2 - второй массив * @return слитый отсортированный массив */ public int[] mergeSortArrays(int[] array1, int[] array2) { int countElements = array1.length + array2.length; int[] resultArray = new int[countElements]; int curIndexArray1 = 0; int curIndexArray2 = 0; for (int i = 0; i < countElements; i++) { if (curIndexArray1 < array1.length && curIndexArray2 < array2.length) { if (array1[curIndexArray1] < array2[curIndexArray2]) { resultArray[i] = array1[curIndexArray1]; curIndexArray1++; } else { resultArray[i] = array2[curIndexArray2]; curIndexArray2++; } } else if (curIndexArray2 < array2.length) { resultArray[i] = array2[curIndexArray2]; curIndexArray2++; } else { resultArray[i] = array1[curIndexArray1]; curIndexArray1++; } } return resultArray; } }
29.246377
83
0.565411
efc42c1caf83c50f13014639e627bdd81829efd7
517
package fixtures.intrange; import com.uber.rave.annotation.Validated; import fixtures.SampleFactory; import androidx.annotation.IntRange; @Validated(factory = SampleFactory.class) public class IntRangeTestClass { @IntRange(from = -5, to = 10) public int getInt1() { return 1; } @IntRange(from = -5) public int getInt2() { return 1; } @IntRange(to = 10) public int getInt3() { return 1; } @IntRange public int getInt4() { return 1; } }
19.884615
42
0.622824
5e574f4ba4b9a76ef9b507ed16a875417769742f
17,754
/* * Copyright 2014-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 * * 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.dbflute.logic.jdbc.mapping; import java.sql.Types; import java.util.Map; import java.util.Map.Entry; import org.apache.torque.engine.database.model.TypeMap; import org.dbflute.logic.generate.language.DfLanguageDependency; import org.dbflute.logic.jdbc.metadata.info.DfColumnMeta; import org.dbflute.util.DfNameHintUtil; import org.dbflute.util.Srl; /** * @author jflute */ public class DfJdbcTypeMapper { // =================================================================================== // Attribute // ========= protected final Map<String, String> _nameToJdbcTypeMap; protected final Map<String, Map<String, String>> _pointToJdbcTypeMap; protected final DfMapperResource _resource; // =================================================================================== // Attribute // ========= public DfJdbcTypeMapper(Map<String, String> nameToJdbcTypeMap, Map<String, Map<String, String>> pointToJdbcTypeMap, DfMapperResource resource) { _nameToJdbcTypeMap = nameToJdbcTypeMap; _pointToJdbcTypeMap = pointToJdbcTypeMap; _resource = resource; } public static interface DfMapperResource { DfLanguageDependency getLang(); boolean isDbmsMySQL(); boolean isDbmsPostgreSQL(); boolean isDbmsOracle(); boolean isDbmsDB2(); boolean isDbmsSQLServer(); boolean isDbmsDerby(); } // =================================================================================== // Torque Type Getting // =================== /** * Get the JDBC type of the column. (contains point type-mapping) <br> * Look at the java-doc of overload method if you want to know the priority of mapping. * @param columnMeta The meta information of column. (NotNull) * @return The JDBC type of the column. (NotNull) */ public String getColumnJdbcType(DfColumnMeta columnMeta) { final String pointMappingType = findPointMappingType(columnMeta); if (pointMappingType != null) { return pointMappingType; } return getColumnJdbcType(columnMeta.getJdbcDefValue(), columnMeta.getDbTypeName()); } protected String findPointMappingType(DfColumnMeta columnMeta) { final String tableName = columnMeta.getTableName(); if (tableName == null) { return null; } Map<String, String> columnTypeMap = _pointToJdbcTypeMap.get(tableName); final String foundType = doFindPointMappingType(columnMeta, columnTypeMap); if (foundType != null) { return foundType; } columnTypeMap = _pointToJdbcTypeMap.get("$$ALL$$"); return doFindPointMappingType(columnMeta, columnTypeMap); } protected String doFindPointMappingType(DfColumnMeta columnMeta, Map<String, String> columnTypeMap) { if (columnTypeMap != null) { final String columnName = columnMeta.getColumnName(); for (Entry<String, String> entry : columnTypeMap.entrySet()) { final String columnHint = entry.getKey(); if (DfNameHintUtil.isHitByTheHint(columnName, columnHint)) { final String value = entry.getValue(); if (value != null) { return value; } } } } return null; } /** * Get the JDBC type of the column. <br> * The priority of mapping is as follows: * <pre> * 1. The specified type mapping by DB type name (typeMappingMap.dfprop) * 2. The fixed type mapping (PostgreSQL's OID and Oracle's Date and so on...) * 3. The standard type mapping by JDBC type if the type is not 'OTHER' (typeMappingMap.dfprop) * 4. The auto type mapping by DB type name * 5. String finally * </pre> * @param jdbcDefType The definition type of JDBC. * @param dbTypeName The name of DB data type. (NullAllowed: If null, the mapping using this is invalid) * @return The JDBC type of the column. (NotNull) */ public String getColumnJdbcType(int jdbcDefType, String dbTypeName) { final String jdbcType = doGetColumnJdbcType(jdbcDefType, dbTypeName); if (jdbcType == null) { // * * * * * * // Priority 5 // * * * * * * return getVarcharJdbcType(); } return jdbcType; } /** * Does it have a mapping about the type? * @param jdbcDefType The definition type of JDBC. * @param dbTypeName The name of DB data type. (NullAllowed: If null, the mapping using this is invalid) * @return The JDBC type of the column. (NotNull) */ public boolean hasMappingJdbcType(int jdbcDefType, String dbTypeName) { return doGetColumnJdbcType(jdbcDefType, dbTypeName) != null; } public String doGetColumnJdbcType(int jdbcDefType, String dbTypeName) { // * * * * * * // Priority 1 // * * * * * * if (dbTypeName != null) { if (_nameToJdbcTypeMap != null && !_nameToJdbcTypeMap.isEmpty()) { final String torqueType = _nameToJdbcTypeMap.get(dbTypeName); if (torqueType != null) { return (String) torqueType; } } } // * * * * * * // Priority 2 // * * * * * * final String adjustment = processForcedAdjustment(jdbcDefType, dbTypeName); if (adjustment != null) { return adjustment; } // * * * * * * // Priority 3 // * * * * * * if (!isOtherType(jdbcDefType)) { final String jdbcType = getJdbcType(jdbcDefType); if (Srl.is_NotNull_and_NotEmpty(jdbcType)) { return jdbcType; } } // here means that it cannot determine by jdbcDefValue // * * * * * * // Priority 4 // * * * * * * // /- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Here is coming if the JDBC type is OTHER or is not found in TypeMap. // - - - - - - - - - -/ if (containsIgnoreCase(dbTypeName, "varchar")) { return getVarcharJdbcType(); } else if (containsIgnoreCase(dbTypeName, "char")) { return getCharJdbcType(); } else if (containsIgnoreCase(dbTypeName, "numeric", "number", "decimal")) { return getNumericJdbcType(); } else if (containsIgnoreCase(dbTypeName, "timestamp", "datetime")) { return getTimestampJdbcType(); } else if (containsIgnoreCase(dbTypeName, "date")) { return getDateJdbcType(); } else if (containsIgnoreCase(dbTypeName, "time")) { return getTimeJdbcType(); } else if (containsIgnoreCase(dbTypeName, "clob")) { return getClobJdbcType(); } else if (containsIgnoreCase(dbTypeName, "blob")) { return getBlobJdbcType(); } else { return null; } } protected String processForcedAdjustment(int jdbcDefValue, String dbTypeName) { if (isConceptTypeUUID(dbTypeName)) { final String uuid = _resource.getLang().getLanguageTypeMapping().getJdbcTypeOfUUID(); if (uuid != null) { // might be unsupported in any language return uuid; } } if (isPostgreSQLOid(dbTypeName)) { return getBlobJdbcType(); } // interval type needs ... string? at PostgreSQL-9.x!? // (it had been worked but error now) //if (isPostgreSQLInterval(dbTypeName)) { // return getTimeJdbcType(); //} if (isOracleCompatibleDate(jdbcDefValue, dbTypeName)) { // for compatibility to Oracle's JDBC driver return getDateJdbcType(); } return null; } // ----------------------------------------------------- // Concept Type // ------------ public boolean isConceptTypeUUID(final String dbTypeName) { // mapped by UUID if (isPostgreSQLUuid(dbTypeName)) { return true; } if (isSQLServerUniqueIdentifier(dbTypeName)) { return true; } return false; } /** * Is the type 'PlainClob' as concept type? </br > * This type is not related to a way of JDBC handling, * whether the type can be purely called 'CLOB type' or not. <br> * But 'text' type is not contained to it. * @param dbTypeName The name of DB type. (NotNull) * @return The determination, true or false. */ public boolean isConceptTypePlainClob(final String dbTypeName) { // all CLOB type return isOracleClob(dbTypeName) || isDB2Clob(dbTypeName) || isDerbyClob(dbTypeName); } /** * Is the type 'StringClob' as concept type? </br > * It means the type needs to be handled as stream on JDBC. * @param dbTypeName The name of DB type. (NotNull) * @return The determination, true or false. */ public boolean isConceptTypeStringClob(final String dbTypeName) { // needs stream return isOracleClob(dbTypeName); // only Oracle's CLOB (it can get all text by getString() on DB2) } public boolean isConceptTypeBytesBlob(final String dbTypeName) { // needs special handling as BLOB return isOracleBlob(dbTypeName); // only Oracle's BLOB for now } public boolean isConceptTypeFixedLengthString(final String dbTypeName) { return isPostgreSQLBpChar(dbTypeName); // procedure only } public boolean isConceptTypeObjectBindingBigDecimal(final String dbTypeName) { return isPostgreSQLNumeric(dbTypeName); // procedure only } // ----------------------------------------------------- // Pinpoint Type // ------------- public boolean isMySQLDatetime(final String dbTypeName) { return _resource.isDbmsMySQL() && matchIgnoreCase(dbTypeName, "datetime"); } public boolean isPostgreSQLSerialFamily(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && matchIgnoreCase(dbTypeName, "serial", "smallserial", "bigserial"); } public boolean isPostgreSQLBpChar(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && matchIgnoreCase(dbTypeName, "bpchar"); } public boolean isPostgreSQLNumeric(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && matchIgnoreCase(dbTypeName, "numeric"); } public boolean isPostgreSQLUuid(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && matchIgnoreCase(dbTypeName, "uuid"); } public boolean isPostgreSQLBytea(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && matchIgnoreCase(dbTypeName, "bytea"); } public boolean isPostgreSQLOid(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && matchIgnoreCase(dbTypeName, "oid"); } public boolean isPostgreSQLInterval(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && matchIgnoreCase(dbTypeName, "interval"); } public boolean isPostgreSQLCursor(final String dbTypeName) { return _resource.isDbmsPostgreSQL() && containsIgnoreCase(dbTypeName, "cursor"); } public boolean isOracleClob(final String dbTypeName) { return _resource.isDbmsOracle() && containsIgnoreCase(dbTypeName, "clob"); } public boolean isOracleBlob(final String dbTypeName) { return _resource.isDbmsOracle() && containsIgnoreCase(dbTypeName, "blob"); } public boolean isOracleNCharOrNVarchar(final String dbTypeName) { return _resource.isDbmsOracle() && containsIgnoreCase(dbTypeName, "nchar", "nvarchar"); } public boolean isOracleNCharOrNVarcharOrNClob(final String dbTypeName) { return _resource.isDbmsOracle() && containsIgnoreCase(dbTypeName, "nchar", "nvarchar", "nclob"); } public boolean isOracleNumber(final String dbTypeName) { return _resource.isDbmsOracle() && matchIgnoreCase(dbTypeName, "number"); } public boolean isOracleDate(final String dbTypeName) { return _resource.isDbmsOracle() && matchIgnoreCase(dbTypeName, "date"); } public boolean isOracleCompatibleDate(final int jdbcType, final String dbTypeName) { return _resource.isDbmsOracle() && java.sql.Types.TIMESTAMP == jdbcType && matchIgnoreCase(dbTypeName, "date"); } public boolean isOracleBinaryFloatDouble(final String dbTypeName) { return _resource.isDbmsOracle() && matchIgnoreCase(dbTypeName, "binary_float", "binary_double"); } public boolean isOracleCursor(final String dbTypeName) { return _resource.isDbmsOracle() && containsIgnoreCase(dbTypeName, "cursor"); } public boolean isOracleTable(final String dbTypeName) { return _resource.isDbmsOracle() && containsIgnoreCase(dbTypeName, "table"); } public boolean isOracleVArray(final String dbTypeName) { return _resource.isDbmsOracle() && containsIgnoreCase(dbTypeName, "varray"); } public boolean isDB2Clob(final String dbTypeName) { return _resource.isDbmsDB2() && containsIgnoreCase(dbTypeName, "clob"); } public boolean isSQLServerUniqueIdentifier(final String dbTypeName) { return _resource.isDbmsSQLServer() && matchIgnoreCase(dbTypeName, "uniqueidentifier"); } public boolean isDerbyClob(final String dbTypeName) { return _resource.isDbmsDerby() && containsIgnoreCase(dbTypeName, "clob"); } // ----------------------------------------------------- // JDBC Type // --------- protected boolean isOtherType(final int jdbcDefValue) { return Types.OTHER == jdbcDefValue; } protected String getJdbcType(int jdbcDefValue) { return TypeMap.findJdbcTypeByJdbcDefValue(jdbcDefValue); } protected String getVarcharJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.VARCHAR); } protected String getCharJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.CHAR); } protected String getNumericJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.NUMERIC); } protected String getTimestampJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.TIMESTAMP); } protected String getTimeJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.TIME); } protected String getDateJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.DATE); } protected String getClobJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.CLOB); } protected String getBlobJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.BLOB); } protected String getBinaryJdbcType() { return TypeMap.findJdbcTypeByJdbcDefValue(java.sql.Types.BINARY); } // =================================================================================== // Matching Helper // =============== protected boolean matchIgnoreCase(String dbTypeName, String... types) { if (dbTypeName == null) { return false; } for (String type : types) { if (dbTypeName.trim().equalsIgnoreCase(type.trim())) { return true; } } return false; } protected boolean containsIgnoreCase(String dbTypeName, String... types) { if (dbTypeName == null) { return false; } final String trimmedLowerName = dbTypeName.toLowerCase().trim(); for (String type : types) { if (trimmedLowerName.contains(type.toLowerCase().trim())) { return true; } } return false; } // =================================================================================== // Basic Override // ============== @Override public String toString() { return _nameToJdbcTypeMap + ":" + _resource; } }
39.192053
119
0.580038
44a87261b8cd67a74fb4d873e0a2a941e7dca832
4,046
package com.mercury.chat.server.protocol.group; import static com.mercury.chat.common.constant.Constant.userInfo; import static com.mercury.chat.common.util.Channels.get; import static com.mercury.chat.common.util.Channels.has; import io.netty.channel.Channel; import io.netty.channel.ChannelId; import io.netty.channel.group.ChannelGroupFuture; import io.netty.channel.group.ChannelMatcher; import io.netty.channel.group.DefaultChannelGroup; import io.netty.util.concurrent.EventExecutor; import java.util.List; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; import com.google.common.collect.Lists; import com.mercury.chat.user.entity.User; public class ChatChannelGroup extends DefaultChannelGroup { private RemovalListener<String,Channel> removalListener = new RemovalListener<String,Channel>(){ @Override public void onRemoval(RemovalNotification<String, Channel> notification) { //TODO } }; private RemovalListener<String,User> removalUserListener = new RemovalListener<String,User>(){ @Override public void onRemoval(RemovalNotification<String, User> notification) { //TODO } }; public List<User> getOnlineUser(long shopId){ return shopUserCache.getIfPresent(shopId); } private Cache<String,Channel> cache = CacheBuilder .newBuilder() .concurrencyLevel(4) .initialCapacity(8) .maximumSize(10000) .removalListener(removalListener) .recordStats() .build(); private Cache<String,User> userCache = CacheBuilder .newBuilder() .concurrencyLevel(4) .initialCapacity(8) .maximumSize(10000) .removalListener(removalUserListener) .recordStats() .build(); private Cache<Long,List<User>> shopUserCache = CacheBuilder .newBuilder() .concurrencyLevel(4) .initialCapacity(8) .maximumSize(10000) .recordStats() .build(); public boolean hasUser(String userId){ return userCache.getIfPresent(userId) != null; } public Cache<String,Channel> getCache(){ return cache; } public ChatChannelGroup(EventExecutor executor) { super(executor); } public ChatChannelGroup(String name, EventExecutor executor) { super(name, executor); } @Override public boolean add(Channel channel) { boolean added = super.add(channel); if(has(channel,userInfo)){ User user = get(channel,userInfo); cache.put(user.getUserId(), channel); userCache.put(user.getUserId(), user); if(user.isSales()){ Long shopId = user.getShopId(); //FIXME Thread safe? List<User> userList = shopUserCache.getIfPresent(shopId); if(userList!=null){ userList.add(user); }else{ userList = Lists.newArrayList(user); shopUserCache.put(shopId, userList); } } } return added; } @Override public boolean remove(Object o) { Channel channel = null; if (o instanceof ChannelId) { ChannelId id = (ChannelId) o; channel = find(id); }else if(o instanceof Channel){ channel = (Channel) o; } if(has(channel,userInfo)){ User user = get(channel,userInfo); //clear the user info from the channel. channel.attr(userInfo).remove(); cache.invalidate(user.getUserId()); userCache.invalidate(user.getUserId()); if(user.isSales()){ Long shopId = user.getShopId(); //FIXME Thread safe? List<User> userList = shopUserCache.getIfPresent(shopId); if(userList!=null){ userList.remove(user); } } } boolean removed = super.remove(o); return removed; } @Override public ChannelGroupFuture writeAndFlush(Object message, ChannelMatcher matcher) { return super.writeAndFlush(message, matcher); } }
28.293706
98
0.669797
423d01152a059d7182640b0b84c47a31fed9abd4
632
package com.sillykid.app.homepage.chartercustom.chartercommon; import com.common.cklibrary.common.BasePresenter; import com.common.cklibrary.common.BaseView; /** * Created by ruitu on 2016/9/24. */ public interface CharterDetailsContract { interface Presenter extends BasePresenter { /** * 获得包车产品详情 */ void getCharterDetails(int id); /** * 收藏产品/取消 */ void postCollectCharter(String line_id, int type); /** * 判断是否登录 */ void isLogin(int flag); } interface View extends BaseView<Presenter, String> { } }
17.555556
62
0.606013
6cf876bb75364331fcb3f86d6cb678ce12cd292f
4,630
/* * Copyright (C) 2009-2018 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac.handlers; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.*; import com.sun.tools.javac.util.List; import lombok.ConfigurationKeys; import lombok.ToString; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.LombokImmutableList; import lombok.core.configuration.CallSuperType; import lombok.core.handlers.InclusionExclusionUtils; import lombok.core.handlers.InclusionExclusionUtils.Included; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import org.mangosdk.spi.ProviderFor; import org.springframework.stereotype.Controller; import java.util.Collection; import static lombok.core.handlers.HandlerUtil.FieldAccess; import static lombok.javac.Javac.CTC_PLUS; import static lombok.javac.handlers.JavacHandlerUtil.*; /** * Handles the {@code Controller} annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandleController extends JavacAnnotationHandler<Controller> { private static final LombokImmutableList<String> METHOD_CHECK_TRIAL = LombokImmutableList.of("com","onevizion","web","filter","TrialLimitationCheck","checkTrial"); private static final LombokImmutableList<String> IGNORED_METHODS = LombokImmutableList.of("detectLastApiVersion", "initTbGridPage"); @Override public void handle(AnnotationValues<Controller> annotation, JCAnnotation ast, JavacNode annotationNode) { JavacNode classNode = annotationNode.up(); if (classNode != null && classNode.get() instanceof JCClassDecl && !classNode.getName().startsWith("Trial")) { for (JCTree def : ((JCClassDecl) classNode.get()).defs) { if (def instanceof JCMethodDecl) { JCMethodDecl methodDecl = (JCMethodDecl) def; if (isConstructor(methodDecl) || isSetter(methodDecl) || IGNORED_METHODS.contains(methodDecl.name.toString())) { continue; } JavacTreeMaker maker = classNode.getTreeMaker(); JCStatement callCheckMethodStatement = maker.Exec(maker.Apply(List.<JCExpression>nil(), chainDots(classNode, METHOD_CHECK_TRIAL), List.<JCExpression>nil())); List<JCStatement> statements = methodDecl.body.stats; List<JCStatement> tail = statements; List<JCStatement> head = List.nil(); for (JCStatement stat : statements) { if (JavacHandlerUtil.isConstructorCall(stat)) { tail = tail.tail; head = head.prepend(stat); continue; } break; } List<JCStatement> newList = tail.prepend(callCheckMethodStatement); for (JCStatement stat : head) newList = newList.prepend(stat); methodDecl.body.stats = newList; annotationNode.getAst().setChanged(); } } } } private boolean isSetter(JCMethodDecl methodDecl) { return methodDecl.name.toString().startsWith("set"); } private boolean isConstructor(JCMethodDecl methodDecl) { return "<init>".equals(methodDecl.name.toString()); } }
44.519231
167
0.678834
1e363ffc95acbd2d7bcbc2abf1da9a5c11c2a00f
1,213
/** * This class holds an enumeration of all command words known * to the program. * * @author David J. Barnes and Michael Kölling. * @version 2011.07.31 */ public class CommandWords { // a constant array that holds all valid command words private static final String validCommands[] = { "add", "search", "list", "help", "quit", }; /** * Constructor for CommandWords */ public CommandWords() { } /** * Check whether a given String is a valid command word. * @param aString The string to be checked. * @return true if it is valid, false if it isn't. */ public boolean isCommand(String aString) { if(aString != null){ for(int i = 0; i < validCommands.length; i++) { if(validCommands[i].equals(aString)) return true; } } // if we get here, the string was not found in the commands return false; } /** * Print all valid commands to System.out. */ public void showAll() { for(String command : validCommands) { System.out.print(command + " "); } System.out.println(); } }
24.26
67
0.555647
7f38f8c5412a42bfe664eb3fc57f5b8377abaab1
3,120
package org.javacc.cpp; import org.javacc.parser.CodeGeneratorSettings; import org.javacc.parser.TokenManagerCodeGenerator; import org.javacc.utils.OutputFileGenerator; public class CodeGenerator implements org.javacc.parser.CodeGenerator { public static final boolean IS_DEBUG = true; /** * The name of the C# code generator. */ @Override public String getName() { return "C++"; } /** * Generate any other support files you need. */ @Override public boolean generateHelpers(CodeGeneratorSettings settings) { try { OutputFileGenerator.generateSimple("/templates/cpp/CharStream.h.template", "CharStream.h", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/CharStream.cc.template", "CharStream.cc", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/TokenMgrError.h.template", "TokenMgrError.h", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/TokenMgrError.cc.template", "TokenMgrError.cc", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/ParseException.h.template", "ParseException.h", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/ParseException.cc.template", "ParseException.cc", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/TokenManager.h.template", "TokenManager.h", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/JavaCC.h.template", "JavaCC.h", "/* JavaCC generated file. */", settings); OutputFileGenerator.generateSimple("/templates/cpp/ErrorHandler.h.template", "ErrorHandler.h", "/* JavaCC generated file. */", settings); // if ((Boolean) settings.get("JAVA_UNICODE_ESCAPE")) { // OutputFileGenerator.generateSimple("/templates/cpp/JavaCharStream.template", "JavaCharStream.cs", "/* JavaCC generated file. */", settings); // } else { // OutputFileGenerator.generateSimple("/templates/cpp/CharStream.template", "CharStream.cs", "/* JavaCC generated file. */", settings); // } OtherFilesGenCPP.start(); } catch (Exception e) { return false; } return true; } /** * The Token class generator. */ @Override public TokenCodeGenerator getTokenCodeGenerator() { return new TokenCodeGenerator(); } /** * The TokenManager class generator. */ @Override public TokenManagerCodeGenerator getTokenManagerCodeGenerator() { return new org.javacc.cpp.classic.TokenManagerCodeGenerator(); } /** * The Parser class generator. */ @Override public ParserCodeGenerator getParserCodeGenerator() { return new ParserCodeGenerator(); } /** * TODO(sreeni): Fix this when we do tree annotations in the parser code generator. The JJTree * preprocesor. */ @Override public org.javacc.jjtree.DefaultJJTreeVisitor getJJTreeCodeGenerator() { return new JJTreeCodeGenerator(); } }
35.454545
150
0.708654
3dd9d351c5f878f29f8bf4de44517a75dde6a467
5,100
/* * 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.lucene.codecs; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; /** * This class accumulates the (freq, norm) pairs that may produce competitive scores. */ public final class CompetitiveFreqNormAccumulator { // We speed up accumulation for common norm values by first computing // the max freq for all norms in -128..127 private final int[] maxFreqs; private boolean dirty; private final TreeSet<FreqAndNorm> freqNormPairs; /** Sole constructor. */ public CompetitiveFreqNormAccumulator() { maxFreqs = new int[256]; Comparator<FreqAndNorm> comparator = new Comparator<CompetitiveFreqNormAccumulator.FreqAndNorm>() { @Override public int compare(FreqAndNorm o1, FreqAndNorm o2) { // greater freqs compare greater int cmp = Integer.compare(o1.freq, o2.freq); if (cmp == 0) { // greater norms compare lower cmp = Long.compareUnsigned(o2.norm, o1.norm); } return cmp; } }; freqNormPairs = new TreeSet<>(comparator); } /** Reset to the same state it was in after creation. */ public void clear() { Arrays.fill(maxFreqs, 0); dirty = false; freqNormPairs.clear(); } /** * A (freq, norm) pair. */ public static class FreqAndNorm { /** Doc-term frequency. */ public final int freq; /** Normalization factor. */ public final long norm; /** Sole constructor. */ public FreqAndNorm(int freq, long norm) { this.freq = freq; this.norm = norm; } @Override public boolean equals(Object obj) { if (obj == null || obj instanceof FreqAndNorm == false) { return false; } FreqAndNorm that = (FreqAndNorm) obj; return freq == that.freq && norm == that.norm; } @Override public int hashCode() { int h = getClass().hashCode(); h = 31 * h + freq; h = 31 * h + Long.hashCode(norm); return h; } @Override public String toString() { return "{" + freq + "," + norm + "}"; } } /** Accumulate a (freq,norm) pair, updating this structure if there is no * equivalent or more competitive entry already. */ public void add(int freq, long norm) { if (norm >= Byte.MIN_VALUE && norm <= Byte.MAX_VALUE) { int index = Byte.toUnsignedInt((byte) norm); maxFreqs[index] = Math.max(maxFreqs[index], freq); dirty = true; } else { add(new FreqAndNorm(freq, norm)); } } /** Merge {@code acc} into this. */ public void addAll(CompetitiveFreqNormAccumulator acc) { for (FreqAndNorm entry : acc.getCompetitiveFreqNormPairs()) { add(entry); } } /** Get the set of competitive freq and norm pairs, orderer by increasing freq and norm. */ public SortedSet<FreqAndNorm> getCompetitiveFreqNormPairs() { if (dirty) { for (int i = 0; i < maxFreqs.length; ++i) { if (maxFreqs[i] > 0) { add(new FreqAndNorm(maxFreqs[i], (byte) i)); maxFreqs[i] = 0; } } dirty = false; } return Collections.unmodifiableSortedSet(freqNormPairs); } private void add(FreqAndNorm newEntry) { FreqAndNorm next = freqNormPairs.ceiling(newEntry); if (next == null) { // nothing is more competitive freqNormPairs.add(newEntry); } else if (Long.compareUnsigned(next.norm, newEntry.norm) <= 0) { // we already have this entry or more competitive entries in the tree return; } else { // some entries have a greater freq but a less competitive norm, so we // don't know which one will trigger greater scores, still add to the tree freqNormPairs.add(newEntry); } for (Iterator<FreqAndNorm> it = freqNormPairs.headSet(newEntry, false).descendingIterator(); it.hasNext(); ) { FreqAndNorm entry = it.next(); if (Long.compareUnsigned(entry.norm, newEntry.norm) >= 0) { // less competitive it.remove(); } else { // lesser freq but better norm, further entries are not comparable break; } } } @Override public String toString() { return getCompetitiveFreqNormPairs().toString(); } }
31.097561
114
0.649412
6b52fb3adc77529c88ccf0b5a862a89d71e7d4b7
2,368
/*-------------------------------------------------------------------------- * Copyright 2007 Taro L. Saito * * 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. *--------------------------------------------------------------------------*/ //-------------------------------------- // XerialJ Project // // StorageServer.java // Since: Jul 5, 2007 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.db.storage; import java.io.File; import java.util.List; import org.xerial.db.DBException; import org.xerial.db.DBErrorCode; import org.xerial.db.RelationalQuery; import org.xerial.json.JSONObject; /** * * @author leo * */ public class XerialStorageServer { private String storageFolderPath; private String masterAddress; public XerialStorageServer(String storageFolderPath, String masterAddress) throws DBException { this.storageFolderPath = storageFolderPath; this.masterAddress = masterAddress; // start up the storage server prepareStorageFolder(); scanFolder(); connectToMaster(); } private void prepareStorageFolder() throws DBException { File folder = new File(storageFolderPath); if (!folder.exists()) folder.mkdir(); if (!folder.isDirectory()) throw new DBException(DBErrorCode.InvalidFile, storageFolderPath + " is not a directory"); } /** * Scans the storage folder contents */ private void scanFolder() { File folder = new File(storageFolderPath); File[] fileList = folder.listFiles(); for(File file : fileList) { } } private void connectToMaster() { } public List<Long> getDatabaseIDList() { // TODO return null; } public int getNumberOfDatabases() { // TODO return -1; } public JSONObject query(Long databaseID, RelationalQuery query) { // TODO return null; } }
21.527273
94
0.630068
ed66b69275403594412e1e80098fac9a284c3e6b
1,036
package nl.knokko.races.event.parameter; public class EntityParameter extends EventParameter { static final EventParameter[] INFO = { new NumberParameter("CurrentSpeed"), new NumberParameter("DimensionID"), new NumberParameter("RemainingFireTicks"), new NumberParameter("CurrentHearts"), new NumberParameter("LightLevel"), new NumberParameter("MaxHearts"), new NumberParameter("SpeedX"), new NumberParameter("SpeedY"), new NumberParameter("SpeedZ"), new NumberParameter("MovementSpeed"), new TextParameter("Name"), new NumberParameter("Temperature"), new NumberParameter("WorldTime"), new NumberParameter("CurrentX"), new NumberParameter("CurrentY"), new NumberParameter("CurrentZ"), new BooleanParameter("InLava"), new BooleanParameter("InWater"), new BooleanParameter("SeeSky") }; public EntityParameter(String name) { super(name); } @Override public ParameterType getType() { return ParameterType.ENTITY; } @Override public EventParameter[] getChildren() { return INFO; } }
25.9
53
0.745174
0b08f681d86d81fc2e07fb1286e597004a83d9ed
701
package com.roocon.thread.ta4; public class Main { private int value; private MyLock2 lock = new MyLock2(); public int next() { lock.lock(); try { Thread.sleep(300); return value++; } catch (InterruptedException e) { throw new RuntimeException(); } finally { lock.unlock(); } } public void a() { lock.lock(); System.out.println("a"); b(); lock.unlock(); } public void b() { lock.lock(); System.out.println("b"); lock.unlock(); } public static void main(String[] args) { Main m = new Main(); new Thread(new Runnable() { @Override public void run() { m.a(); } }).start(); } }
14.306122
42
0.544936
44e27553426fb9516af88e696fb614cc1c07ca47
236
package com.baidu.ueditor; import java.io.File; public interface CloudStorageInteface { /** * @param file 待上传的文件 * @param key 上传到云存储的key * @return 返回对象的访问路径url,若为null则表示失败 * */ public String upload(File file,String key); }
18.153846
45
0.720339
eec1455beac8bcb59ec49fb5469e5d3a4f75e963
5,262
/* * Copyright (c) 2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.test.asserter.refinedschema; import com.evolveum.midpoint.schema.processor.ResourceObjectTypeDefinition; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ResourceObjectDefinition; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.processor.ResourceSchemaFactory; import com.evolveum.midpoint.test.asserter.prism.PrismSchemaAsserter; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import javax.xml.namespace.QName; import static org.testng.AssertJUnit.assertNotNull; /** * @author Radovan Semancik */ public class RefinedResourceSchemaAsserter<RA> extends PrismSchemaAsserter<RA> { public RefinedResourceSchemaAsserter(ResourceSchema schema) { super(schema); } public RefinedResourceSchemaAsserter(ResourceSchema schema, String detail) { super(schema, detail); } public RefinedResourceSchemaAsserter(ResourceSchema schema, RA returnAsserter, String detail) { super(schema, returnAsserter, detail); } public static RefinedResourceSchemaAsserter<Void> forRefinedResourceSchema(ResourceSchema schema) { return new RefinedResourceSchemaAsserter<>(schema); } public static RefinedResourceSchemaAsserter<Void> forResource(PrismObject<ResourceType> resource) throws SchemaException, ConfigurationException { ResourceSchema refinedSchema = ResourceSchemaFactory.getCompleteSchema(resource); assertNotNull("No refined schema for "+resource, refinedSchema); return new RefinedResourceSchemaAsserter<>(refinedSchema, resource.toString()); } public static RefinedResourceSchemaAsserter<Void> forResource(PrismObject<ResourceType> resource, String details) throws SchemaException, ConfigurationException { ResourceSchema refinedSchema = ResourceSchemaFactory.getCompleteSchema(resource); assertNotNull("No refined schema for "+resource+" ("+details+")", refinedSchema); return new RefinedResourceSchemaAsserter<>(refinedSchema, resource +" ("+details+")"); } public ResourceSchema getSchema() { return (ResourceSchema) super.getSchema(); } public RefinedResourceSchemaAsserter<RA> assertNamespace(String expected) { super.assertNamespace(expected); return this; } public ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> objectClass(QName ocQname) { ResourceObjectDefinition objectClassDefinition = getSchema().findDefinitionForObjectClass(ocQname); ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> asserter = new ResourceObjectDefinitionAsserter<>(objectClassDefinition, this, desc()); copySetupTo(asserter); return asserter; } public ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> objectClass(String ocName) { ResourceObjectDefinition objectClassDefinition = getSchema().findDefinitionForObjectClass(new QName(MidPointConstants.NS_RI, ocName)); ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> asserter = new ResourceObjectDefinitionAsserter<>(objectClassDefinition, this, desc()); copySetupTo(asserter); return asserter; } public ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> defaultDefinition(ShadowKindType kind) { ResourceObjectTypeDefinition objectClassDefinition = getSchema().findDefaultOrAnyObjectTypeDefinition(kind); ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> asserter = new ResourceObjectDefinitionAsserter<>(objectClassDefinition, this, "default definition for kind " + kind + " in " + desc()); copySetupTo(asserter); return asserter; } public ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> defaultAccountDefinition() { ResourceObjectTypeDefinition objectClassDefinition = getSchema().findDefaultOrAnyObjectTypeDefinition(ShadowKindType.ACCOUNT); ResourceObjectDefinitionAsserter<RefinedResourceSchemaAsserter<RA>> asserter = new ResourceObjectDefinitionAsserter<>(objectClassDefinition, this, "default account definition in " + desc()); copySetupTo(asserter); return asserter; } protected String desc() { return descWithDetails("refined schema"); } public RefinedResourceSchemaAsserter<RA> display() { display(desc()); return this; } public RefinedResourceSchemaAsserter<RA> display(String message) { PrismTestUtil.display(message, getSchema()); return this; } }
45.756522
198
0.764158
f7676681ad70169ab639af0f3c34d0df676dc266
1,348
/* * Copyright 2017-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 * * 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.alilitech.mybatis.jpa.pagination; /** * 分页工具类 * * @author Zhou Xiaoxiang * @since 1.0 */ public class PageHelper { /** * 计算当前分页偏移量 * @param current 当前页 * @param size 每页显示数量 * @return 分页偏移量 */ public static int offsetCurrent(int current, int size) { if (current > 0) { return (current - 1) * size; } return 0; } /** * 计算当前分页偏移量 * @param pagination 分页类 * @return 分页偏移量 */ public static int offsetCurrent(Pagination pagination) { if (null == pagination) { return 0; } return offsetCurrent(pagination.getPage(), pagination.getSize()); } }
24.962963
78
0.624629
4d46888434631be649a052258e596c322c9f3948
2,599
/** * Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caintegrator/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.web.action.abstractlist; import static org.junit.Assert.assertEquals; import gov.nih.nci.caintegrator.application.study.StudyConfiguration; import gov.nih.nci.caintegrator.domain.application.GeneList; import gov.nih.nci.caintegrator.domain.application.StudySubscription; import gov.nih.nci.caintegrator.domain.genomic.Gene; import gov.nih.nci.caintegrator.domain.translational.Study; import gov.nih.nci.caintegrator.web.SessionHelper; import gov.nih.nci.caintegrator.web.action.AbstractSessionBasedTest; import gov.nih.nci.caintegrator.web.action.abstractlist.ManageListAction; import gov.nih.nci.caintegrator.web.action.abstractlist.SearchGeneListAction; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import com.opensymphony.xwork2.ActionContext; public class SearchListActionTest extends AbstractSessionBasedTest { private SearchGeneListAction action = new SearchGeneListAction(); private StudySubscription subscription = new StudySubscription(); @Override @Before public void setUp() throws Exception { super.setUp(); SessionHelper.getInstance().getDisplayableUserWorkspace().setCurrentStudySubscription(subscription); ActionContext.getContext().setSession(new HashMap<String, Object>()); ActionContext.getContext().getValueStack().setValue("studySubscription", subscription); setStudySubscription(subscription); subscription.setStudy(new Study()); subscription.getStudy().setStudyConfiguration(new StudyConfiguration()); action.setWorkspaceService(workspaceService); } @Test public void testAll() { // Test Execute assertEquals(ManageListAction.SUCCESS, action.execute()); assertEquals(null, action.getGeneListName()); GeneList geneList = new GeneList(); geneList.setName("List1"); subscription.getListCollection().add(geneList); assertEquals(ManageListAction.SUCCESS, action.execute()); assertEquals("List1", action.getGeneListName()); assertEquals(0, action.getGenes().size()); geneList.getGeneCollection().add(new Gene()); assertEquals(ManageListAction.SUCCESS, action.execute()); assertEquals("List1", action.getGeneListName()); assertEquals(1, action.getGenes().size()); } }
40.609375
109
0.734898
efa10ea13e8d8be3147d9add22cde3c0a01fb60e
19,092
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ package com.gemstone.gemfire.management.internal; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.rmi.AlreadyBoundException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.server.UnicastRemoteObject; import java.util.HashMap; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnectorServer; import javax.management.remote.rmi.RMIJRMPServerImpl; import javax.management.remote.rmi.RMIServerImpl; import javax.rmi.ssl.SslRMIClientSocketFactory; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.distributed.internal.DistributionConfig; import com.gemstone.gemfire.i18n.LogWriterI18n; import com.gemstone.gemfire.internal.SocketCreator; import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import com.gemstone.gemfire.internal.lang.StringUtils; import com.gemstone.gemfire.internal.tcp.TCPConduit; import com.gemstone.gemfire.management.ManagementException; import com.gemstone.gemfire.management.ManagementService; import com.gemstone.gemfire.management.ManagerMXBean; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; /** * Agent implementation that controls the JMX server end points for JMX * clients to connect, such as an RMI server. * * The ManagementAgent could be used in a loner or GemFire client to define and * control JMX server end points for the Platform MBeanServer and the GemFire * MBeans hosted within it. * * @author Pivotal Software, Inc. * @since 7.0 */ public class ManagementAgent { /** * True if running. Protected by synchronizing on this Manager instance. I * used synchronization because I think we'll want to hold the same * synchronize while configuring, starting, and eventually stopping the * RMI server, the hidden management regions (in FederatingManager), etc */ private boolean running = false; private Registry registry; private JMXConnectorServer cs; private final DistributionConfig config; private final LogWriterI18n logger; /** * This system property is set to true when the embedded HTTP server is started so that the embedded pulse webapp * can use a local MBeanServer instead of a remote JMX connection. */ private static final String PULSE_EMBEDDED_PROP = "pulse.embedded"; private static final String PULSE_EMBEDDED_GFXD_PROP = "pulse.embedded.gfxd"; public ManagementAgent(DistributionConfig config, LogWriterI18n logger) { this.config = config; this.logger = logger; } private LogWriterI18n getLogger() { return this.logger; } public synchronized boolean isRunning() { return this.running; } public synchronized void startAgent(){ startHttpService(); if (!this.running && this.config.getJmxManagerPort() != 0) { try { configureAndStart(); } catch (IOException e) { throw new ManagementException(e); } this.running = true; } } public synchronized void stopAgent(){ stopHttpService(); if (!this.running) return; this.logger.info(LocalizedStrings.DEBUG, "Stopping jmx manager agent"); try { cs.stop(); UnicastRemoteObject.unexportObject(registry, true); } catch (IOException e) { throw new ManagementException(e); } this.running = false; } private Server httpServer; private void startHttpService() { GemFireCacheImpl cache = (GemFireCacheImpl)CacheFactory.getAnyInstance(); final SystemManagementService managementService = (SystemManagementService) ManagementService.getManagementService(cache); final ManagerMXBean managerBean = managementService.getManagerMXBean(); if (this.config.getJmxManagerHttpPort() != 0) { if (this.logger.infoEnabled()) { this.logger.info(LocalizedStrings.DEBUG, String.format( "Attempting to start HTTP service on port (%1$d) at bind-address (%2$s)...", this.config.getJmxManagerHttpPort(), this.config.getJmxManagerBindAddress())); } String productHome = StringUtils.EMPTY_STRING; String productName = StringUtils.EMPTY_STRING; if (cache.isGFXDSystem()) { productHome = System.getenv("GEMFIREXD"); productName = "GEMFIREXD"; } else { productHome = System.getenv("GEMFIRE"); productName = "GEMFIRE"; } // Check for empty variable. if empty, then log message and exit HTTP server startup if (StringUtils.isBlank(productHome)) { final String message = ManagementStrings.HTTP_SERVICE_CANT_START.toLocalizedString(productName); setStatusMessage(managerBean, message); this.logger.info(LocalizedStrings.DEBUG, message); return; } // Find the Management WAR file final String gemfireWar = getGemFireWarLocation(productHome); if (gemfireWar == null) { this.logger.info(LocalizedStrings.DEBUG, "Unable to find GemFire REST API WAR file; the REST API to GemFire will not be exported and accessible."); } // Find the Pulse WAR file final String pulseWar = getPulseWarLocation(productHome, productName); if (pulseWar == null) { final String message = "Unable to find Pulse web application WAR file; Pulse will not start in embeded mode"; setStatusMessage(managerBean, message); this.logger.info(LocalizedStrings.DEBUG, message); } try { if (isWebApplicationAvailable(gemfireWar, pulseWar)) { final String bindAddress = this.config.getJmxManagerBindAddress(); final int port = this.config.getJmxManagerHttpPort(); this.httpServer = JettyHelper.initJetty(bindAddress, port, logger); if (isWebApplicationAvailable(gemfireWar)) { this.httpServer = JettyHelper.addWebApplication(this.httpServer, "/gemfire", gemfireWar); } if (isWebApplicationAvailable(pulseWar)) { this.httpServer = JettyHelper.addWebApplication(this.httpServer, "/pulse", pulseWar); } if (this.logger.infoEnabled()) { this.logger.info(LocalizedStrings.DEBUG, String.format( "Starting embedded HTTP server on port (%1$d) at bind-address (%2$s)...", this.httpServer.getConnectors()[0].getPort(), bindAddress)); } System.setProperty(PULSE_EMBEDDED_PROP, "true"); if(productName.equals("GEMFIREXD")){ System.setProperty(PULSE_EMBEDDED_GFXD_PROP, "true"); } this.httpServer = JettyHelper.startJetty(this.httpServer); // now, that the HTTP serever has been started, we can set the URL // used by web clients to connect to Pulse. if (isWebApplicationAvailable(pulseWar)) { managerBean.setPulseURL("http://".concat(getHost(bindAddress)) .concat(":").concat(String.valueOf(port)).concat("/pulse/")); } } } catch (Exception e) { setStatusMessage(managerBean, "HTTP service failed to start with " + e.getClass().getSimpleName() + " '" + e.getMessage() + "'"); throw new ManagementException("HTTP service failed to start", e); } } else { setStatusMessage(managerBean, "Embedded HTTP server configured not to start (jmx-manager-http-port=0)"); } } private String getHost(final String bindAddress) throws UnknownHostException { if (!StringUtils.isBlank(this.config.getJmxManagerHostnameForClients())) { return this.config.getJmxManagerHostnameForClients(); } else if (!StringUtils.isBlank(bindAddress)) { return InetAddress.getByName(bindAddress).getHostAddress(); } else { return SocketCreator.getLocalHost().getHostAddress(); } } // Use the GEMFIRE environment variable to find the GemFire product tree. // First, look in the $GEMFIRE/tools/Management directory // Second, look in the $GEMFIRE/lib directory // Finally, if we cannot find Management WAR file then return null... private String getGemFireWarLocation(final String gemfireHome) { assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!"; if (new File(gemfireHome + "/tools/Extensions/gemfire.war").isFile()) { return gemfireHome + "/tools/Extensions/gemfire.war"; } else if (new File(gemfireHome + "/lib/gemfire.war").isFile()) { return gemfireHome + "/lib/gemfire.war"; } else { return null; } } // Use the GEMFIRE environment variable to find the GemFire product tree. // First, look in the $GEMFIRE/tools/Pulse directory // Second, look in the $GEMFIRE/lib directory // Finally, if we cannot find the Management WAR file then return null... private String getPulseWarLocation(final String productHome, final String productName) { assert !StringUtils.isBlank(productHome) : ManagementStrings.ASSERT_PRODUCT_ENV_VAR_MSG.toLocalizedString(productName); if (new File(productHome + "/tools/Pulse/pulse.war").isFile()) { return productHome + "/tools/Pulse/pulse.war"; } else if (new File(productHome + "/lib/pulse.war").isFile()) { return productHome + "/lib/pulse.war"; } else { return null; } } private boolean isWebApplicationAvailable(final String warFileLocation) { return !StringUtils.isBlank(warFileLocation); } private boolean isWebApplicationAvailable(final String... warFileLocations) { for (String warFileLocation : warFileLocations) { if (isWebApplicationAvailable(warFileLocation)) { return true; } } return false; } private void setStatusMessage(ManagerMXBean mBean, String message) { mBean.setPulseURL(""); mBean.setStatusMessage(message); } private void stopHttpService() { if (this.httpServer != null) { this.logger.info(LocalizedStrings.DEBUG, "Stopping the HTTP service..."); try { this.httpServer.stop(); } catch (Exception e) { this.logger.warning(LocalizedStrings.DEBUG, "Failed to stop the HTTP service because: " + e); } finally { try { this.httpServer.destroy(); } catch (Exception ignore) { this.logger.error(LocalizedStrings.ERROR, "Failed to properly release resources held by the HTTP service: ", ignore); } finally { this.httpServer = null; System.clearProperty("catalina.base"); System.clearProperty("catalina.home"); } } } } /** * http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html#gdfvq * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors * https://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector * https://blogs.oracle.com/jmxetc/entry/jmx_connecting_through_firewalls_using */ private void configureAndStart() throws IOException { // KIRK: I copied this from https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors // we'll need to change this significantly but it's a starting point // get the port for RMI Registry and RMI Connector Server final int port = this.config.getJmxManagerPort(); final String hostname; final InetAddress bindAddr; if (this.config.getJmxManagerBindAddress().equals("")) { hostname = SocketCreator.getLocalHost().getHostName(); bindAddr = null; } else { hostname = this.config.getJmxManagerBindAddress(); bindAddr = InetAddress.getByName(hostname); } final boolean ssl = this.config.getJmxManagerSSL(); this.logger.info(LocalizedStrings.DEBUG, "Starting jmx manager agent on port " + port + (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : "")); final SocketCreator sc = SocketCreator.createNonDefaultInstance(ssl, this.config.getJmxManagerSSLRequireAuthentication(), this.config.getJmxManagerSSLProtocols(), this.config.getJmxManagerSSLCiphers(), this.config.getJmxSSLProperties()); RMIClientSocketFactory csf = ssl ? new SslRMIClientSocketFactory() : null;//RMISocketFactory.getDefaultSocketFactory(); //new GemFireRMIClientSocketFactory(sc, getLogger()); RMIServerSocketFactory ssf = new GemFireRMIServerSocketFactory(sc, getLogger(), bindAddr); // Following is done to prevent rmi causing stop the world gcs System.setProperty("sun.rmi.dgc.server.gcInterval", Long.toString(Long.MAX_VALUE-1)); // Create the RMI Registry using the SSL socket factories above. // In order to use a single port, we must use these factories // everywhere, or nowhere. Since we want to use them in the JMX // RMI Connector server, we must also use them in the RMI Registry. // Otherwise, we wouldn't be able to use a single port. // // Start an RMI registry on port <port>. registry = LocateRegistry.createRegistry(port, csf, ssf); // Retrieve the PlatformMBeanServer. final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // Environment map. KIRK: why is this declared as HashMap? final HashMap<String,Object> env = new HashMap<String,Object>(); String pwFile = this.config.getJmxManagerPasswordFile(); if (pwFile != null && pwFile.length() > 0) { env.put("jmx.remote.x.password.file", pwFile); } String accessFile = this.config.getJmxManagerAccessFile(); if (accessFile != null && accessFile.length() > 0) { env.put("jmx.remote.x.access.file", accessFile); } // Manually creates and binds a JMX RMI Connector Server stub with the // registry created above: the port we pass here is the port that can // be specified in "service:jmx:rmi://"+hostname+":"+port - where the // RMI server stub and connection objects will be exported. // Here we choose to use the same port as was specified for the // RMI Registry. We can do so because we're using \*the same\* client // and server socket factories, for the registry itself \*and\* for this // object. final RMIServerImpl stub = new RMIJRMPServerImpl(port, csf, ssf, env); // Create an RMI connector server. // // As specified in the JMXServiceURL the RMIServer stub will be // registered in the RMI registry running in the local host on // port <port> with the name "jmxrmi". This is the same name the // out-of-the-box management agent uses to register the RMIServer // stub too. // // The port specified in "service:jmx:rmi://"+hostname+":"+port // is the second port, where RMI connection objects will be exported. // Here we use the same port as that we choose for the RMI registry. // The port for the RMI registry is specified in the second part // of the URL, in "rmi://"+hostname+":"+port // // We construct a JMXServiceURL corresponding to what we have done // for our stub... final JMXServiceURL url = new JMXServiceURL( "service:jmx:rmi://"+hostname+":"+port+"/jndi/rmi://"+hostname+":"+port+"/jmxrmi"); // Create an RMI connector server with the JMXServiceURL // // KIRK: JDK 1.5 cannot use JMXConnectorServerFactory because of // http://bugs.sun.com/view_bug.do?bug_id=5107423 // but we're using JDK 1.6 cs = new RMIConnectorServer(new JMXServiceURL("rmi",hostname,port), env,stub,mbs) { @Override public JMXServiceURL getAddress() { return url;} @Override public synchronized void start() throws IOException { try { registry.bind("jmxrmi", stub); } catch (AlreadyBoundException x) { final IOException io = new IOException(x.getMessage()); io.initCause(x); throw io; } super.start(); } }; // This may be the 1.6 way of doing it but the problem is it does not use our "stub". //cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs); // Start the RMI connector server. // //System.out.println("Start the RMI connector server on port "+port); cs.start(); this.logger.info(LocalizedStrings.DEBUG, "Finished starting jmx manager agent."); //System.out.println("Server started at: "+cs.getAddress()); // Start the CleanThread daemon... KIRK: not sure what CleanThread is... // //final Thread clean = new CleanThread(cs); //clean.start(); } private static class GemFireRMIClientSocketFactory implements RMIClientSocketFactory, Serializable { private static final long serialVersionUID = -7604285019188827617L; private /*final hack to prevent serialization*/ transient SocketCreator sc; private /*final hack to prevent serialization*/ transient LogWriterI18n logger; public GemFireRMIClientSocketFactory(SocketCreator sc, LogWriterI18n logger) { this.sc = sc; this.logger = logger; } @Override public Socket createSocket(String host, int port) throws IOException { return this.sc.connectForClient(host, port, this.logger, 0/*no timeout*/); } }; private static class GemFireRMIServerSocketFactory implements RMIServerSocketFactory, Serializable { private static final long serialVersionUID = -811909050641332716L; private /*final hack to prevent serialization*/ transient SocketCreator sc; private /*final hack to prevent serialization*/ transient LogWriterI18n logger; private final InetAddress bindAddr; public GemFireRMIServerSocketFactory(SocketCreator sc, LogWriterI18n logger, InetAddress bindAddr) { this.sc = sc; this.logger = logger; this.bindAddr = bindAddr; } @Override public ServerSocket createServerSocket(int port) throws IOException { return this.sc.createServerSocket(port, TCPConduit.getBackLog(), this.bindAddr, this.logger); } }; }
39.52795
173
0.695841
82efd863ea76db994ba2e7be816d216cc743622b
8,626
/* * FastReport Cloud * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package cloud.fastreport.model; import java.util.Objects; import java.util.Arrays; import cloud.fastreport.model.ProblemDetails; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * ValidationProblemDetails */ @JsonPropertyOrder({ ValidationProblemDetails.JSON_PROPERTY_ERRORS, ValidationProblemDetails.JSON_PROPERTY_TYPE, ValidationProblemDetails.JSON_PROPERTY_TITLE, ValidationProblemDetails.JSON_PROPERTY_STATUS, ValidationProblemDetails.JSON_PROPERTY_DETAIL, ValidationProblemDetails.JSON_PROPERTY_INSTANCE }) @JsonTypeName("ValidationProblemDetails") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class ValidationProblemDetails { public static final String JSON_PROPERTY_ERRORS = "errors"; private JsonNullable<Map<String, List<String>>> errors = JsonNullable.<Map<String, List<String>>>undefined(); public static final String JSON_PROPERTY_TYPE = "type"; private JsonNullable<String> type = JsonNullable.<String>undefined(); public static final String JSON_PROPERTY_TITLE = "title"; private JsonNullable<String> title = JsonNullable.<String>undefined(); public static final String JSON_PROPERTY_STATUS = "status"; private JsonNullable<Integer> status = JsonNullable.<Integer>undefined(); public static final String JSON_PROPERTY_DETAIL = "detail"; private JsonNullable<String> detail = JsonNullable.<String>undefined(); public static final String JSON_PROPERTY_INSTANCE = "instance"; private JsonNullable<String> instance = JsonNullable.<String>undefined(); /** * Get errors * @return errors **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonIgnore public Map<String, List<String>> getErrors() { if (errors == null) { errors = JsonNullable.<Map<String, List<String>>>of(new HashMap<>()); } return errors.orElse(null); } @JsonProperty(JSON_PROPERTY_ERRORS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public JsonNullable<Map<String, List<String>>> getErrors_JsonNullable() { return errors; } @JsonProperty(JSON_PROPERTY_ERRORS) private void setErrors_JsonNullable(JsonNullable<Map<String, List<String>>> errors) { this.errors = errors; } public ValidationProblemDetails type(String type) { this.type = JsonNullable.<String>of(type); return this; } /** * Get type * @return type **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonIgnore public String getType() { return type.orElse(null); } @JsonProperty(JSON_PROPERTY_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public JsonNullable<String> getType_JsonNullable() { return type; } @JsonProperty(JSON_PROPERTY_TYPE) public void setType_JsonNullable(JsonNullable<String> type) { this.type = type; } public void setType(String type) { this.type = JsonNullable.<String>of(type); } public ValidationProblemDetails title(String title) { this.title = JsonNullable.<String>of(title); return this; } /** * Get title * @return title **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonIgnore public String getTitle() { return title.orElse(null); } @JsonProperty(JSON_PROPERTY_TITLE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public JsonNullable<String> getTitle_JsonNullable() { return title; } @JsonProperty(JSON_PROPERTY_TITLE) public void setTitle_JsonNullable(JsonNullable<String> title) { this.title = title; } public void setTitle(String title) { this.title = JsonNullable.<String>of(title); } public ValidationProblemDetails status(Integer status) { this.status = JsonNullable.<Integer>of(status); return this; } /** * Get status * @return status **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonIgnore public Integer getStatus() { return status.orElse(null); } @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public JsonNullable<Integer> getStatus_JsonNullable() { return status; } @JsonProperty(JSON_PROPERTY_STATUS) public void setStatus_JsonNullable(JsonNullable<Integer> status) { this.status = status; } public void setStatus(Integer status) { this.status = JsonNullable.<Integer>of(status); } public ValidationProblemDetails detail(String detail) { this.detail = JsonNullable.<String>of(detail); return this; } /** * Get detail * @return detail **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonIgnore public String getDetail() { return detail.orElse(null); } @JsonProperty(JSON_PROPERTY_DETAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public JsonNullable<String> getDetail_JsonNullable() { return detail; } @JsonProperty(JSON_PROPERTY_DETAIL) public void setDetail_JsonNullable(JsonNullable<String> detail) { this.detail = detail; } public void setDetail(String detail) { this.detail = JsonNullable.<String>of(detail); } public ValidationProblemDetails instance(String instance) { this.instance = JsonNullable.<String>of(instance); return this; } /** * Get instance * @return instance **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonIgnore public String getInstance() { return instance.orElse(null); } @JsonProperty(JSON_PROPERTY_INSTANCE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public JsonNullable<String> getInstance_JsonNullable() { return instance; } @JsonProperty(JSON_PROPERTY_INSTANCE) public void setInstance_JsonNullable(JsonNullable<String> instance) { this.instance = instance; } public void setInstance(String instance) { this.instance = JsonNullable.<String>of(instance); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ValidationProblemDetails validationProblemDetails = (ValidationProblemDetails) o; return Objects.equals(this.errors, validationProblemDetails.errors) && Objects.equals(this.type, validationProblemDetails.type) && Objects.equals(this.title, validationProblemDetails.title) && Objects.equals(this.status, validationProblemDetails.status) && Objects.equals(this.detail, validationProblemDetails.detail) && Objects.equals(this.instance, validationProblemDetails.instance); } @Override public int hashCode() { return Objects.hash(errors, type, title, status, detail, instance); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ValidationProblemDetails {\n"); sb.append(" errors: ").append(toIndentedString(errors)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" detail: ").append(toIndentedString(detail)).append("\n"); sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
26.872274
111
0.717946
ed351dfacf76a528dbc0aa2319a72ca0e01a579a
1,220
package com.xiaohuan.multithread; /** * <p>Title: Test1</p > * <p>Description: </p > * <p>Company: http://www.taiyuejinfu.com</p > * <p>Project: spring</p > * * @author: xiaohuan * @Date: 2020/5/19 5:34 下午 * @Version: 1.0 */ import java.util.LinkedList; public class Test1 { //最大的数量 private static final Integer maxCount = 5; //最大的数量 private static final Integer minCount = 0; //弹夹总数量 private LinkedList<Integer> list = new LinkedList<>(); //生产者 public void producerIng() throws Exception { while (true) { Thread.sleep((int) (Math.random() * 10) * 100); synchronized (list) { if (list.size() < maxCount) { list.addLast(1); System.out.println(Thread.currentThread().getName() + "成功压入了一颗子弹=====现在的子弹数量" + list.size()); list.notifyAll(); } else { list.wait(); } } } } //消费者 public void consumerIng() throws Exception { while (true) { Thread.sleep((int) (Math.random() * 10) * 100); synchronized (list) { if (list.size() > minCount) { list.removeFirst(); System.out.println(Thread.currentThread().getName() + "成功射出了一发子弹======现在的子弹数量" + list.size()); list.notifyAll(); } else { list.wait(); } } } } }
19.677419
99
0.60082
d50a7ea6869294e8428a5fc7b96976b003a9af17
552
package oop.inheritance; public class Lebewesen { // Attribute protected String name; protected int alter; protected int gewicht; // Standardkonstruktor public Lebewesen() { name = "unbekannt"; alter = 0; gewicht = 0; } // Paremter-Konstruktor public Lebewesen(String name, int alter, int gewicht) { this.name = name; this.alter = alter; this.gewicht = gewicht; } // Methoden public void bewegen() { } public void essen(String mahl) { } }
18.4
59
0.583333
0634e0d3547bb26bdc2d114c8196bcb965cbd9d5
1,081
/* # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015 */ package com.ibm.streamsx.topology.test; import com.ibm.streamsx.topology.function.UnaryOperator; /** * A functional operator to delay a stream's first tuple; * subsequent tuples are not delayed. * * @param <T> */ public class InitialDelay<T> implements UnaryOperator<T> { private static final long serialVersionUID = 1L; private long initialDelayMsec; /** * @param delayMsec */ public InitialDelay(long delayMsec) { if (delayMsec < 0) throw new IllegalArgumentException("delayMsec"); this.initialDelayMsec = delayMsec; } @Override public T apply(T v) { if (initialDelayMsec != -1) { try { Thread.sleep(initialDelayMsec); } catch (InterruptedException e) { // Force parent thread to terminate Thread.currentThread().interrupt(); return null; } initialDelayMsec = -1; } return v; } }
24.568182
60
0.592044
04486a4e3e8917ab3f889fb6db88cc98e1e41a47
589
package com.davidmedenjak.redditsample.features.home; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.davidmedenjak.redditsample.R; class AccountViewHolder extends RecyclerView.ViewHolder { TextView name; TextView linkKarma; TextView commentKarma; public AccountViewHolder(View itemView) { super(itemView); name = itemView.findViewById(R.id.name); linkKarma = itemView.findViewById(R.id.link_karma); commentKarma = itemView.findViewById(R.id.comment_karma); } }
28.047619
65
0.752122
da09c0b2dacc702cad1ff66a1d90a920cbd6ae4a
12,414
package com.google.common.primitives; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import com.google.common.base.Preconditions; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import javax.annotation.CheckForNull; import javax.annotation.Nullable; @GwtCompatible(emulated = true) public final class Ints { public static final int BYTES = 4; public static final int MAX_POWER_OF_TWO = 1073741824; @GwtCompatible private static class IntArrayAsList extends AbstractList<Integer> implements RandomAccess, Serializable { private static final long serialVersionUID = 0; final int[] array; final int end; final int start; IntArrayAsList(int[] array) { this(array, 0, array.length); } IntArrayAsList(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } public int size() { return this.end - this.start; } public boolean isEmpty() { return false; } public Integer get(int index) { Preconditions.checkElementIndex(index, size()); return Integer.valueOf(this.array[this.start + index]); } public boolean contains(Object target) { return (target instanceof Integer) && Ints.indexOf(this.array, ((Integer) target).intValue(), this.start, this.end) != -1; } public int indexOf(Object target) { if (target instanceof Integer) { int i = Ints.indexOf(this.array, ((Integer) target).intValue(), this.start, this.end); if (i >= 0) { return i - this.start; } } return -1; } public int lastIndexOf(Object target) { if (target instanceof Integer) { int i = Ints.lastIndexOf(this.array, ((Integer) target).intValue(), this.start, this.end); if (i >= 0) { return i - this.start; } } return -1; } public Integer set(int index, Integer element) { Preconditions.checkElementIndex(index, size()); int oldValue = this.array[this.start + index]; this.array[this.start + index] = ((Integer) Preconditions.checkNotNull(element)).intValue(); return Integer.valueOf(oldValue); } public List<Integer> subList(int fromIndex, int toIndex) { Preconditions.checkPositionIndexes(fromIndex, toIndex, size()); if (fromIndex == toIndex) { return Collections.emptyList(); } return new IntArrayAsList(this.array, this.start + fromIndex, this.start + toIndex); } public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (!(object instanceof IntArrayAsList)) { return super.equals(object); } IntArrayAsList that = (IntArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (this.array[this.start + i] != that.array[that.start + i]) { return false; } } return true; } public int hashCode() { int result = 1; for (int i = this.start; i < this.end; i++) { result = (result * 31) + Ints.hashCode(this.array[i]); } return result; } public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(this.array[this.start]); for (int i = this.start + 1; i < this.end; i++) { builder.append(", ").append(this.array[i]); } return builder.append(']').toString(); } int[] toIntArray() { int size = size(); int[] result = new int[size]; System.arraycopy(this.array, this.start, result, 0, size); return result; } } private static final class IntConverter extends Converter<String, Integer> implements Serializable { static final IntConverter INSTANCE = new IntConverter(); private static final long serialVersionUID = 1; private IntConverter() { } protected Integer doForward(String value) { return Integer.decode(value); } protected String doBackward(Integer value) { return value.toString(); } public String toString() { return "Ints.stringConverter()"; } private Object readResolve() { return INSTANCE; } } private enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Ints.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } public String toString() { return "Ints.lexicographicalComparator()"; } } private Ints() { } public static int hashCode(int value) { return value; } public static int checkedCast(long value) { int result = (int) value; if (((long) result) == value) { return result; } throw new IllegalArgumentException("Out of range: " + value); } public static int saturatedCast(long value) { if (value > 2147483647L) { return Integer.MAX_VALUE; } if (value < -2147483648L) { return Integer.MIN_VALUE; } return (int) value; } public static int compare(int a, int b) { if (a < b) { return -1; } return a > b ? 1 : 0; } public static boolean contains(int[] array, int target) { for (int value : array) { if (value == target) { return true; } } return false; } public static int indexOf(int[] array, int target) { return indexOf(array, target, 0, array.length); } private static int indexOf(int[] array, int target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } public static int indexOf(int[] array, int[] target) { Preconditions.checkNotNull(array, "array"); Preconditions.checkNotNull(target, "target"); if (target.length == 0) { return 0; } int i = 0; while (i < (array.length - target.length) + 1) { int j = 0; while (j < target.length) { if (array[i + j] != target[j]) { i++; } else { j++; } } return i; } return -1; } public static int lastIndexOf(int[] array, int target) { return lastIndexOf(array, target, 0, array.length); } private static int lastIndexOf(int[] array, int target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } public static int min(int... array) { boolean z; if (array.length > 0) { z = true; } else { z = false; } Preconditions.checkArgument(z); int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } public static int max(int... array) { boolean z; if (array.length > 0) { z = true; } else { z = false; } Preconditions.checkArgument(z); int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } public static int[] concat(int[]... arrays) { int length = 0; for (int[] array : arrays) { length += array.length; } int[] result = new int[length]; int pos = 0; for (int[] array2 : arrays) { System.arraycopy(array2, 0, result, pos, array2.length); pos += array2.length; } return result; } @GwtIncompatible public static byte[] toByteArray(int value) { return new byte[]{(byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value}; } @GwtIncompatible public static int fromByteArray(byte[] bytes) { boolean z; if (bytes.length >= 4) { z = true; } else { z = false; } Preconditions.checkArgument(z, "array too small: %s < %s", bytes.length, 4); return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); } @GwtIncompatible public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { return (((b1 << 24) | ((b2 & 255) << 16)) | ((b3 & 255) << 8)) | (b4 & 255); } @Beta public static Converter<String, Integer> stringConverter() { return IntConverter.INSTANCE; } public static int[] ensureCapacity(int[] array, int minLength, int padding) { boolean z; boolean z2 = true; if (minLength >= 0) { z = true; } else { z = false; } Preconditions.checkArgument(z, "Invalid minLength: %s", minLength); if (padding < 0) { z2 = false; } Preconditions.checkArgument(z2, "Invalid padding: %s", padding); return array.length < minLength ? Arrays.copyOf(array, minLength + padding) : array; } public static String join(String separator, int... array) { Preconditions.checkNotNull(separator); if (array.length == 0) { return ""; } StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } public static int[] toArray(Collection<? extends Number> collection) { if (collection instanceof IntArrayAsList) { return ((IntArrayAsList) collection).toIntArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; int[] array = new int[len]; for (int i = 0; i < len; i++) { array[i] = ((Number) Preconditions.checkNotNull(boxedArray[i])).intValue(); } return array; } public static List<Integer> asList(int... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new IntArrayAsList(backingArray); } @CheckForNull @Nullable @Beta public static Integer tryParse(String string) { return tryParse(string, 10); } @CheckForNull @Nullable @Beta public static Integer tryParse(String string, int radix) { Long result = Longs.tryParse(string, radix); if (result == null || result.longValue() != ((long) result.intValue())) { return null; } return Integer.valueOf(result.intValue()); } }
29.913253
134
0.525616
3f24085f09f981c8d8e308d41879461a477f4024
806
package unit.dev.andersoncontreira.trainingddd.infrastructure.persistence.hibernate.repositories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import unit.AbstractUnitTestCase; class CategoryRepositoryTest extends AbstractUnitTestCase { @BeforeEach void setUp() { // PersistenceConfiguration persistenceConfiguration = new PersistenceConfigurationFactory().factory(); // org.hibernate.SessionFactory sessionFactory = new SessionFactory(persistenceConfiguration).factory(); // categoryRepository = new CategoryRepository(logger, sessionFactory); } @Test void find() { } @Test void list() { } @Test void create() { } @Test void update() { } @Test void deleted() { } }
22.388889
118
0.689826
427690bb3803512b06f1144eb53e22ccd8ba0140
2,086
package spring.boot._2.test.by.howtodoinjava.reactive.webflux; import de.flapdoodle.embed.mongo.MongodExecutable; import de.flapdoodle.embed.mongo.MongodProcess; import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.IMongodConfig; import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; import de.flapdoodle.embed.mongo.config.Net; import de.flapdoodle.embed.mongo.distribution.Version; import de.flapdoodle.embed.process.runtime.AbstractProcess; import de.flapdoodle.embed.process.runtime.Executable; import de.flapdoodle.embed.process.runtime.Network; import java.io.IOException; import java.util.Optional; import javax.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Profile("development") @Configuration public class MongoConfiguration { @Value("${mongodb.host:localhost}") private String host; @Value("${mongodb.port:27017}") private int port; @Bean public MongodExecutable mongodExecutable() throws IOException { MongodStarter starter = MongodStarter.getDefaultInstance(); // by default no authentication IMongodConfig mongodConfig = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(host, port, Network.localhostIsIPv6())) .build(); return starter.prepare(mongodConfig); } @Bean public MongodProcess mongodProcess(MongodExecutable mongodExecutable) throws IOException { return mongodExecutable.start(); } @Autowired MongodExecutable mongodExecutable; // for shutdown @Autowired MongodProcess mongodProcess; // for shutdown @PreDestroy public void shutdownMongo() { // even do not have this, it will auto shutdown Optional.of(mongodProcess).ifPresent(AbstractProcess::stop); Optional.of(mongodExecutable).ifPresent(Executable::stop); } }
35.355932
92
0.784276
37fdf853d3a2fa1d9a7132bff36d347f3c014524
5,366
package com.github.suosi.commons.spider.utils; import com.google.common.net.InternetDomainName; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; public class DomainUtilsTest { @Test public void topDomain() { System.out.println(DomainUtils.topDomain("hi.chinanews.com")); System.out.println(DomainUtils.topDomain("a.wh.cn")); System.out.println(DomainUtils.topDomain("siat.ac.cn")); System.out.println(DomainUtils.topDomain("abc.spring.io")); System.out.println(DomainUtils.topDomain("abc.spring.ai")); System.out.println(DomainUtils.topDomain("www.china-embassy.or.jp")); System.out.println(DomainUtils.topDomain("whszdj.wh.cn")); System.out.println(DomainUtils.topDomain("gk.wh.cn")); System.out.println(DomainUtils.topDomain("xwxc.mwr.cn")); System.out.println(DomainUtils.topDomain("legismac.safp.gov.mo")); System.out.println(DomainUtils.topDomain("dezhou.rcsd.cn")); System.out.println(DomainUtils.topDomain("www.gov.cn")); System.out.println(DomainUtils.topDomain("scopsr.gov.cn")); } @Test public void topDomainFromUrl() { System.out.println(DomainUtils.topDomainFromUrl("https://www.baidu.com/news")); } @Test public void topDomain2() { String[] subDomains = { "spartanswire.usatoday.com", "badgerswire.usatoday.com", "wolverineswire.usatoday.com", "volswire.usatoday.com", "buckeyeswire.usatoday.com", "ugawire.usatoday.com", "guce.yahoo.com", "pageviewer.yomiuri.co.jp", "partner.buy.yahoo.com", "tw.edit.yahoo.com", "tw.security.yahoo.com", "tw.knowledge.yahoo.com", "travel.m.pchome.com.tw", "blogs.reuters.com", "reuters.com", "tw.money.yahoo.com", "tw.mobile.yahoo.com", "asia.adspecs.yahoo.com", "learngerman.dw.com", "conference.udn.com", "mediadirectory.economist.com", "eventsregistration.economist.com", "eventscustom.economist.com", "technologyforchange.economist.com", "sustainabilityregistration.economist.com", "learn-french.lemonde.fr", "jungeleute.sueddeutsche.de", "jetzt.sueddeutsche.de", "coupons.cnn.com", "www.cnn.com", "www.khmer.voanews.com", "www.burmese.voanews.com", "www.tigrigna.voanews.com", "nkpos.nikkei.co.jp", "nvs.nikkei.co.jp", "simonglazin.dailymail.co.uk", "adweb.nikkei.co.jp", "broganblog.dailymail.co.uk", "pclub.nikkei.co.jp", "araward.nikkei.co.jp", "blend.nikkei.co.jp", "esf.nikkei.co.jp", "hoshiaward.nikkei.co.jp", "marketing.nikkei.com", "www.now.com", "jp.wsj.com", "subscribenow.economist.com", "sportsawards.usatoday.com", "cooking.nytimes.com" }; for (String subDomain : subDomains) { String domain = DomainUtils.topDomain(subDomain); System.out.println(domain + "," + subDomain); } } @Test public void topDomain22() { File file = new File("tmpUrls.txt"); BufferedReader reader = null; StringBuffer sbf = new StringBuffer(); try { reader = new BufferedReader(new FileReader(file)); String tempStr; while ((tempStr = reader.readLine()) != null) { System.out.println(tempStr.toString()); String url = tempStr.toString(); String domain = ""; String topDomain = ""; URL parse = UrlUtils.parse(url); if (parse != null) { domain = parse.getHost(); if (StringUtils.isNotBlank(domain) && InternetDomainName.isValid(domain)) { InternetDomainName topDomain2 = InternetDomainName.from(domain).topPrivateDomain(); topDomain = topDomain2.toString(); } } String content = topDomain + "##" + domain + "##" + url; FileUtils.recordFile("tmpUrls2.txt", content + "\n"); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { e1.printStackTrace(); } } } // for (String subDomain : subDomains) { // String domain = DomainUtils.topDomain(subDomain); // System.out.println(domain + "," + subDomain); // } // } } }
35.071895
107
0.524599
f8f56d75554a388205d9c7af60072ad8821ae8a9
703
package org.phoenix.leetcode.challenges; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class Problem30_WordSearchIITest { private final Problem30_WordSearchII test = new Problem30_WordSearchII(); @Test void findWords() { char[][] board = { {'o', 'a', 'a', 'n'}, {'e', 't', 'a', 'e'}, {'i', 'h', 'k', 'r'}, {'i', 'f', 'l', 'v'} }; String[] words = {"oath", "pea", "eat", "rain"}; List<String> expected = Arrays.asList("eat", "oath"); assertEquals(expected, test.findWords(board, words)); } }
27.038462
77
0.543385
6b4c90181534e400c319f319a3993a86ba6580cc
4,713
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.inbound.endpoint.protocol.grpc; import com.google.protobuf.Empty; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.SynapseException; import org.apache.synapse.core.SynapseEnvironment; import org.apache.synapse.inbound.InboundProcessorParams; import org.apache.synapse.inbound.InboundRequestProcessor; import org.wso2.carbon.inbound.endpoint.protocol.grpc.util.EventServiceGrpc; import org.wso2.carbon.inbound.endpoint.protocol.grpc.util.Event; import java.io.IOException; import java.util.concurrent.TimeUnit; public class InboundGRPCListener implements InboundRequestProcessor { private int port; private GRPCInjectHandler injectHandler; private static final Log log = LogFactory.getLog(InboundGRPCListener.class.getName()); private Server server; public InboundGRPCListener(InboundProcessorParams params) { String injectingSeq = params.getInjectingSeq(); String onErrorSeq = params.getOnErrorSeq(); SynapseEnvironment synapseEnvironment = params.getSynapseEnvironment(); String portParam = params.getProperties().getProperty(InboundGRPCConstants.INBOUND_ENDPOINT_PARAMETER_GRPC_PORT); try { port = Integer.parseInt(portParam); } catch (NumberFormatException e) { log.warn("Exception occurred when getting " + InboundGRPCConstants.INBOUND_ENDPOINT_PARAMETER_GRPC_PORT + " property. Setting the port as " + InboundGRPCConstants.DEFAULT_INBOUND_ENDPOINT_GRPC_PORT); port = InboundGRPCConstants.DEFAULT_INBOUND_ENDPOINT_GRPC_PORT; } injectHandler = new GRPCInjectHandler(injectingSeq, onErrorSeq, false, synapseEnvironment); } public void init() { try { this.start(); } catch (IOException e) { throw new SynapseException("IOException when starting gRPC server: " + e.getMessage(), e); } } public void destroy() { try { this.stop(); } catch (InterruptedException e) { throw new SynapseException("Failed to stop gRPC server: " +e.getMessage()); } } public void start() throws IOException { if (server != null) { throw new IllegalStateException("gRPC Listener Server already started"); } server = ServerBuilder.forPort(port).addService(new EventServiceGrpc.EventServiceImplBase() { @Override public void process(Event request, StreamObserver<Event> responseObserver) { if (log.isDebugEnabled()) { log.debug("Event received for gRPC Listener process method"); } injectHandler.invokeProcess(request, responseObserver); } @Override public void consume(Event request, StreamObserver<Empty> responseObserver) { if (log.isDebugEnabled()) { log.debug("Event received for gRPC Listener consume method"); } injectHandler.invokeConsume(request, responseObserver); responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); } }).build(); server.start(); log.debug("gRPC Listener Server started"); } public void stop() throws InterruptedException { Server s = server; if (s == null) { throw new IllegalStateException("gRPC Listener Server is already stopped"); } server = null; s.shutdown(); if (s.awaitTermination(1, TimeUnit.SECONDS)) { log.debug("gRPC Listener Server stopped"); return; } s.shutdownNow(); if (s.awaitTermination(1, TimeUnit.SECONDS)) { return; } throw new RuntimeException("Unable to shutdown gRPC Listener Server"); } }
39.940678
121
0.670274
465bd3a6814135e266030f207a406501df133aac
213
@ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault package net.silentchaos512.gear.api.stats; import net.minecraft.MethodsReturnNonnullByDefault; import javax.annotation.ParametersAreNonnullByDefault;
30.428571
54
0.896714
8ec032751323e5d9df1a82104a27019c99fb48ae
7,650
package seedu.souschef.storage; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import seedu.souschef.commons.core.ComponentManager; import seedu.souschef.commons.core.LogsCenter; import seedu.souschef.commons.events.model.AppContentChangedEvent; import seedu.souschef.commons.events.storage.DataSavingExceptionEvent; import seedu.souschef.commons.events.storage.SwitchFeatureStorageEvent; import seedu.souschef.commons.exceptions.DataConversionException; import seedu.souschef.logic.parser.Context; import seedu.souschef.model.AppContent; import seedu.souschef.model.ReadOnlyAppContent; import seedu.souschef.model.UserPrefs; import seedu.souschef.model.util.SampleDataUtil; import seedu.souschef.storage.favourite.XmlFavouriteStorage; import seedu.souschef.storage.healthplan.XmlHealthPlanStorage; import seedu.souschef.storage.ingredient.XmlIngredientStorage; import seedu.souschef.storage.mealplanner.XmlMealPlanStorage; import seedu.souschef.storage.recipe.XmlRecipeStorage; /** * Manages storage of AppContent data in local storage. */ public class StorageManager extends ComponentManager implements Storage { private static final Logger logger = LogsCenter.getLogger(StorageManager.class); private FeatureStorage featureStorage; private UserPrefsStorage userPrefsStorage; private Map<Context, FeatureStorage> listOfFeatureStorage; private AppContent appContent; public StorageManager(UserPrefsStorage userPrefsStorage, UserPrefs userPrefs, AppContent appContent) { super(); this.appContent = appContent; this.userPrefsStorage = userPrefsStorage; this.listOfFeatureStorage = new HashMap<>(); FeatureStorage recipeStorage = new XmlRecipeStorage(userPrefs.getRecipeFilePath()); FeatureStorage ingredientStorage = new XmlIngredientStorage(userPrefs.getIngredientFilePath()); FeatureStorage healthPlanStorage = new XmlHealthPlanStorage(userPrefs.getHealthplanPath()); FeatureStorage mealPlanStorage = new XmlMealPlanStorage(userPrefs.getMealPlanPath()); FeatureStorage favouriteStorage = new XmlFavouriteStorage(userPrefs.getFavouritePath()); listOfFeatureStorage.put(Context.RECIPE, recipeStorage); listOfFeatureStorage.put(Context.INGREDIENT, ingredientStorage); listOfFeatureStorage.put(Context.HEALTH_PLAN, healthPlanStorage); listOfFeatureStorage.put(Context.MEAL_PLAN, mealPlanStorage); listOfFeatureStorage.put(Context.FAVOURITES, favouriteStorage); this.featureStorage = recipeStorage; } public StorageManager(FeatureStorage featureStorage, UserPrefsStorage userPrefsStorage) { super(); this.featureStorage = featureStorage; this.userPrefsStorage = userPrefsStorage; this.listOfFeatureStorage = new HashMap<>(); } public StorageManager () { this.listOfFeatureStorage = new HashMap<>(); } // ================ UserPrefs methods ============================== @Override public Path getUserPrefsFilePath() { return userPrefsStorage.getUserPrefsFilePath(); } @Override public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException { return userPrefsStorage.readUserPrefs(); } @Override public void saveUserPrefs(UserPrefs userPrefs) throws IOException { userPrefsStorage.saveUserPrefs(userPrefs); } // ================ AppContent methods ============================== @Override public Path getFeatureFilePath() { return featureStorage.getFeatureFilePath(); } @Override public Map<Context, FeatureStorage> getListOfFeatureStorage() { return listOfFeatureStorage; } @Subscribe protected void handleSwitchFeatureStorageEvent(SwitchFeatureStorageEvent event) { this.featureStorage = listOfFeatureStorage.get(event.context); } /** * this function is for reading specific features only */ @Override public Optional<ReadOnlyAppContent> readFeature() throws DataConversionException, IOException { return readFeature(featureStorage.getFeatureFilePath()); } @Override public Optional<ReadOnlyAppContent> readFeature(Path filePath) throws DataConversionException, IOException { logger.fine("Attempting to read data from file: " + filePath); return featureStorage.readFeature(filePath); } /** * Read data for a specific feature if available in its default file path. * If not, retrieve sample data from the supplier. * @param context Specify the feature to be read. * @param sampleSupplier Supply sample data as backup. */ private void readFeature(Context context, Supplier<ReadOnlyAppContent> sampleSupplier) throws DataConversionException, IOException { if (listOfFeatureStorage.containsKey(context)) { this.featureStorage = listOfFeatureStorage.get(context); this.appContent.includeData(readFeature(this.featureStorage.getFeatureFilePath()) .orElseGet(sampleSupplier)); } } @Override public Optional<ReadOnlyAppContent> readAll() throws DataConversionException, IOException { readFeature(Context.RECIPE, SampleDataUtil::getSampleRecipes); readFeature(Context.INGREDIENT, SampleDataUtil::getSampleIngredients); readFeature(Context.HEALTH_PLAN, SampleDataUtil::getSampleHealthPlans); readFeature(Context.MEAL_PLAN, SampleDataUtil::getSampleDays); readFeature(Context.FAVOURITES, SampleDataUtil::getSampleFavourites); featureStorage = listOfFeatureStorage.get(Context.RECIPE); return Optional.of(this.appContent); } @Override public void saveFeature(ReadOnlyAppContent appContent) throws IOException { saveFeature(appContent, this.featureStorage.getFeatureFilePath()); } @Override public void saveFeature(ReadOnlyAppContent appContent, Path filePath) throws IOException { logger.fine("Attempting to write to data file: " + filePath); if (this.featureStorage instanceof XmlRecipeStorage) { XmlRecipeStorage temp = new XmlRecipeStorage(filePath); temp.saveFeature(appContent, filePath); } else if (this.featureStorage instanceof XmlIngredientStorage) { XmlIngredientStorage temp = new XmlIngredientStorage(filePath); temp.saveFeature(appContent, filePath); } else if (this.featureStorage instanceof XmlHealthPlanStorage) { XmlHealthPlanStorage temp = new XmlHealthPlanStorage(filePath); temp.saveFeature(appContent, filePath); } else if (this.featureStorage instanceof XmlMealPlanStorage) { XmlMealPlanStorage temp = new XmlMealPlanStorage(filePath); temp.saveFeature(appContent, filePath); } else if (this.featureStorage instanceof XmlFavouriteStorage) { XmlFavouriteStorage temp = new XmlFavouriteStorage(filePath); temp.saveFeature(appContent, filePath); } } @Override @Subscribe public void handleAppContentChangedEvent(AppContentChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Local data changed, saving to file")); try { saveFeature(event.data); } catch (IOException e) { raise(new DataSavingExceptionEvent(e)); } } }
41.129032
112
0.730327
b56919152a759439e0168977a3c16120237189be
11,106
/* * 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.pluto.driver.container; import javax.portlet.PortalContext; import org.apache.pluto.container.CCPPProfileService; import org.apache.pluto.container.EventCoordinationService; import org.apache.pluto.container.FilterManagerService; import org.apache.pluto.container.NamespaceMapper; import org.apache.pluto.container.PortletEnvironmentService; import org.apache.pluto.container.PortletInvokerService; import org.apache.pluto.container.PortletPreferencesService; import org.apache.pluto.container.PortletRequestContextService; import org.apache.pluto.container.PortletURLListenerService; import org.apache.pluto.container.RequestDispatcherService; import org.apache.pluto.container.UserInfoService; import org.apache.pluto.container.driver.OptionalContainerServices; import org.apache.pluto.container.driver.PortalAdministrationService; import org.apache.pluto.container.driver.PortalDriverServices; import org.apache.pluto.container.driver.PortletContextService; import org.apache.pluto.container.driver.PortletRegistryService; import org.apache.pluto.container.driver.RequiredContainerServices; import org.apache.pluto.container.impl.PortletEnvironmentServiceImpl; import org.apache.pluto.container.impl.RequestDispatcherServiceImpl; import org.apache.pluto.container.impl.PortletAppDescriptorServiceImpl; public class PortalDriverServicesImpl implements RequiredContainerServices, OptionalContainerServices, PortalDriverServices { /* * required services */ private PortalContext context; private EventCoordinationService eventCoordinationService; private PortletRequestContextService portletRequestContextService; private CCPPProfileService ccppProfileService; private FilterManagerService filterManagerService; private PortletURLListenerService portletURLListenerService; /* * optional services */ private PortletPreferencesService portletPreferencesService; private PortletInvokerService portletInvokerService; private PortletEnvironmentService portletEnvironmentService; private UserInfoService userInfoService; private NamespaceMapper namespaceMapper; private RequestDispatcherService rdService; /* * portal driver services */ private PortletContextService portletContextService; private PortletRegistryService portletRegistryService; private PortalAdministrationService portalAdministrationService; /** * Constructor for just passing in the required services. * @param context * @param portletRequestContextService * @param eventCoordinationService * @param filterManagerService * @param portletURLListenerService */ public PortalDriverServicesImpl(PortalContext context, PortletRequestContextService portletRequestContextService, EventCoordinationService eventCoordinationService, FilterManagerService filterManagerService, PortletURLListenerService portletURLListenerService) { this(context, portletRequestContextService, eventCoordinationService, filterManagerService, portletURLListenerService, null); } /** * Constructor for passing in the required services and optional container services. * @param context * @param portletRequestContextService * @param eventCoordinationService * @param filterManagerService * @param portletURLListenerService * @param optionalServices Optional services (if this is null, default services are used) */ public PortalDriverServicesImpl(PortalContext context, PortletRequestContextService portletRequestContextService, EventCoordinationService eventCoordinationService, FilterManagerService filterManagerService, PortletURLListenerService portletURLListenerService, OptionalContainerServices optionalServices) { this(context, portletRequestContextService, eventCoordinationService, filterManagerService, portletURLListenerService, optionalServices, null, null, null); } /** * Constructor for passing in the required services and optional container services. * @param context * @param portletRequestContextService * @param eventCoordinationService * @param filterManagerService * @param portletURLListenerService * @param optionalServices Optional services (if this is null, default services are used) */ public PortalDriverServicesImpl(PortalContext context, PortletRequestContextService portletRequestContextService, EventCoordinationService eventCoordinationService, FilterManagerService filterManagerService, PortletURLListenerService portletURLListenerService, OptionalContainerServices optionalServices, PortletContextService portletContextService, PortletRegistryService portletRegistryService, PortalAdministrationService portalAdministrationService) { // set required first this.context = context; this.eventCoordinationService = eventCoordinationService; this.portletRequestContextService = portletRequestContextService; this.filterManagerService = filterManagerService; this.portletURLListenerService = portletURLListenerService; // now optional if ( optionalServices != null ) { ccppProfileService = optionalServices.getCCPPProfileService(); portletPreferencesService = optionalServices.getPortletPreferencesService(); portletInvokerService = optionalServices.getPortletInvokerService(); portletEnvironmentService = optionalServices.getPortletEnvironmentService(); userInfoService = optionalServices.getUserInfoService(); namespaceMapper = optionalServices.getNamespaceMapper(); rdService = optionalServices.getRequestDispatcherService(); } // and finally driver this.portletContextService = portletContextService; this.portletRegistryService = portletRegistryService; this.portalAdministrationService = portalAdministrationService; createDefaultServicesIfNeeded(); } /** * Constructor * @param required * @param optional Optional services (if this is null, default services are used) */ public PortalDriverServicesImpl(RequiredContainerServices required, OptionalContainerServices optional) { this(required.getPortalContext(), required.getPortletRequestContextService(), required.getEventCoordinationService(), required.getFilterManagerService(), required.getPortletURLListenerService(), optional); } protected void createDefaultServicesIfNeeded() { rdService = rdService == null ? new RequestDispatcherServiceImpl() : rdService; portletRegistryService = portletRegistryService == null ? new PortletContextManager(rdService, new PortletAppDescriptorServiceImpl()) : portletRegistryService; portletContextService = portletContextService == null ? (PortletContextManager)portletRegistryService : portletContextService; portalAdministrationService = portalAdministrationService == null ? new DefaultPortalAdministrationService() : portalAdministrationService; ccppProfileService = ccppProfileService == null ? new DummyCCPPProfileServiceImpl() : ccppProfileService; portletPreferencesService = portletPreferencesService == null ? new DefaultPortletPreferencesService() : portletPreferencesService; portletInvokerService = portletInvokerService == null ? new DefaultPortletInvokerService(portletContextService) : portletInvokerService; portletEnvironmentService = portletEnvironmentService == null ? new PortletEnvironmentServiceImpl() : portletEnvironmentService; userInfoService = userInfoService == null ? new DefaultUserInfoService() : userInfoService; namespaceMapper = namespaceMapper == null ? new DefaultNamespaceMapper() : namespaceMapper; } /** * @see org.apache.pluto.container.ContainerServices#getPortalContext() */ public PortalContext getPortalContext() { return context; } /** * The PortletPreferencesService provides access to the portal's * PortletPreference persistence mechanism. * @return a PortletPreferencesService instance. */ public PortletPreferencesService getPortletPreferencesService() { return this.portletPreferencesService; } /** * Returns null to use pluto's default */ public PortletRegistryService getPortletRegistryService() { return this.portletRegistryService; } public PortletContextService getPortletContextService() { return this.portletContextService; } public PortletRequestContextService getPortletRequestContextService() { return this.portletRequestContextService; } public PortletEnvironmentService getPortletEnvironmentService() { return this.portletEnvironmentService; } public PortletInvokerService getPortletInvokerService() { return this.portletInvokerService; } public CCPPProfileService getCCPPProfileService() { return ccppProfileService; } public PortalAdministrationService getPortalAdministrationService() { return this.portalAdministrationService; } public UserInfoService getUserInfoService() { return this.userInfoService; } public NamespaceMapper getNamespaceMapper() { return this.namespaceMapper; } public CCPPProfileService getCcppProfileService() { return ccppProfileService; } public EventCoordinationService getEventCoordinationService() { return eventCoordinationService; } public FilterManagerService getFilterManagerService() { return filterManagerService; } public PortletURLListenerService getPortletURLListenerService() { return portletURLListenerService; } public RequestDispatcherService getRequestDispatcherService() { return rdService; } }
40.98155
167
0.753827
d4ebc221b31962ddd26a7d4a54454ed617f9efb9
1,836
package org.edmcouncil.spec.fibo.view.controller; import java.util.List; import org.edmcouncil.spec.fibo.weasel.model.module.FiboModule; import org.edmcouncil.spec.fibo.weasel.ontology.DataManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.edmcouncil.spec.fibo.view.util.ModelBuilder; import org.edmcouncil.spec.fibo.weasel.model.details.OwlDetails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestParam; /** * @author Michał Daniel (michal.daniel@makolab.com) */ @Controller @RequestMapping(value = {"/", "/index", "module"}) public class ModuleController { private static final Logger LOG = LoggerFactory.getLogger(ModuleController.class); @Autowired private DataManager ontologyManager; @GetMapping("/json") public ResponseEntity<List<FiboModule>> getAllModulesDataAsJson() { LOG.debug("[REQ] GET : module / json"); List<FiboModule> modules = ontologyManager.getAllModulesData(); return ResponseEntity.ok(modules); } @GetMapping public String getModulesMeta( @RequestParam(value = "meta", required = false) String query, Model model) { LOG.debug("[REQ] GET: module /"); List<FiboModule> modules = ontologyManager.getAllModulesData(); ModelBuilder mb = new ModelBuilder(model); if (query != null) { OwlDetails details = ontologyManager.getDetailsByIri(query); mb.ontoDetails(details).isGrouped(true); } mb.emptyQuery().modelTree(modules); model = mb.getModel(); return "module"; } }
31.655172
84
0.757625
7274fc952d0eb3a5df57146cd616d6b95bba70fe
8,713
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import util.DBConnection; import java.sql.*; public final class studentView_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html>\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"sidenav.css\"> \n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"TableStyleSheet.css\"> \n"); out.write(" <title></title>\n"); out.write(" <style>\n"); out.write("\n"); out.write(" .customers {\n"); out.write(" font-family: \"Trebuchet MS\", Arial, Helvetica, sans-serif;\n"); out.write(" border-collapse: collapse;\n"); out.write(" width: 100%;\n"); out.write("\n"); out.write(" }\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" .customers td, .customers th {\n"); out.write(" border: 1px solid #ddd;\n"); out.write(" padding: 8px;\n"); out.write("\n"); out.write("\n"); out.write(" }\n"); out.write("\n"); out.write(" .customers tr:nth-child(even){background-color: #f2f2f2;}\n"); out.write("\n"); out.write(" .customers tr:hover {background-color: #ddd;}\n"); out.write("\n"); out.write(" .customers th {\n"); out.write(" padding-top: 12px;\n"); out.write(" padding-bottom: 12px;\n"); out.write(" text-align: left;\n"); out.write(" background-color: #008ae6;\n"); out.write(" color: white;\n"); out.write(" width:90px;\n"); out.write(" }\n"); out.write(" </style>\n"); out.write("\n"); out.write(" "); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/WEB-INF/views/header.jsp", out, false); out.write("\n"); out.write(" </head>\n"); out.write(" <body>\n"); out.write("\n"); out.write(" "); Connection con = null; out.write("\n"); out.write("\n"); out.write(" "); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/WEB-INF/views/studentnavi.jsp", out, false); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" <div class=\"\" >\n"); out.write("\n"); out.write(" <div class=\"sidenav\" style=\"float:left;\">\n"); out.write(" <ul> \n"); out.write(" \n"); out.write(" <a href=\"studentView.jsp\">View Registered Students</a>\n"); out.write(" <a href=\"studentEdit.jsp\">Edit & Update</a>\n"); out.write(" <a href=\"studentDelete.jsp\">Delete</a>\n"); out.write(" <form action=\"studentReport\" method=\"post\" >\n"); out.write(" <input type=\"submit\" value=\"Generate Report\">\n"); out.write(" \n"); out.write(" </form>\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write("\n"); out.write("\n"); out.write(" <div class=\"\" style=\"float:left;padding-left: 100px;padding-top: 40px;\">\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" \n"); out.write("\n"); out.write(" <table class=\"customers\" >\n"); out.write(" <tr>\n"); out.write(" <th> Student ID </th>\n"); out.write(" <th> Student Name </th>\n"); out.write(" <th> Address </th>\n"); out.write(" <th> Contact Number </th>\n"); out.write(" <th> Email </th>\n"); out.write(" <th> NIC </th>\n"); out.write(" <th> Course Code </th>\n"); out.write(" \n"); out.write(" </tr>\n"); out.write("\n"); out.write(" "); try { con = DBConnection.createConnection(); Statement st = con.createStatement(); String sql = "Select * from student"; ResultSet rs = st.executeQuery(sql); while (rs.next()) { out.write("\n"); out.write("\n"); out.write("\n"); out.write(" <tr>\n"); out.write("\n"); out.write(" <td> "); out.print(rs.getString("userID")); out.write(" </td>\n"); out.write(" <td> "); out.print(rs.getString("fullname")); out.write("</td>\n"); out.write(" <td> "); out.print( rs.getString("address")); out.write("</td>\n"); out.write(" <td> "); out.print( rs.getString("contactNum")); out.write("</td>\n"); out.write(" <td> "); out.print(rs.getString("email")); out.write("</td>\n"); out.write(" <td> "); out.print(rs.getString("NIC")); out.write("</td>\n"); out.write(" <td> "); out.print(rs.getString("courseCode")); out.write("</td>\n"); out.write("\n"); out.write("\n"); out.write(" \n"); out.write(" </tr>\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" "); } con.close(); } catch (Exception e) { System.out.println("error"); } out.write("\n"); out.write(" </table\n"); out.write("\n"); out.write(" </div>\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" </body>\n"); out.write("</html>\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
38.724444
138
0.46356
17ff8a6414be083cecd761decdb64149d441a8d5
499
package adapter; import com.google.inject.Inject; import dto.Example; import service.TestService; import java.util.concurrent.Future; public class TestAdapter { @Inject private TestService testService; public String get() { return testService.getString(); } public Future getFuture(String a) { return testService.getFuture(a); } public Example getExample(String text) { return testService.getExample(text); } }
19.192308
45
0.657315
8a6976fc2238e7a8b58509ffccda626863fc8285
495
public static boolean copy(String source, String dest) { int bytes; byte array[] = new byte[BUFFER_LEN]; try { InputStream is = new FileInputStream(source); OutputStream os = new FileOutputStream(dest); while ((bytes = is.read(array, 0, BUFFER_LEN)) > 0) os.write(array, 0, bytes); is.close(); os.close(); return true; } catch (IOException e) { return false; } }
33
90
0.523232
82ff7972d47ac79c8c477d17fa94663b8fd9b4b9
910
package app.example.store.jwt; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class JwtCanceledAccessTokenServiceImpl implements JwtCanceledAccessTokenService { @Autowired JwtCanceledAccessTokenRepository repository; @Override public JwtCanceledAccessToken create(JwtCanceledAccessToken token) { return repository.save(token); } @Override public JwtCanceledAccessToken read(Long id) { return repository.getOne(id); } @Override public JwtCanceledAccessToken update(JwtCanceledAccessToken token) { return repository.save(token); } @Override public void delete(Long id) { repository.deleteById(id); } @Override public List<JwtCanceledAccessToken> list() { return repository.findAll(); } }
22.75
89
0.721978
bd183cccb36f389a52080162531dcb59891b0d69
1,493
package fr.kayrnt.tindplayer.fragment; import android.os.Bundle; import com.google.android.gms.maps.GoogleMap; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import fr.kayrnt.tindplayer.R; import fr.kayrnt.tindplayer.utils.AdvSupportMapFragment; /** * Created by Kayrnt on 30/03/2014. */ public abstract class MapBasedFragment extends Fragment implements AdvSupportMapFragment .MySupportMapFragmentListener { protected GoogleMap map; protected AdvSupportMapFragment mapFragment; /*public void onDestroyView() { if (mapFragment != null) { try { FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); ft.remove(mapFragment).commit(); } catch (Exception e) { e.printStackTrace(); } } map = null; super.onDestroyView(); Log.i("=> Map based fragment", "destroy view"); }*/ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); FragmentManager fm = getChildFragmentManager(); mapFragment = (AdvSupportMapFragment) fm.findFragmentById(R.id.map); if (mapFragment == null) { mapFragment = AdvSupportMapFragment.newInstance(); fm.beginTransaction().replace(R.id.map, mapFragment).commit(); mapFragment.setListener(this); } } }
31.104167
102
0.665104
2d21727fc10942ea4b3a58b55b1cb1c6bc4603e8
379
package zmaster587.libVulpes.inventory.modules; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public interface IButtonInventory { /** * Called on the client when a user presses a button * @param buttonId id of the button pressed */ @OnlyIn(value=Dist.CLIENT) void onInventoryButtonPressed(ModuleButton buttonId); }
23.6875
54
0.783641
793ba017402ce109ae1b1b73b0e71928c2b86f56
16,622
package com.pungwe.cms.core.theme.services; import com.pungwe.cms.core.annotations.stereotypes.Theme; import com.pungwe.cms.core.annotations.system.ModuleDependency; import com.pungwe.cms.core.module.services.ModuleManagementService; import com.pungwe.cms.core.system.element.templates.PageElement; import com.pungwe.cms.core.theme.ThemeConfig; import com.pungwe.cms.core.utils.services.HookService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.stereotype.Service; import org.springframework.util.ResourceUtils; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.stream.Collectors; import static com.lyncode.jtwig.util.LocalThreadHolder.getServletRequest; /** * Created by ian on 29/01/2016. */ @Service public class ThemeManagementService { private static final Logger LOG = LoggerFactory.getLogger(ThemeManagementService.class); @Autowired private ThemeConfigService<? extends ThemeConfig> themeConfigService; @Autowired private HookService hookService; @Autowired private ModuleManagementService moduleManagementService; @Autowired private ApplicationContext rootContext; private Map<String, AnnotationConfigApplicationContext> themeContexts = new TreeMap<>(); public ApplicationContext getThemeContext(String name) { return themeContexts.get(name); } public boolean enable(String theme) { if (StringUtils.isEmpty(theme)) { return false; } // Fetch the theme config ThemeConfig config = themeConfigService.getTheme(theme); try { Class<?> c = Class.forName(config.getEntryPoint()); Theme info = c.getAnnotation(Theme.class); String parent = info.parent(); if (!StringUtils.isEmpty(parent) && !themeConfigService.isEnabled(parent) && !enable(parent)) { LOG.error("Could not enabled parent theme: " + parent + " for theme: " + theme); return false; } // Enable dependencies moduleManagementService.enable(Arrays.asList(info.dependencies()).stream().map(moduleDependency -> { return moduleDependency.value(); }).collect(Collectors.toList())); themeConfigService.setThemeEnabled(theme, true); return true; } catch (ClassNotFoundException ex) { LOG.error("Could not enable theme: " + theme, ex); themeConfigService.removeThemes(theme); return false; } } public void setDefaultTheme(String theme) { themeConfigService.setDefaultTheme(theme); } public void setDefaultAdminTheme(String theme) { themeConfigService.setDefaultAdminTheme(theme); } public boolean disable(String theme) { themeConfigService.setThemeEnabled(theme, false); AnnotationConfigApplicationContext ctx = themeContexts.remove(theme); ctx.close(); return ctx.isActive(); } public void startEnabledThemes() { removeMissingThemes(); // Get a list of enabled themes Set<ThemeConfig> enabled = (Set<ThemeConfig>) themeConfigService.listEnabledThemes(); // Create application contexts for the enabled themes. This is different from the module // context, whereby the modules share a single application context, themes need to be isolated // from each other in order to function correctly... enabled.stream().sorted((t1, t2) -> { try { // First theme class Class<?> c1 = Class.forName(t1.getEntryPoint()); Theme i1 = c1.getAnnotation(Theme.class); // Second theme class Class<?> c2 = Class.forName(t2.getEntryPoint()); Theme i2 = c2.getAnnotation(Theme.class); // If t1 parent is blank and t2 is not, then t1 should be before t2. if (StringUtils.isEmpty(i1.parent()) && !StringUtils.isEmpty(i2.parent())) { return -1; // If t1 has a parent and t2 does not, then it should be after t2 } else if (!StringUtils.isEmpty(i1.parent()) && StringUtils.isEmpty(i2.parent())) { return 1; } // Check if t1 is the parent of t2. If it is, then t1 should be first if (i1.name().equalsIgnoreCase(i2.parent())) { return -1; // otherwise t2 should be first if it's the parent of t1 } else if (i2.name().equalsIgnoreCase(i1.parent())) { return 1; // Ensure that there is not a circular reference } else if (i1.name().equalsIgnoreCase(i2.parent()) && i2.name().equalsIgnoreCase(i1.parent())) { throw new IllegalArgumentException("Circular reference in theme parents"); } // Just sort by name by default... If none of the above, then sort by name... return t1.getName().compareTo(t2.getName()); } catch (ClassNotFoundException ex) { return -1; } }).forEachOrdered(theme -> { try { Class<?> c = Class.forName(theme.getEntryPoint()); // Check for an existing application context AnnotationConfigApplicationContext ctx = (AnnotationConfigApplicationContext) getThemeContext(theme.getName()); if (ctx != null && ctx.isActive()) { ctx.close(); } // Create a new application context for the theme ctx = new AnnotationConfigApplicationContext(); // Fetch the theme info Theme themeInfo = c.getAnnotation(Theme.class); ctx.setId("theme-application-context-" + themeInfo.name()); // Find the parent application context for the theme and set it ApplicationContext parent = getThemeContext(themeInfo.parent()); ctx.setParent(parent == null ? moduleManagementService.getModuleContext() : parent); // Register the theme entry point class ctx.register(c); // Refresh the context ctx.refresh(); // Overwrite the existing theme application context themeContexts.put(theme.getName(), ctx); // Execute hook install - the theme should be installed. if (!theme.isInstalled()) { hookService.executeHook(ctx, c, "install"); themeConfigService.setInstalled(theme.getName(), true); } } catch (ClassNotFoundException ex) { LOG.error("Could not start theme: " + theme.getName(), ex); } catch (IllegalAccessException ex) { LOG.error("Could not install theme: " + theme.getName(), ex); } catch (InvocationTargetException ex) { LOG.error("Could not install theme: " + theme.getName(), ex); } }); } public void scan() { // Remove the themes missing from the classpath removeMissingThemes(); String defaultTheme = rootContext.getEnvironment().getProperty("themes.default", ""); String defaultAdminTheme = rootContext.getEnvironment().getProperty("themes.defaultAdmin", defaultTheme); ThemeConfig defaultThemeConfig = themeConfigService.getDefaultTheme(); ThemeConfig defaultAdminThemeConfig = themeConfigService.getDefaultAdminTheme(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.addIncludeFilter(new AnnotationTypeFilter(Theme.class)); Set<BeanDefinition> modules = scanner.findCandidateComponents("*"); modules.forEach(b -> { try { Class c = Class.forName(b.getBeanClassName()); themeConfigService.registerTheme(c, c.getProtectionDomain().getCodeSource().getLocation()); } catch (ClassNotFoundException e) { LOG.error("Could not load a module found on the class path, due to it's class not being found. This should never happen and usually means something is wrong with the environment", e); } }); if ((defaultThemeConfig == null || !themeClassExists(defaultThemeConfig))) { enable(defaultTheme); setDefaultTheme(defaultTheme); } if ((defaultAdminThemeConfig == null || !themeClassExists(defaultAdminThemeConfig))) { enable(defaultAdminTheme); setDefaultAdminTheme(defaultAdminTheme); } } private boolean themeClassExists(ThemeConfig config) { try { // Just running this will check that the class exists Class.forName(config.getEntryPoint()); return true; } catch (ClassNotFoundException ex) { return false; } } public ApplicationContext getDefaultThemeContext() { HttpServletRequest request = getServletRequest(); String currentPath = request.getRequestURI().substring(request.getContextPath().length()); // If the current path starts with /admin, then load the admin theme. ThemeConfig themeConfig = null; if (currentPath.startsWith("/admin")) { themeConfig = themeConfigService.getDefaultAdminTheme(); } else { themeConfig = themeConfigService.getDefaultTheme(); } if (themeConfig == null) { return null; } return getThemeContext(themeConfig.getName()); } protected void removeMissingThemes() { Set<String> missing = themeConfigService.listAllThemes().stream().filter(t -> { try { Class<?> c = Class.forName(t.getEntryPoint()); return !c.isAnnotationPresent(Theme.class); } catch (Exception ex) { return true; } }).map(t -> t.getName()).collect(Collectors.toSet()); themeConfigService.removeThemes(missing); } public List<String> resolveViewPath(HttpServletRequest request, final String prefix, final String viewName, final String suffix) { List<String> urls = new ArrayList<>(); urls.add(prefix + viewName + suffix); urls.addAll(getThemeTemplateURLSearchPath(prefix.replace(ResourceUtils.CLASSPATH_URL_PREFIX, ""), viewName, suffix)); // Get the request path... We use a substring of this excluding the context path and the rest of the url to determine if it's admin or not. try { hookService.executeHook("theme", (c, o) -> { if (o instanceof Map && ((Map) o).containsKey(viewName)) { URL hookLocation = c.getProtectionDomain().getCodeSource().getLocation(); String prefixPath = prefix.replace(ResourceUtils.CLASSPATH_URL_PREFIX, ""); if (ResourceUtils.isJarFileURL(hookLocation)) { String url = hookLocation.toExternalForm() + ResourceUtils.JAR_URL_SEPARATOR + prefixPath + ((Map) o).get(viewName) + suffix; if (!urls.contains(url)) { urls.add(url); } // Should default to standard prefix + file } else { String url = prefix + ((Map) o).get(viewName) + suffix; if (!urls.contains(url)) { urls.add(url); } } } }); // FIXME: Add custom exception here // Shouldn't ever happen... But you never know } catch (InvocationTargetException e) { LOG.error("Could not execute hook theme", e); } catch (IllegalAccessException e) { LOG.error("Could not execute hook theme", e); } // Reverse the collection Collections.reverse(urls); return urls; } private List<String> getThemeTemplateURLSearchPath(String prefix, String viewName, String suffix) { ThemeConfig config = getDefaultThemeConfigForRequest(); if (config == null) { return new LinkedList<>(); } URL url = null; try { if (ResourceUtils.isJarFileURL(new URL(config.getThemeLocation()))) { url = new URL(config.getThemeLocation() + ResourceUtils.JAR_URL_SEPARATOR + prefix.replaceAll("^/", "").replaceAll("/$", "") + "/" + config.getName() + "/" + viewName + suffix); } else { url = new URL(config.getThemeLocation() + "/" + prefix.replaceAll("^/", "").replaceAll("/$", "") + "/" + config.getName() + "/" + viewName + suffix); } } catch (MalformedURLException ex) { // do nothing } List<String> themePaths = new ArrayList<>(1); if (url != null) { themePaths.add(url.toExternalForm()); } return themePaths; } protected ThemeConfig getDefaultThemeConfigForRequest() { // FIXME: Move to a method as this is done more than once... HttpServletRequest request = getServletRequest(); String currentPath = request.getRequestURI().substring(request.getContextPath().length()); // Fetch the default theme config ThemeConfig themeConfig = null; if (currentPath.startsWith("/admin")) { themeConfig = themeConfigService.getDefaultAdminTheme(); } else { themeConfig = themeConfigService.getDefaultTheme(); } return themeConfig; } public Map<String, String> getRegionsForDefaultThemeByRequest() { ThemeConfig themeConfig = getDefaultThemeConfigForRequest(); return getThemeRegions(themeConfig); } public Map<String, String> getThemeRegions(String theme) { ThemeConfig themeConfig = themeConfigService.getTheme(theme); return getThemeRegions(themeConfig); } /** * Returns a list of the regions for the default theme, independent of current request. * * @return */ public Map<String, String> getRegionsForDefaultTheme() { ThemeConfig config = themeConfigService.getDefaultTheme(); return getThemeRegions(config); } protected Map<String, String> getThemeRegions(ThemeConfig themeConfig) { if (themeConfig != null) { try { Class<?> clazz = Class.forName(themeConfig.getEntryPoint()); final Map<String, String> regions = new LinkedHashMap<>(); Arrays.asList(clazz.getAnnotation(Theme.class).regions()).forEach(themeRegion -> { regions.put(themeRegion.name(), themeRegion.label()); }); if (regions.isEmpty()) { regions.putAll(PageElement.DEFAULT_REGIONS); } return regions; } catch (ClassNotFoundException e) { LOG.warn("Could not find default theme class!"); } } return PageElement.DEFAULT_REGIONS; } public String getDefaultThemeName() { ThemeConfig config = themeConfigService.getDefaultTheme(); if (config != null) { return config.getName(); } return null; } public String getCurrentThemeNameForRequest() { ThemeConfig config = getDefaultThemeConfigForRequest(); if (config == null) { return null; } return config.getName(); } public List<ApplicationContext> getThemeContextsAsList() { if (this.themeContexts == null) { return new LinkedList<>(); } return themeContexts.values().stream().collect(Collectors.toList()); } }
41.869018
199
0.612381
90fc453a9ae67e21778be91c0f3dd27dad1998ee
1,886
package com.xiaobudian.huastools.data; import android.util.Log; import org.jsoup.Jsoup; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by 小不点 on 2016/6/20. */ public class GetNetData { private static final String TAG="GetNetData"; public static Map<String,String> education_cookies=null; private static String result; public static int get_html_timeout=10*1000; public static int post_html_timeout=10*1000; public static void setEducationCookies(String cookie){ education_cookies=new HashMap<>(); Pattern p=Pattern.compile("(?<==).*(?=;)"); Matcher m=p.matcher(cookie); while(m.find()){ education_cookies.put("JSESSIONID", m.group()); } Log.d(TAG,education_cookies.toString()); } /** * 通过get方法获取html * @param url * @return */ public static String getEducationHtml(String cookie,String url){ setEducationCookies(cookie); Log.e(TAG,cookie); result=null; try { result=Jsoup.connect(url).cookies(education_cookies).timeout(get_html_timeout).get().toString(); } catch (IOException e) { Log.i(TAG, "无数据"); e.printStackTrace(); } return result; } /** * 通过post方法获取html * @param url * @param map * @return */ public static String postEducationHtml(String cookie,String url,Map<String,String> map){ setEducationCookies(cookie); result=null; try { result= Jsoup.connect(url).data(map).cookies(education_cookies).timeout(post_html_timeout).post().toString(); } catch (IOException e) { Log.i(TAG, "无数据"); e.printStackTrace(); } return result; } }
26.194444
121
0.61824
745d608846e4913224d424df6617aa5dc8f8628d
1,912
package org.mifos.connector.gsma.transfer; import io.zeebe.client.ZeebeClient; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.time.Duration; import java.util.HashMap; import java.util.Map; import static org.mifos.connector.gsma.camel.config.CamelProperties.*; import static org.mifos.connector.gsma.zeebe.ZeebeMessages.GSMA_QUOTE_RESPONSE; @Component public class QuoteResponseProcessor implements Processor { @Autowired private ZeebeClient zeebeClient; private Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${zeebe.client.ttl}") private int timeToLive; @Override public void process(Exchange exchange) { Map<String, Object> variables = new HashMap<>(); Object hasTransferFailed = exchange.getProperty(GSMA_QUOTE_FAILED); if (hasTransferFailed != null && (boolean)hasTransferFailed) { variables.put(GSMA_QUOTE_FAILED, true); variables.put(ERROR_INFORMATION, exchange.getIn().getBody(String.class)); } else { variables.put(QUOTE_ID, exchange.getProperty(QUOTE_ID)); variables.put(QUOTE_REFERENCE, exchange.getProperty(QUOTE_REFERENCE)); variables.put(GSMA_QUOTE_FAILED, false); } logger.info("Publishing quote message variables: " + variables); zeebeClient.newPublishMessageCommand() .messageName(GSMA_QUOTE_RESPONSE) .correlationKey(exchange.getProperty(TRANSACTION_ID, String.class)) .timeToLive(Duration.ofMillis(timeToLive)) .variables(variables) .send() .join(); } }
32.40678
85
0.708159
6cdbecd96ad5f1e094bf66b3e6e87b62aa2de93f
5,338
/* * Copyright (c) 2021, MegaEase * 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.megaease.easeagent.plugin.api; import org.junit.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.megaease.easeagent.plugin.api.ProgressFields.*; import static org.junit.Assert.*; public class ProgressFieldsTest { @Test public void changeListener() { getForwardedHeaders(); } @Test public void isProgressFields() { assertFalse(ProgressFields.isProgressFields(EASEAGENT_PROGRESS_FORWARDED_HEADERS_CONFIG + "abc")); assertTrue(ProgressFields.isProgressFields(EASEAGENT_PROGRESS_FORWARDED_HEADERS_CONFIG)); assertTrue(ProgressFields.isProgressFields(OBSERVABILITY_TRACINGS_TAG_RESPONSE_HEADERS_CONFIG + "abc")); assertTrue(ProgressFields.isProgressFields(OBSERVABILITY_TRACINGS_SERVICE_TAGS_CONFIG + "abc")); assertFalse(ProgressFields.isProgressFields("c" + OBSERVABILITY_TRACINGS_SERVICE_TAGS_CONFIG + "abc")); } @Test public void isEmpty() { assertTrue(true); assertTrue(ProgressFields.isEmpty(new String[0])); assertFalse(ProgressFields.isEmpty(new String[1])); } @Test public void getForwardedHeaders() { String key = EASEAGENT_PROGRESS_FORWARDED_HEADERS_CONFIG; assertTrue(ProgressFields.getForwardedHeaders().isEmpty()); ProgressFields.changeListener().accept(Collections.singletonMap(key, "a,b,c")); assertFalse(ProgressFields.getForwardedHeaders().isEmpty()); assertEquals(3, ProgressFields.getForwardedHeaders().size()); assertTrue(ProgressFields.getForwardedHeaders().contains("b")); ProgressFields.changeListener().accept(Collections.singletonMap(key, "a,b")); assertFalse(ProgressFields.getForwardedHeaders().isEmpty()); assertTrue(ProgressFields.getForwardedHeaders().contains("a")); assertTrue(ProgressFields.getForwardedHeaders().contains("b")); assertFalse(ProgressFields.getForwardedHeaders().contains("c")); ProgressFields.changeListener().accept(Collections.singletonMap(key, "")); assertTrue(ProgressFields.getForwardedHeaders().isEmpty()); } @Test public void getResponseHoldTagFields() { String keyPrefix = OBSERVABILITY_TRACINGS_TAG_RESPONSE_HEADERS_CONFIG; assertTrue(ProgressFields.isEmpty(ProgressFields.getResponseHoldTagFields())); ProgressFields.changeListener().accept(Collections.singletonMap(keyPrefix + "aaa", "bbb")); assertFalse(ProgressFields.isEmpty(ProgressFields.getResponseHoldTagFields())); assertEquals(1, ProgressFields.getResponseHoldTagFields().length); assertEquals("bbb", ProgressFields.getResponseHoldTagFields()[0]); ProgressFields.changeListener().accept(Collections.singletonMap(keyPrefix + "aaa", "")); assertTrue(ProgressFields.isEmpty(ProgressFields.getResponseHoldTagFields())); Map<String, String> map = new HashMap<>(); map.put(keyPrefix + "aaa", "bbb"); map.put(keyPrefix + "ccc", "ddd"); map.put(keyPrefix + "ffff", "fff"); ProgressFields.changeListener().accept(map); assertEquals(3, ProgressFields.getResponseHoldTagFields().length); map.replaceAll((s, v) -> ""); ProgressFields.changeListener().accept(map); assertTrue(ProgressFields.isEmpty(ProgressFields.getResponseHoldTagFields())); } @Test public void getServerTags() { String keyPrefix = OBSERVABILITY_TRACINGS_SERVICE_TAGS_CONFIG; assertTrue(ProgressFields.getServiceTags().isEmpty()); ProgressFields.changeListener().accept(Collections.singletonMap(keyPrefix + "aaa", "bbb")); assertFalse(ProgressFields.getServiceTags().isEmpty()); assertEquals(1, ProgressFields.getServiceTags().size()); assertEquals("bbb", ProgressFields.getServiceTags().get("aaa")); ProgressFields.changeListener().accept(Collections.singletonMap(keyPrefix + "aaa", "")); assertTrue(ProgressFields.getServiceTags().isEmpty()); Map<String, String> map = new HashMap<>(); map.put(keyPrefix + "aaa", "bbb"); map.put(keyPrefix + "ccc", "ddd"); map.put(keyPrefix + "ffff", "fff"); ProgressFields.changeListener().accept(map); assertEquals(3, ProgressFields.getServiceTags().size()); assertEquals("bbb", ProgressFields.getServiceTags().get("aaa")); assertEquals("ddd", ProgressFields.getServiceTags().get("ccc")); assertEquals("fff", ProgressFields.getServiceTags().get("ffff")); map.replaceAll((s, v) -> ""); ProgressFields.changeListener().accept(map); assertTrue(ProgressFields.getServiceTags().isEmpty()); } }
46.017241
112
0.709442
b7dcd1b8dac0d46c5ce332ed93a6df77ad78ebe5
669
package com.applause.assignment.testermatching.models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; /** * Entity object representing Tester_Device database table */ @Entity @Table(name = "TESTER_DEVICE") public class TesterDevice implements Serializable { private static final long serialVersionUID = -7003324516685466301L; @Id @Column(name = "TESTER_ID") private int testerId; @Column(name = "DEVICE_ID") private int deviceId; public int getTesterId() { return testerId; } public int getDeviceId() { return deviceId; } }
20.90625
69
0.753363
537df11996b26b990acdb3044e1150ecd2047f9d
854
package com.krux.kafka.offsetReporter; import java.util.List; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; public class ConsumerOffsetReporter { public static void main(String[] args) { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy); client.start(); try { List<String> children = client.getChildren().forPath("/"); for (String child : children) { System.out.println(child); } } catch (Exception e) { e.printStackTrace(); } client.close(); } }
26.6875
99
0.667447
10299e8f92ea4bdc92aa2094b441ecc33a5469bf
754
package com.qa.framework.library.log4j; import org.apache.log4j.PatternLayout; import org.apache.log4j.helpers.PatternParser; /** * Created by kcgw001 on 2016/2/22. */ public class Log4jExPatternLayout extends PatternLayout { /** * Instantiates a new Log 4 j ex pattern layout. * * @param pattern the pattern */ public Log4jExPatternLayout(String pattern) { super(pattern); } /** * Instantiates a new Log 4 j ex pattern layout. */ public Log4jExPatternLayout() { super(); } /** * 重写createPatternParser方法,返回PatternParser的子类 */ @Override protected PatternParser createPatternParser(String pattern) { return new Log4jExPatternParser(pattern); } }
22.176471
65
0.659151
afc083b9d32b3475aeb6752733fd2490f7ef7a6d
743
package com.telRun.tests; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class LoginTrelloTest extends TestBase{ // @BeforeMethod // public void ensurePreconditions() throws InterruptedException { // Thread.sleep(6000); // if(app.header().isAvatarPresent()){ // app.header().logout(); // } // // } @Test public void testLoginPositive() throws InterruptedException { if(app.header().isAvatarPresent()){ app.header().logout(); } app.session().login("lyubov.yapparova@gmail.com", "holopenio21"); Assert.assertTrue(app.header().isAvatarPresent()); //is user correct } }
24.766667
73
0.637954
04c88a9e12437fc0ea20d3005b97d65431f36c5a
2,371
// copied this class over from lab03 nothing special here package pr1; import java.awt.Color; import java.awt.Graphics; /** * @author Ivan Capistran * */ public class Ball { //ball private double x; private double y; private double radius; // Part II private double velocityX; private double velocityY; private Color color; /** * */ public Ball(double x, double y, double radius) { //make the private values available this.x = x; this.y = y; this.radius = radius; this.color = Color.red; this.velocityX=0; this.velocityY=0; // TODO Auto-generated constructor stub } /** * @return the x */ public double getX() { return x; } /** * @param x the x to set */ public void setX(double x) { this.x = x; } /** * @return the y */ public double getY() { return y; } /** * @param y the y to set */ public void setY(double y) { this.y = y; } /** * @return the radius */ public double getRadius() { return radius; } /** * @param radius the radius to set */ public void setRadius(double radius) { this.radius = radius; } /** * @return the color */ public java.awt.Color getColor() { return color; } /** * @param color the color to set */ public void setColor(java.awt.Color color) { this.color = color; } /** * @return the velocityX */ public double getVelocityX() { return velocityX; } /** * @param velocityX the velocityX to set */ public void setVelocityX(double velocityX) { this.velocityX = velocityX; } /** * @return the velocityY */ public double getVelocityY() { return velocityY; } /** * @param velocityY the velocityY to set */ public void setVelocityY(double velocityY) { this.velocityY = velocityY; } public void draw(Graphics g){ g.setColor(this.color); g.fillOval((int) Math.round(x-radius) , (int) Math.round (y-radius) , (int) Math.round(radius*2) , (int) Math.round(radius*2)); } public boolean intersectsBall(Ball b){ double d = Math.sqrt(Math.pow(b.getX()-this.getX(),2) + Math.pow(b.getY()-this.getY(),2)); double r = (b.getRadius() + this.getRadius()); if (d<r){ return true; } return false; } public void setCollided(){ setColor(Color.red); } }
18.379845
93
0.595108
457d099d0750332f6afff4d6ab4d3cbb42f914a3
490
package com.woophee.stream.transform; import com.woophee.common.SourceData; import org.apache.flink.api.common.functions.ReduceFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Reduce implements ReduceFunction<SourceData> { private final static Logger logger = LoggerFactory.getLogger(Reduce.class); @Override public SourceData reduce(SourceData t1, SourceData t2) throws Exception { logger.info("#Reduce#"); return t2; } }
27.222222
79
0.755102
aa04eaea3604efcf4021504beacdabbc2c940108
4,728
package org.aksw.simba.bigrdfbench.util; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.RepositoryException; import com.google.common.collect.Sets; public class StatsGenerator { public static void main(String[] args) throws RepositoryException, MalformedQueryException, QueryEvaluationException { // TODO Auto-generated method stub // String results = "D:/BigRDFBench/completeness_correctness/results.nt"; // ResultsLoader.loadResults(results); // getActualResults("S1"); } public static String getFscores(String queryNo,TupleQueryResult res) throws QueryEvaluationException, RepositoryException, MalformedQueryException { String Fscores = "" ; double precision, recall,F1; Set<String> curResults = getCurrentResult(res) ; //System.out.println("current:"+ curResults); Set<String> actualResults = getActualResults(queryNo) ; //System.out.println("actual:" +actualResults); Set<String> diffSet = Sets.difference(actualResults, curResults); //System.out.println(diffSet); //System.out.println(Sets.difference( curResults,actualResults)); double correctResults = actualResults.size()-diffSet.size(); precision = (correctResults/curResults.size()); recall = correctResults/actualResults.size(); F1 = 2*(precision*recall)/(precision+recall); Fscores = "Precision: "+precision+", Recall: " + recall +", F1: "+F1; return Fscores; } // public static float getPrecision(String queryNo,TupleQueryResult res) throws QueryEvaluationException, RepositoryException, MalformedQueryException // { // // float precision = 0 ; // Set<String> curResults = getCurrentResult(res) ; // Set<String> actualResults = getActualResults(queryNo) ; // Set<String> diffSet = Sets.difference(actualResults, curResults); // precision = diffSet.size(); // System.out.println(diffSet); // System.out.println(Sets.difference(curResults,actualResults)); // return precision; // // } private static Set<String> getCurrentResult(TupleQueryResult res) throws QueryEvaluationException { List<String> bindingNames = res.getBindingNames(); Set<String> curResults = new HashSet<String>() ; while (res.hasNext()) { BindingSet result = res.next(); String recordLine =""; for(int i = 0 ; i < bindingNames.size(); i++) { String bindingName = bindingNames.get(i); String bindingVal = result.getBinding(bindingName).getValue().toString().replaceAll("\n", " ").replace("]", "").replace("[", ""); if(i< bindingNames.size()-1) recordLine = recordLine+bindingName+"="+bindingVal+";"; else recordLine = recordLine+bindingName+"="+bindingVal; } curResults.add("["+recordLine+"]"); } return curResults; } private static Set<String> getActualResults(String queryName) throws RepositoryException, MalformedQueryException, QueryEvaluationException { Set<String> actualResults = new HashSet<String>() ; String queryString = "PREFIX bigrdfbench: <http://bigrdfbench.aksw.org/schema/> \n" + " Select ?names ?values \n" + " WHERE \n" + " {\n" + " ?s bigrdfbench:queryName <http://aksw.org/bigrdfbench/query/"+queryName+">.\n" + " <http://aksw.org/bigrdfbench/query/"+queryName+"> bigrdfbench:bindingNames ?names.\n" + " <http://aksw.org/bigrdfbench/query/"+queryName+"> bigrdfbench:bindingValues ?values\n" + " }"; TupleQuery tupleQuery = ResultsLoader.con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); TupleQueryResult res = tupleQuery.evaluate(); while(res.hasNext()) { BindingSet result = res.next(); String[] bindingNames = result.getValue("names").stringValue().replace("'", "\"").replace("[", "").replace("]", "").split(";"); String[] bindingValues = result.getValue("values").stringValue().replace("'", "\"").replace("[", "").replace("]", "").split(";"); String actualResult = "["; for(int i=0 ; i < bindingNames.length;i++) { if(i<bindingNames.length-1) actualResult= actualResult+bindingNames[i]+"="+bindingValues[i]+";"; else actualResult= actualResult+bindingNames[i]+"="+bindingValues[i]+"]"; } actualResults.add(actualResult); // System.out.println(actualResult); } // System.out.println(actualResults.size()); return actualResults; } }
39.731092
151
0.692047
a003703ec7f317298d1d186413065ed97dcc877c
130
package br.com.bytebank.banco.teste; public class Teste { public static void main(String[] args) { System.out.println(); } }
16.25
41
0.707692
0a87372ba88a74892b49ffa374414715482045cf
2,912
package tests; import com.github.chengyuxing.common.tuple.Pair; import com.github.chengyuxing.sql.Args; import com.github.chengyuxing.sql.BakiDao; import com.github.chengyuxing.sql.SQLFileManager; import com.github.chengyuxing.sql.utils.SqlUtil; import org.junit.Test; import org.nutz.dao.impl.NutDao; import org.nutz.ioc.Ioc; import org.nutz.ioc.impl.NutIoc; import org.nutz.ioc.loader.json.JsonLoader; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; public class SqlFileTest { private static Ioc ioc; // @BeforeClass public static void init() { ioc = new NutIoc(new JsonLoader("ioc.js")); } @Test public void dynamicSqlFileManagerTest() throws Exception { SQLFileManager sqlFileManager = new SQLFileManager(); sqlFileManager.add("data", "pgsql/data.sql"); sqlFileManager.init(); System.out.println("-------"); System.out.println(sqlFileManager.get("data.logical", Args.<Object>of("name", "cyx").add("age", 101))); } @Test public void argsTest() throws Exception { System.out.println(Args.create("id", 1, "name", "cyx", "dt", LocalDateTime.now())); } @Test public void sqlf() throws Exception { SQLFileManager sqlFileManager = new SQLFileManager(); sqlFileManager.add("rabbit", "file:/Users/chengyuxing/Downloads/local.sql"); sqlFileManager.init(); sqlFileManager.look(); } @Test public void ref() throws Exception { Pair<String, List<String>> pair = SqlUtil.getPreparedSql(":res = call getUser(:id, :name)", Collections.emptyMap()); System.out.println(pair.getItem1()); System.out.println(pair.getItem2()); } @Test public void trimTest() throws Exception { System.out.println(" data.sql\n\t \n".trim()); } @Test public void nutzIoc() throws Exception { SQLFileManager sqlFileManager = ioc.get(SQLFileManager.class, "sqlFileManager"); sqlFileManager.init(); sqlFileManager.look(); } @Test public void sqlTest() throws Exception { SQLFileManager sqlFileManager = new SQLFileManager("pgsql/nest.sql"); sqlFileManager.setConstants(Args.of("db", "qbpt_deve")); sqlFileManager.setCheckModified(true); // sqlFileManager.add("pgsql/other.sql"); // sqlFileManager.add("mac", "file:/Users/chengyuxing/Downloads/local.sql"); sqlFileManager.init(); sqlFileManager.look(); } @Test public void strTest() throws Exception { String sql = "select * from user where 1=1 and id = 2)}];\n;; \t\n \r\n;; \n\n\t\r"; System.out.println(SqlUtil.trimEnd(sql)); System.out.println(sql.trim()); } @Test public void bakiDao() throws Exception { BakiDao bakiDao = new BakiDao(null); NutDao nutDao = new NutDao(); } }
30.978723
124
0.652129
9ec8bea327ca13acdbe8ace9d8484bdd301c41ff
409
package com.example.diploma.persistence.dto.front; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.FieldDefaults; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE) public class CategoryDto { String url; String name; String catalogUrl; }
18.590909
50
0.801956
a5c188194d05ccba16e38ba0fe621704e68ae134
85
module jp.dip.oyasirazu.xmlviewer { requires java.xml; requires args4j; }
10.625
35
0.682353
e6c810a71e65711ff795906c4f216b7409800cc7
307
// 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.android.compiler.artifact; public enum AndroidArtifactSigningMode { DEBUG, DEBUG_WITH_CUSTOM_CERTIFICATE, RELEASE_UNSIGNED, RELEASE_SIGNED }
43.857143
140
0.814332
c0640dcc0d59b6af9e8c98e611a7deee00bd2a4c
801
package cn.glogs.news.entity; public class NewsType { private int typeId; private String typeName; private String Remark; public int getTypeId() { return typeId; } public void setTypeId(int typeId) { this.typeId = typeId; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getRemark() { return Remark; } public void setRemark(String remark) { Remark = remark; } @Override public String toString() { return "NewsType{" + "typeId=" + typeId + ", typeName='" + typeName + '\'' + ", Remark='" + Remark + '\'' + '}'; } }
19.536585
50
0.52809
071208841bc4e3127a1996a919fbe562f9516ad0
1,632
package starter.math; import io.cucumber.junit.CucumberOptions; import net.serenitybdd.cucumber.CucumberWithSerenity; import net.serenitybdd.junit.runners.SerenityRunner; import net.thucydides.core.annotations.Narrative; import net.thucydides.core.annotations.Steps; import org.junit.Test; import org.junit.runner.RunWith; import starter.steps.ExampleTestHelper; //OLD one(without cucumber)@RunWith(SerenityRunner.class) //@Narrative(text={"Weather is important."}) @RunWith(CucumberWithSerenity.class) // new one (with cucumber) @CucumberOptions( features="src/test/resources/features", glue = "starter.steps", plugin = {"pretty", "html:target/cucumber-report/cucumber.html"}) public class ExampleTest { @Steps ExampleTestHelper exampleTestHelper; @Test public void verifyThatIstanbulIsInTurkeyUsingTheWeatherAPI() { exampleTestHelper.tryTofindWeatherOfCountry("Istanbul"); exampleTestHelper.weatherSearchIsExecutedSuccesfully(); exampleTestHelper.weatherResponseBelongsToCountry("Turkey"); } @Test public void verifyThatIstanbulIsInCorrectLatLongUsingTheWeatherAPI(){ exampleTestHelper.tryTofindWeatherOfCountry("Istanbul"); exampleTestHelper.weatherSearchIsExecutedSuccesfully(); exampleTestHelper.isCountryInBetweenLatLong("41.019", "28.965"); } @Test public void verifyThatResponseCityNameIsEqualToIstanbul(){ exampleTestHelper.tryTofindWeatherOfCountry("Istanbul"); exampleTestHelper.weatherSearchIsExecutedSuccesfully(); exampleTestHelper.isCityNameEqualsToCity("Istanbul"); } }
36.266667
73
0.766544
aea01cb7933b2faa77bcb1df187818c13234b044
1,623
package io.kaif.service; import java.util.List; import java.util.Optional; import io.kaif.model.account.Authorization; import io.kaif.model.clientapp.ClientApp; import io.kaif.model.clientapp.ClientAppUser; import io.kaif.model.clientapp.ClientAppUserAccessToken; import io.kaif.oauth.OauthAccessTokenDto; import io.kaif.web.support.AccessDeniedException; public interface ClientAppService { ClientApp create(Authorization authorization, String name, String description, String callbackUri); ClientApp loadClientAppWithoutCache(String clientId); List<ClientApp> listClientApps(Authorization creator); void update(Authorization creator, String clientId, String name, String description, String callbackUri); Optional<ClientApp> verifyRedirectUri(String clientId, String redirectUri); String directGrantCode(String oauthDirectAuthorize, String clientId, String scope, String redirectUri) throws AccessDeniedException; OauthAccessTokenDto createOauthAccessTokenByGrantCode(String code, String clientId, String redirectUri) throws AccessDeniedException; Optional<ClientAppUserAccessToken> verifyAccessToken(String rawAccessToken); List<ClientAppUser> listGrantedAppUsers(Authorization authorization); void resetClientAppSecret(Authorization creator, String clientId); void revokeApp(Authorization user, String clientId); boolean validateApp(String clientId, String clientSecret); List<ClientApp> listGrantedApps(Authorization user); String generateDebugAccessToken(Authorization developer, String clientId); }
29.509091
78
0.797289
be2e1dbd1e661ca0a4b9fbf73dbdf5ea6ed36749
18,318
package org.apache.ofbiz.accounting.payment.service.base; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.apache.ofbiz.common.ExecuteFindService.In; import org.apache.ofbiz.common.ExecuteFindService.Out; import org.apache.ofbiz.common.ExecuteFindService; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.Collections; import org.apache.commons.collections4.CollectionUtils; import java.util.Optional; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.condition.EntityConditionList; import org.apache.ofbiz.entity.condition.EntityExpr; import org.apache.ofbiz.entity.condition.EntityOperator; import com.github.yuri0x7c1.uxcrm.util.OfbizUtil; import org.apache.ofbiz.accounting.payment.PaymentMethod; import org.springframework.beans.factory.annotation.Autowired; import org.apache.ofbiz.accounting.payment.PaymentMethodType; import org.apache.ofbiz.party.party.Party; import org.apache.ofbiz.accounting.ledger.GlAccount; import org.apache.ofbiz.accounting.finaccount.FinAccount; import org.apache.ofbiz.accounting.payment.CheckAccount; import org.apache.ofbiz.accounting.payment.CreditCard; import org.apache.ofbiz.accounting.payment.EftAccount; import org.apache.ofbiz.accounting.payment.GiftCard; import org.apache.ofbiz.order.order.OrderPaymentPreference; import org.apache.ofbiz.accounting.ledger.PartyAcctgPreference; import org.apache.ofbiz.accounting.payment.PayPalPaymentMethod; import org.apache.ofbiz.accounting.payment.Payment; import org.apache.ofbiz.accounting.payment.PaymentGatewayResponse; import org.apache.ofbiz.order._return.ReturnHeader; import org.apache.ofbiz.order.shoppinglist.ShoppingList; @Slf4j @Component @SuppressWarnings("unchecked") public class PaymentMethodBaseService { protected ExecuteFindService executeFindService; @Autowired public PaymentMethodBaseService(ExecuteFindService executeFindService) { this.executeFindService = executeFindService; } /** * Count PaymentMethods */ public Integer count(EntityConditionList conditions) { In in = new In(); in.setEntityName(PaymentMethod.NAME); if (conditions == null) { in.setNoConditionFind(OfbizUtil.Y); } else { in.setEntityConditionList(conditions); } Out out = executeFindService.runSync(in); return out.getListSize(); } /** * Find PaymentMethods */ public List<PaymentMethod> find(Integer start, Integer number, List<String> orderBy, EntityConditionList conditions) { List<PaymentMethod> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(PaymentMethod.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); if (conditions == null) { in.setNoConditionFind(OfbizUtil.Y); } else { in.setEntityConditionList(conditions); } Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = PaymentMethod.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Find one PaymentMethod */ public Optional<PaymentMethod> findOne(Object paymentMethodId) { List<PaymentMethod> entityList = null; In in = new In(); in.setEntityName(PaymentMethod.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethodId)), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = PaymentMethod.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get payment method type */ public Optional<PaymentMethodType> getPaymentMethodType( PaymentMethod paymentMethod) { List<PaymentMethodType> entityList = null; In in = new In(); in.setEntityName(PaymentMethodType.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodTypeId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodTypeId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = PaymentMethodType.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get party */ public Optional<Party> getParty(PaymentMethod paymentMethod) { List<Party> entityList = null; In in = new In(); in.setEntityName(Party.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("partyId", EntityOperator.EQUALS, paymentMethod.getPartyId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = Party .fromValues(out.getListIt().getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get gl account */ public Optional<GlAccount> getGlAccount(PaymentMethod paymentMethod) { List<GlAccount> entityList = null; In in = new In(); in.setEntityName(GlAccount.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("glAccountId", EntityOperator.EQUALS, paymentMethod.getGlAccountId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = GlAccount.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get fin account */ public Optional<FinAccount> getFinAccount(PaymentMethod paymentMethod) { List<FinAccount> entityList = null; In in = new In(); in.setEntityName(FinAccount.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("finAccountId", EntityOperator.EQUALS, paymentMethod.getFinAccountId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = FinAccount.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get check account */ public Optional<CheckAccount> getCheckAccount(PaymentMethod paymentMethod) { List<CheckAccount> entityList = null; In in = new In(); in.setEntityName(CheckAccount.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = CheckAccount.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get credit card */ public Optional<CreditCard> getCreditCard(PaymentMethod paymentMethod) { List<CreditCard> entityList = null; In in = new In(); in.setEntityName(CreditCard.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = CreditCard.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get eft account */ public Optional<EftAccount> getEftAccount(PaymentMethod paymentMethod) { List<EftAccount> entityList = null; In in = new In(); in.setEntityName(EftAccount.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = EftAccount.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get replenish fin accounts */ public List<FinAccount> getReplenishFinAccounts( PaymentMethod paymentMethod, Integer start, Integer number, List<String> orderBy) { List<FinAccount> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(FinAccount.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("replenishPaymentId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = FinAccount.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get gift card */ public Optional<GiftCard> getGiftCard(PaymentMethod paymentMethod) { List<GiftCard> entityList = null; In in = new In(); in.setEntityName(GiftCard.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = GiftCard.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get order payment preferences */ public List<OrderPaymentPreference> getOrderPaymentPreferences( PaymentMethod paymentMethod, Integer start, Integer number, List<String> orderBy) { List<OrderPaymentPreference> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(OrderPaymentPreference.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = OrderPaymentPreference.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get party acctg preferences */ public List<PartyAcctgPreference> getPartyAcctgPreferences( PaymentMethod paymentMethod, Integer start, Integer number, List<String> orderBy) { List<PartyAcctgPreference> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(PartyAcctgPreference.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("refundPaymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = PartyAcctgPreference.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get pay pal payment method */ public Optional<PayPalPaymentMethod> getPayPalPaymentMethod( PaymentMethod paymentMethod) { List<PayPalPaymentMethod> entityList = null; In in = new In(); in.setEntityName(PayPalPaymentMethod.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = PayPalPaymentMethod.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get payments */ public List<Payment> getPayments(PaymentMethod paymentMethod, Integer start, Integer number, List<String> orderBy) { List<Payment> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(Payment.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = Payment.fromValues(out.getListIt().getPartialList( start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get payment gateway responses */ public List<PaymentGatewayResponse> getPaymentGatewayResponses( PaymentMethod paymentMethod, Integer start, Integer number, List<String> orderBy) { List<PaymentGatewayResponse> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(PaymentGatewayResponse.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = PaymentGatewayResponse.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get return headers */ public List<ReturnHeader> getReturnHeaders(PaymentMethod paymentMethod, Integer start, Integer number, List<String> orderBy) { List<ReturnHeader> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(ReturnHeader.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ReturnHeader.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get shopping lists */ public List<ShoppingList> getShoppingLists(PaymentMethod paymentMethod, Integer start, Integer number, List<String> orderBy) { List<ShoppingList> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(ShoppingList.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("paymentMethodId", EntityOperator.EQUALS, paymentMethod .getPaymentMethodId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ShoppingList.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } }
30.890388
77
0.714106
2a953fda2f5aa9c45f05bd8d5adf9b4a8f5de3ae
3,078
/** * Copyright 2016 Confluent 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 io.confluent.connect.elasticsearch; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import io.confluent.connect.elasticsearch.bulk.BulkClient; import io.confluent.connect.elasticsearch.bulk.BulkResponse; import io.searchbox.client.JestClient; import io.searchbox.core.Bulk; import io.searchbox.core.BulkResult; public class BulkIndexingClient implements BulkClient<IndexableRecord, Bulk> { private static final Logger LOG = LoggerFactory.getLogger(BulkIndexingClient.class); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final JestClient client; public BulkIndexingClient(JestClient client) { this.client = client; } @Override public Bulk bulkRequest(List<IndexableRecord> batch) { final Bulk.Builder builder = new Bulk.Builder(); for (IndexableRecord record : batch) { builder.addAction(record.toIndexRequest()); } return builder.build(); } @Override public BulkResponse execute(Bulk bulk) throws IOException { final BulkResult result = client.execute(bulk); if (result.isSucceeded()) { return BulkResponse.success(); } boolean retriable = true; final List<Key> versionConflicts = new ArrayList<>(); final List<String> errors = new ArrayList<>(); for (BulkResult.BulkResultItem item : result.getItems()) { if (item.error != null) { final ObjectNode parsedError = (ObjectNode) OBJECT_MAPPER.readTree(item.error); final String errorType = parsedError.get("type").asText(""); if ("version_conflict_engine_exception".equals(errorType)) { versionConflicts.add(new Key(item.index, item.type, item.id)); } else if ("mapper_parse_exception".equals(errorType)) { retriable = false; errors.add(item.error); } else { errors.add(item.error); } } } if (!versionConflicts.isEmpty()) { LOG.debug("Ignoring version conflicts for items: {}", versionConflicts); if (errors.isEmpty()) { // The only errors were version conflicts return BulkResponse.success(); } } final String errorInfo = errors.isEmpty() ? result.getErrorMessage() : errors.toString(); return BulkResponse.failure(retriable, errorInfo); } }
31.408163
93
0.712476
59fb3a4dac33a50b5dc66602f1e1fbcdb62166fd
840
package com.ampota.user.resource.admin; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ampota.shared.dto.BankInfo; import com.ampota.user.service.BankService; import xyz.xpay.shared.web.BaseResource; import static org.springframework.http.HttpStatus.*; @RestController @RequestMapping("/api/admin/bank") public class BankAdminResource extends BaseResource<BankInfo, BankService> { @PostMapping public ResponseEntity<BankInfo> saveBank(@RequestBody BankInfo bank) { return ResponseEntity.status(OK).body(service.saveInfo(bank)); } }
33.6
77
0.789286
66d78c9ced89cf51d17f022218e10289df92e6b7
468
package se.natusoft.osgi.aps.util; import java.io.InputStream; /** * This because getClass().getResourceAsStream(path) fails in Groovy 3.x!! * * Thereby I decided to create this resource loading tool in Java and add to it as needed. * * Works fine when this is called from Groovy code! */ public class APSResourceLoader { public static InputStream asInputStream( String path ) { return APSResourceLoader.class.getResourceAsStream( path ); } }
26
90
0.730769
3dcd3b129114781b65e290cd0a32201a447e786b
1,331
/* * CentrallyHeld.java * * 21.01.2008 * * (c) by O.Lieshoff * */ package corent.db.xs; /** * Dieses Interface mu&szlig; von Klassen implementiert werden, die zentralisiert gehalten * werden und &uuml;ber eine globale Identifikationsnummer verf&uuml;gen. * * @author * O.Lieshoff * <P> * * @changed * OLI 21.01.2008 - Hinzugef&uuml;gt. * <P>OLI 23.03.2009 - Nachkommentierung der Methoden und Formatanpassungen. * <P> * */ public interface CentrallyHeld { /** * Liefert die GLI (Global-Lokal-Identifikatornummer) des Objektes. Hierbei handelt es sich * um eine Identifikationsnummer, die &uuml;ber alle Datenbest&auml;nde der Anwendung * eindeutig ist und so z. B. zur Synchronisation von Datens&auml;tzen genutzt werden kann. * * @return Die GLI des Objekts. */ public long getGLI(); /** * Setzt den &uuml;bergebenen Wert als neue GLI f&uuml;r das Objekt ein. Hierbei handelt es * sich um eine Identifikationsnummer, die &uuml;ber alle Datenbest&auml;nde der Anwendung * eindeutig ist und so z. B. zur Synchronisation von Datens&auml;tzen genutzt werden kann. * * @param gli Der neue Wert f&uuml;r die GLI des Objekts. */ public void setGLI(long gli); }
27.163265
97
0.642374
fc06da82ebc0679951df364be839a20da3b1b1fb
274
/** * UserView.java * in package: * org.net9.minipie.server.logic * by Mini-Pie Project */ package org.net9.minipie.server.logic; /** * @author Seastar * */ public class UserView { /** * @param args */ public static void main(String[] args) { } }
11.913043
50
0.60219
d666936df3d9130deb8bcd29d9d1c92cdee6ff44
3,959
package com.mrbysco.candyworld.config; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; import net.minecraftforge.common.ForgeConfigSpec.IntValue; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.config.ModConfig; import org.apache.commons.lang3.tuple.Pair; public class CandyConfig { public static class Common { public final BooleanValue disableTeleporter; public final IntValue weightCottonCandyPlains; public final IntValue weightChocolateForest; public final IntValue weightGummySwamp; public final IntValue weightCottonCandySheep; public final IntValue weightEasterChicken; public final IntValue weightGummyMouse; public final IntValue weightGummyBear; public final BooleanValue preventModdedMobSpawn; public final BooleanValue recursiveTreeTrunks; public final BooleanValue stackableTreeTrunks; Common(ForgeConfigSpec.Builder builder) { builder.comment("Dimension settings") .push("Dimension"); disableTeleporter = builder .comment("Setting this to true will prevent players from teleporting to the dimension") .define("disableTeleporter", false); builder.pop(); builder.comment("Biome settings") .push("Biome"); weightCottonCandyPlains = builder .comment("Overworld cotton candy plains biome weight. 0 to prevent generation in overworld") .defineInRange("weightCottonCandyPlains", 1, 0, Integer.MAX_VALUE); weightChocolateForest = builder .comment("Overworld chocolate forest biome weight. 0 to prevent generation in overworld") .defineInRange("weightChocolateForest", 1, 0, Integer.MAX_VALUE); weightGummySwamp = builder .comment("Overworld gummy swamp biome weight. 0 to prevent generation in overworld") .defineInRange("weightGummySwamp", 1, 0, Integer.MAX_VALUE); builder.pop(); builder.comment("Mob settings") .push("Mobs"); weightCottonCandySheep = builder .comment("Cotton candy sheep weight. 0 to prevent spawning") .defineInRange("weightCottonCandySheep", 140, 1, Integer.MAX_VALUE); weightEasterChicken = builder .comment("Easter chicken weight. 0 to prevent spawning") .defineInRange("weightEasterChicken", 140, 1, Integer.MAX_VALUE); weightGummyMouse = builder .comment("Gummy mice weight. 0 to prevent spawning") .defineInRange("weightGummyMouse", 140, 1, Integer.MAX_VALUE); weightGummyBear = builder .comment("Gummy bear weight. 0 to prevent spawning") .defineInRange("weightGummyBear", 110, 1, Integer.MAX_VALUE); preventModdedMobSpawn = builder .comment("Setting this to true should prevent any non-Candy World mobs from spawning in candy world biomes") .define("preventModdedMobSpawn", false); builder.pop(); builder.comment("General settings") .push("General"); recursiveTreeTrunks = builder .comment("Setting this to true will make tree trunks take longer to mine the higher they are") .define("recursiveTreeTrunks", false); stackableTreeTrunks = builder .comment("Setting this to false will make tree trunk blocks behave like normal blocks") .define("stackableTreeTrunks", true); builder.pop(); } } public static final ForgeConfigSpec commonSpec; public static final Common COMMON; static { final Pair<Common, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Common::new); commonSpec = specPair.getRight(); COMMON = specPair.getLeft(); } @SubscribeEvent public static void onLoad(final ModConfig.Loading configEvent) { com.mrbysco.candyworld.CandyWorld.LOGGER.debug("Loaded Candy World's config file {}", configEvent.getConfig().getFileName()); } @SubscribeEvent public static void onFileChange(final ModConfig.Reloading configEvent) { com.mrbysco.candyworld.CandyWorld.LOGGER.debug("Candy World's config just got changed on the file system!"); } }
35.348214
127
0.75802
6fbc7304ce8bc3ce137f5fad380dc7910e27d94c
3,317
/* Copyright 2010, 2017, Oracle and/or its affiliates. All rights reserved. */ package oracle.demo.view; /*------------------------------------------------------------------------------------------- * This code is distributed under the MIT License (MIT) * * Copyright (c) 2012 Duncan Mills *------------------------------------------------------------------------------------------- * * 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. *-------------------------------------------------------------------------------------------*/ import java.util.Map; import oracle.adf.view.rich.component.rich.layout.RichPanelFormLayout; import oracle.adf.view.rich.context.AdfFacesContext; import oracle.adf.view.rich.render.ClientEvent; /** * Request scoped managed bean used to hold event handlers for the main page * Has the state holding UIManager injected */ public class HomePageHandler { private UIManager _uiManager; private RichPanelFormLayout infoForm; public void setUiManager(UIManager _uiManager) { this._uiManager = _uiManager; } public UIManager getUiManager() { return _uiManager; } /** * Handler for the custom event queued by JavaScript in the client. * Specifically this is registered by the af:serverListener to react to * a custom event called <em>windowResizeEvent</em> * @param clientEvent */ public void windowResizeClientEventHandler(ClientEvent clientEvent) { Map payload = clientEvent.getParameters(); int width = (int)((Double)payload.get("width")).doubleValue(); int height = (int)((Double)payload.get("height")).doubleValue(); //Update the UI Manager getUiManager().setWindowWidth(width); getUiManager().setWindowHeight(height); //In this example PPR the form so that the fields on screen //can display the new values AdfFacesContext fctx = AdfFacesContext.getCurrentInstance(); fctx.addPartialTarget(getInfoForm()); } public void setInfoForm(RichPanelFormLayout infoForm) { this.infoForm = infoForm; } public RichPanelFormLayout getInfoForm() { return infoForm; } }
42.525641
96
0.640941
4fe17ff8da508de2a4e133ff305907e79cbfb2b3
845
package leetcode.oo.dp; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public final class DecodingWaysTestCase { private DecodingWays alg; /** * Init. */ @Before public void init() { this.alg = new DecodingWays(); } @Test public void test() { Assert.assertEquals( this.alg.numDecodings("012"), 0 ); Assert.assertEquals( this.alg.numDecodings("10"), 1 ); Assert.assertEquals( this.alg.numDecodings("01"), 0 ); Assert.assertEquals( this.alg.numDecodings("00"), 0 ); Assert.assertEquals( this.alg.numDecodings("226"), 3 ); } }
19.651163
45
0.474556
948f662225c1553891a23dfad732c0b139770a73
2,506
/* * Copyright 2015 Realm 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 io.realm.processor; import com.squareup.javawriter.JavaWriter; import java.io.BufferedWriter; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Modifier; import javax.tools.JavaFileObject; import io.realm.annotations.RealmModule; /** * This class is responsible for creating the DefaultRealmModule that contains all known * {@link io.realm.annotations.RealmClass}' known at compile time. */ public class DefaultModuleGenerator { private final ProcessingEnvironment env; public DefaultModuleGenerator(ProcessingEnvironment env) { this.env = env; } public void generate() throws IOException { String qualifiedGeneratedClassName = String.format(Locale.US, "%s.%s", Constants.REALM_PACKAGE_NAME, Constants.DEFAULT_MODULE_CLASS_NAME); JavaFileObject sourceFile = env.getFiler().createSourceFile(qualifiedGeneratedClassName); JavaWriter writer = new JavaWriter(new BufferedWriter(sourceFile.openWriter())); writer.setIndent(" "); writer.emitPackage(Constants.REALM_PACKAGE_NAME); writer.emitEmptyLine(); Map<String, Boolean> attributes = new LinkedHashMap<>(); attributes.put("allClasses", Boolean.TRUE); writer.emitAnnotation(RealmModule.class, attributes); writer.beginType( qualifiedGeneratedClassName, // full qualified name of the item to generate "class", // the type of the item Collections.<Modifier>emptySet(), // modifiers to apply null); // class to extend writer.emitEmptyLine(); writer.endType(); writer.close(); } }
34.805556
146
0.702314
0a29e2199767ceade52a05dbc96de94544ffb29c
778
package james.gustavo.exemplopostconstructpredestroy.dao; import james.gustavo.exemplopostconstructpredestroy.model.Client; import lombok.Getter; import lombok.Setter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * @author Gustavo James * @version 1.0 * @since 14/06/2020 - 22:25 */ //lombok @Getter @Setter //springboot @Component public class ClientDAO { @Autowired private Client client; @PostConstruct public void postConstruct() { System.out.println("O objeto foi criado!"); } @PreDestroy public void preDestroy() { System.out.println("O objeto foi finalizado!"); } }
21.027027
65
0.736504
a538ce82fd821b6eaaf23ec7fe5a70697369a5c2
3,026
/* Copyright 2019 Telstra Open Source * * 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.openkilda.wfm.topology.network.service; import org.openkilda.model.Isl; import org.openkilda.model.Switch; import org.openkilda.model.SwitchId; import org.openkilda.model.SwitchStatus; import org.openkilda.persistence.PersistenceManager; import org.openkilda.persistence.repositories.IslRepository; import org.openkilda.persistence.repositories.RepositoryFactory; import org.openkilda.persistence.repositories.SwitchRepository; import org.openkilda.wfm.topology.network.model.facts.HistoryFacts; import lombok.extern.slf4j.Slf4j; import java.util.Collection; import java.util.HashMap; @Slf4j public class NetworkHistoryService { private final ISwitchPrepopulateCarrier carrier; private final PersistenceManager persistenceManager; public NetworkHistoryService(ISwitchPrepopulateCarrier carrier, PersistenceManager persistenceManager) { this.carrier = carrier; this.persistenceManager = persistenceManager; } /** * . */ public void applyHistory() { log.debug("History service receive history lookup request"); for (HistoryFacts history : loadNetworkHistory()) { carrier.switchAddWithHistory(history); } } // -- private -- private Collection<HistoryFacts> loadNetworkHistory() { RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory(); SwitchRepository switchRepository = repositoryFactory.createSwitchRepository(); HashMap<SwitchId, HistoryFacts> switchById = new HashMap<>(); for (Switch switchEntry : switchRepository.findAll()) { SwitchId switchId = switchEntry.getSwitchId(); SwitchStatus switchStatus = switchEntry.getStatus(); switchById.put(switchId, new HistoryFacts(switchId, switchStatus)); } IslRepository islRepository = repositoryFactory.createIslRepository(); for (Isl islEntry : islRepository.findAll()) { HistoryFacts history = switchById.get(islEntry.getSrcSwitchId()); if (history == null) { log.error("Orphaned ISL relation - {}-{} (read race condition?)", islEntry.getSrcSwitchId(), islEntry.getSrcPort()); continue; } islRepository.detach(islEntry); history.addLink(islEntry); } return switchById.values(); } }
36.902439
108
0.705882
24eeed19c076ce0338a806d729d72523e6237dc2
274
package com.dumas.pedestal.framework.springboot.constant; /** * Web模块常量 * * @author az.ye * @version V1.0 * @since 2021-06-03 14:39 */ public class WebConstant { /** * 用户基本信息请求头 */ public static final String REQ_HEADER_USER_INFO = "x-user-info"; }
16.117647
68
0.645985
ffd0c61ea7f600a796d27b5e085a4887d744e037
4,180
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package eapli.base.smm.application; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; /** * -------------------------------------------------------------------------------------------------------------------------- * offset 0 - 1 byte : VERSION * offset 1 - 1 byte : MESSAGE CODE (0/3) * offset 2 - 2 byte : MACHINE ID (0) * offset 4 - 2 byte : Number of bytes stored in the following RAW DATA field. * Number = (first byte + 256 x second byte) * The total length of the message is (6 + DATA LENGTH) bytes. * DATA LENGTH may be zero, meaning there’s no RAW DATA, and thus the total message length is 6 bytes. * offset 6 - DATA LENGTH bytes: Data to be interpreted by end applications, usually a text content. * -------------------------------------------------------------------------------------------------------------------------- * * @author Tiago Ribeiro */ public class MonitorizeMachineByUdp { private static final byte HELLO = 0; private static final byte RESET = 3; private static final byte VERSION = 1; public void run() throws Exception { this.start(); } public void start() throws Exception{ final long time = (1000 * 30); //30 seconds Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { byte[] inData = new byte[3]; byte[] outData = new byte[6]; byte[] ipAddress = new byte[] {10, 8, 0, 82}; outData[0] = VERSION; outData[1] = HELLO; outData[2] = 0; outData[3] = 0; outData[4] = 0; outData[5] = 0; InetAddress address = null; try { address = InetAddress.getByAddress(ipAddress); } catch (UnknownHostException ex) { Logger.getLogger(MonitorizeMachineByUdp.class.getName()).log(Level.SEVERE, null, ex); } DatagramSocket socket = null; try { socket = new DatagramSocket(); } catch (SocketException ex) { Logger.getLogger(MonitorizeMachineByUdp.class.getName()).log(Level.SEVERE, null, ex); } DatagramPacket udpPacketOut = new DatagramPacket(outData, outData.length, address, 31206); try { socket.send(udpPacketOut); } catch (IOException ex) { Logger.getLogger(MonitorizeMachineByUdp.class.getName()).log(Level.SEVERE, null, ex); } // RECEIVE DatagramPacket udpPacketIn = new DatagramPacket(inData, inData.length); udpPacketIn.setData(inData); udpPacketIn.setLength(inData.length); try { socket.setSoTimeout(20000); socket.receive(udpPacketIn); String read = new String(udpPacketIn.getData()); System.out.println("\nCode Read:" + read); System.out.println("Server IP Read: "+ udpPacketIn.getAddress()); System.out.println("Port Used: " + udpPacketIn.getPort()+"\n"); } catch (IOException ex) { Logger.getLogger(MonitorizeMachineByUdp.class.getName()).log(Level.SEVERE, null, ex); } //System.out.println(Arrays.toString(udpPacketIn.getData())); socket.close(); } }; timer.scheduleAtFixedRate(task, 0, time); } }
37.657658
125
0.543301
f7a98ff06febbf2136fd141f915ef964dab66e8e
1,719
package com.gbourquet.yaph.serveur.password.handler; import java.util.HashMap; import java.util.List; import net.customware.gwt.dispatch.server.ExecutionContext; import net.customware.gwt.dispatch.shared.ActionException; import com.gbourquet.yaph.serveur.handler.AbstractHandler; import com.gbourquet.yaph.serveur.metier.generated.Account; import com.gbourquet.yaph.serveur.metier.generated.PasswordCard; import com.gbourquet.yaph.serveur.metier.generated.PasswordField; import com.gbourquet.yaph.serveur.password.in.AllPasswordAction; import com.gbourquet.yaph.serveur.password.out.AllPasswordResult; import com.gbourquet.yaph.serveur.service.PasswordService; import com.gbourquet.yaph.serveur.service.exception.ServiceException; import com.gbourquet.yaph.serveur.util.BeanFactory; public class AllPasswordFromAccountHandler extends AbstractHandler<AllPasswordAction, AllPasswordResult> { public AllPasswordResult exec(AllPasswordAction in, ExecutionContext context) throws ActionException { final Account account = in.getAccount(); HashMap<PasswordCard, List<PasswordField>> outData = null; PasswordService service = (PasswordService) BeanFactory.getInstance().getService("passwordService"); try { outData = service.getPasswords(account); } catch (ServiceException e) { throw new ActionException(e.getMessage()); } return new AllPasswordResult(outData); } @Override public void rollback(final AllPasswordAction action, final AllPasswordResult result, final ExecutionContext context) throws ActionException { // Nothing to do here } @Override public Class<AllPasswordAction> getActionType() { return AllPasswordAction.class; } }
37.369565
143
0.79523
0901aa2e0da4122db25ae0b1964476e2aa2424ea
1,692
/** * Copyright 2016 William Van Woensel 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. * * * @author wvw * */ package wvw.mobibench.service.select.domain.forward; import java.util.List; import wvw.mobibench.service.convert.ConvertConfig; import wvw.mobibench.service.convert.ConvertException; import wvw.mobibench.service.convert.spin.rulestr.SPIN2RuleStr; import wvw.mobibench.service.select.domain.rule.IRule; import wvw.mobibench.service.select.domain.rule.IRuleParser; import wvw.mobibench.service.select.domain.rule.IRuleset; import wvw.mobibench.service.select.domain.rule.RuleParseException; import wvw.mobibench.service.select.domain.rule.str.RulesetList; import wvw.utils.log.Logger; public class ForwardNaiveRuleParser implements IRuleParser { private Logger logger = Logger.getLogger(); @SuppressWarnings({ "unchecked", "rawtypes" }) public IRuleset parse(String rulesStr) throws RuleParseException { try { SPIN2RuleStr conv = new SPIN2RuleStr(); List<IRule> result = (List) conv.convertRules(rulesStr, new ConvertConfig(false)); return new RulesetList(result); } catch (ConvertException e) { logger.log(this, e); } return null; } }
31.333333
85
0.767139
ffa2a1cbe7cfd8be034061735b4b5b7b034d0f89
2,386
package com.github.vanroy.springboot.autoconfigure.data.jest; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Jest Elasticsearch properties. * @author Julien Roy */ @ConfigurationProperties(prefix = "spring.data.jest") public class ElasticsearchJestProperties { private String uri; private String username; private String password; private String awsRegion; private int maxTotalConnection = 50; private int defaultMaxTotalConnectionPerRoute = 50; private int readTimeout = 5000; private Boolean multiThreaded = true; /** * Proxy settings. */ private final Proxy proxy = new Proxy(); public Proxy getProxy() { return this.proxy; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getMaxTotalConnection() { return maxTotalConnection; } public void setMaxTotalConnection(int maxTotalConnection) { this.maxTotalConnection = maxTotalConnection; } public int getDefaultMaxTotalConnectionPerRoute() { return defaultMaxTotalConnectionPerRoute; } public void setDefaultMaxTotalConnectionPerRoute(int defaultMaxTotalConnectionPerRoute) { this.defaultMaxTotalConnectionPerRoute = defaultMaxTotalConnectionPerRoute; } public int getReadTimeout() { return readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public Boolean getMultiThreaded() { return multiThreaded; } public void setMultiThreaded(Boolean multiThreaded) { this.multiThreaded = multiThreaded; } public String getAwsRegion() { return awsRegion; } public void setAwsRegion(String awsRegion) { this.awsRegion = awsRegion; } public static class Proxy { /** * Proxy host the HTTP client should use. */ private String host; /** * Proxy port the HTTP client should use. */ private Integer port; public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return this.port; } public void setPort(Integer port) { this.port = port; } } }
18.936508
90
0.733864
81b15d89d1fe9229d95890b3d32a687bd87058a3
821
package study.huhao.demo.application.usecases; import org.springframework.stereotype.Component; import study.huhao.demo.application.concepts.UseCase; import study.huhao.demo.domain.contexts.blogcontext.blog.Blog; import study.huhao.demo.domain.contexts.blogcontext.blog.BlogRepository; import study.huhao.demo.domain.contexts.blogcontext.blog.BlogService; import java.util.UUID; @Component public class QueryPublishedBlogUseCase implements UseCase { private final BlogService blogService; public QueryPublishedBlogUseCase(BlogRepository blogRepository) { // 依赖注入是一种应用需要和技术实现细节,所以在 UseCase 里使用依赖注入框架,通过实例化 DomainService 并注入相关依赖的方式实现了 Domain 与技术框架的解耦。 this.blogService = new BlogService(blogRepository); } public Blog get(UUID id) { return blogService.getPublished(id); } }
34.208333
102
0.795371
8bf7ade4a536a29fac71b7b2d295df708d6873b2
2,410
/* ** Author(s): Miguel Calejo ** Contact: interprolog@declarativa.com, http://www.declarativa.com ** Copyright (C) Declarativa, Portugal, 2000-2005 ** Use and distribution, without any warranties, under the terms of the ** GNU Library General Public License, readable in http://www.fsf.org/copyleft/lgpl.html */ package com.declarativa.interprolog; import junit.framework.*; import java.util.*; import com.declarativa.interprolog.util.*; public class XSBSubprocessEngineTest extends SubprocessEngineTest { public XSBSubprocessEngineTest(String name){ super(name); } protected void setUp() throws java.lang.Exception{ super.setUp(); engine.deterministicGoal("import append/3,length/2 from basics"); engine.waitUntilAvailable(); } // JUnit reloads all classes, clobbering variables, // so the path should be obtained elsewhere: protected AbstractPrologEngine buildNewEngine(){ return new XSBSubprocessEngine(/*true*/); } public void testPrologInstallDir(){ PrologImplementationPeer peer = engine.getImplementationPeer(); // The following is too complicated for the assertion presently tested, but ready for deeper stuff: engine.teachOneObject(new ConfigurationItem()); String g = "findall(Obj, ( F=install_dir, xsb_configuration(F,V), "; //String g = "findall(Obj, ( "+peer.getFVInstallDirGoal()+", "; g += "ipObjectSpec('com.declarativa.interprolog.XSBSubprocessEngineTest$ConfigurationItem',[feature=string(F),value=string(V)],Obj)"; g += "),L), ipObjectSpec('ArrayOfObject',L,Array)"; Object[] items = (Object[])engine.deterministicGoal(g,"[Array]")[0]; ConfigurationItem item = (ConfigurationItem) items[0]; java.io.File f = new java.io.File(item.value); String path = engine.getPrologBaseDirectory(); assertTrue(path.indexOf(f.getName()/*item.value*/)!=-1); } public static class ConfigurationItem implements java.io.Serializable{ String feature,value; public String toString(){ return "FEATURE "+feature+" HAS VALUE "+value; } } // XSB 2.7.1 has float problems on Linux: public void testNumbers2(){ if (AbstractPrologEngine.isWindowsOS()||AbstractPrologEngine.isMacOS()) super.testNumbers2(); else System.err.println("Skipping testNumbers2"); } public void testNumbers(){ if (AbstractPrologEngine.isWindowsOS()||AbstractPrologEngine.isMacOS()) super.testNumbers(); else System.err.println("Skipping testNumbers2"); } }
40.847458
135
0.744398
4d2c919a99970a4104efb05d02f2ba9ce34c15a5
1,006
package com.github.oliverschen.olirpc.cluster; import com.github.oliverschen.olirpc.exception.OliException; import com.github.oliverschen.olirpc.protocol.OliUrl; import org.springframework.util.StringUtils; import static com.github.oliverschen.olirpc.constant.Constants.*; /** * @author ck */ public class OliUrlCluster extends AbstractCluster { /** * 组装请求参数 */ @Override <T> OliUrl<T> doObtainOliUrl(String url, Class<T> serviceClass, String protocol) { OliUrl<T> oliUrl = new OliUrl<>(); oliUrl.setSrcUrl(url); if (StringUtils.hasLength(url)) { String[] address = url.split(URL_SPLIT)[1].split(URL_COLON); if (address.length != SPLIT_SIZE) { throw new OliException("配置有误"); } oliUrl.setHost(address[0]); oliUrl.setPort(Integer.parseInt(address[1])); } oliUrl.setProtocol(protocol); oliUrl.setServiceClass(serviceClass); return oliUrl; } }
28.742857
86
0.646123
56b0013f50d15fa1cec1f1474e07963fd5aecd9f
253
package com.open.lcp.core.framework.loader; import com.open.lcp.core.framework.api.service.dao.entity.ApiMaxThreadsEntity; public interface ApiMaxThreadsTimerLoader extends TimerLoader { public ApiMaxThreadsEntity getLcpApiMaxThreads(String api); }
28.111111
78
0.841897
519774ce6d24e5ba0eed07a9d61defa9530fa8cf
890
package uk.gov.ida.matchingserviceadapter.mappers; import stubidp.saml.domain.assertions.AuthnContext; import uk.gov.ida.matchingserviceadapter.rest.matchingservice.LevelOfAssuranceDto; public class AuthnContextToLevelOfAssuranceDtoMapper { private AuthnContextToLevelOfAssuranceDtoMapper() {} public static LevelOfAssuranceDto map(AuthnContext authnContext) { switch (authnContext){ case LEVEL_1: return LevelOfAssuranceDto.LEVEL_1; case LEVEL_2: return LevelOfAssuranceDto.LEVEL_2; case LEVEL_3: return LevelOfAssuranceDto.LEVEL_3; case LEVEL_4: return LevelOfAssuranceDto.LEVEL_4; default: throw new IllegalArgumentException("Level of Assurance: '" + authnContext + "' is not a legal value in this context"); } } }
35.6
134
0.677528
54d6148b7c033d63c762981a38bbc97a5b5241e8
3,671
package org.cipres.treebase.domain.matrix; import javax.persistence.AttributeOverride; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.cipres.treebase.domain.AbstractPersistedObject; import org.cipres.treebase.domain.TBPersistable; /** * MatrixDataType.java * * Created on Mar 21, 2006 * * @author Jin Ruan * */ @Entity @Table(name = "MATRIXDATATYPE") @AttributeOverride(name = "id", column = @Column(name = "MATRIXDATATYPE_ID")) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "matrixCache") public class MatrixDataType extends AbstractPersistedObject { private static final long serialVersionUID = 1208732648506944463L; // TODO: add a subclass for build-in immutable data types: public static final String MATRIX_DATATYPE_STANDARD = "Standard"; public static final String MATRIX_DATATYPE_DNA = "DNA"; public static final String MATRIX_DATATYPE_RNA = "RNA"; public static final String MATRIX_DATATYPE_NUCLEOTIDE = "Nucleotide"; public static final String MATRIX_DATATYPE_PROTEIN = "Protein"; public static final String MATRIX_DATATYPE_CONTINUOUS = "Continuous"; public static final String MATRIX_DATATYPE_DISTANCE = "Distance"; public static final String MATRIX_DATATYPE_MIXED = "Mixed"; private String mDescription; private PhyloChar mDefaultCharacter; /** * Constructor. */ public MatrixDataType() { super(); } /** * Return the Description field. * * @return String mDescription */ @Override @Column(name = "Description", length = TBPersistable.COLUMN_LENGTH_STRING) public String getDescription() { return mDescription; } /** * Set the Description field. */ public void setDescription(String pNewDescription) { mDescription = pNewDescription; } /** * Return the DefaultCharacter field. * * @return PhyloChar mDefaultCharacter */ @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinColumn(name = "PHYLOCHAR_ID", nullable = true) public PhyloChar getDefaultCharacter() { return mDefaultCharacter; } /** * Set the DefaultCharacter field. */ public void setDefaultCharacter(PhyloChar pNewDefaultCharacter) { mDefaultCharacter = pNewDefaultCharacter; } /** * Returns true if the data type is dna. * * @return */ @Transient public boolean isDNA() { return MATRIX_DATATYPE_DNA.equals(getDescription()); } /** * Returns true if the data type is rna. * * @return */ @Transient public boolean isRNA() { return MATRIX_DATATYPE_RNA.equals(getDescription()); } /** * Returns true if the data type is protein. * * @return */ @Transient public boolean isProtein() { return MATRIX_DATATYPE_PROTEIN.equals(getDescription()); } /** * Returns true if the data type is Standard. * * @return */ @Transient public boolean isStandard() { return MATRIX_DATATYPE_STANDARD.equals(getDescription()); } /** * Returns true if the data type is sequence. * * @return */ @Transient public boolean isSequence() { return (MATRIX_DATATYPE_DNA.equals(getDescription()) || MATRIX_DATATYPE_NUCLEOTIDE.equals(getDescription()) || MATRIX_DATATYPE_PROTEIN.equals(getDescription()) || MATRIX_DATATYPE_RNA .equals(getDescription())); } }
25.493056
86
0.715336
941983a1e2b1fb5785c44efd1f199a77fbef328a
626
package com.jinhaoxun.dubbo.module.user.vo.response; import com.jinhaoxun.dubbo.vo.action.ActionPageableResponse; import com.jinhaoxun.dubbo.pojo.user.User; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import java.util.List; /** * @version 1.0 * @author jinhaoxun * @date 2018-05-09 * @description 获取用户列表响应实体类 */ @Setter @Getter @ApiModel("获取用户列表响应实体类") public class GetUserListActionRes extends ActionPageableResponse { @ApiModelProperty(required = true, value = "用户列表", example = "用户列表") private List<User> userList; }
23.185185
72
0.769968
c7031dc15b956c923e274fc8783801bbc1326cb0
426
package io.github.scave.lsp4a.model.completion; /** * The class define the formats of text insertion * @author Scave */ public class InsertTextFormat { /** * The plain text will be inserted */ public static final int PLAINTEXT = 1; /** * The snippet will be inserted * In fact, the snippet is a code snippet that specifies a code template */ public static final int SNIPPET = 2; }
23.666667
76
0.659624
13406c58716e716c64060f0510beb89ad3abd77a
501
package game.block; import util.BmpRes; import graphics.Canvas; public class AirBlock extends AirType{ private static final long serialVersionUID=1844677L; static BmpRes bmp=new BmpRes("Block/AirBlock"); public BmpRes getBmp(){return bmp;} public void draw(Canvas cv){} public void onDestroy(int x,int y){} public void des(int x,int y,int v){} public boolean onCheck(int x,int y){return false;} public boolean onUpdate(int x,int y){return false;} public boolean fallable(){return false;} };
29.470588
52
0.758483
de9552761e9bb796cd227a5df4dfa2f5f233da71
2,136
package com.github.zella.rxprocess2.common; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Function; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.concurrent.Callable; import static com.github.zella.rxprocess2.RxProcessConfig.DEFAULT_READ_BUFFER; public class RxUtils { public static Single<byte[]> collect(Observable<byte[]> source) { return source.collect(BosCreatorHolder.INSTANCE, BosCollectorHolder.INSTANCE).map(BosToArrayHolder.INSTANCE); } private static final class BosCreatorHolder { static final Callable<ByteArrayOutputStream> INSTANCE = new Callable<ByteArrayOutputStream>() { @Override public ByteArrayOutputStream call() { return new ByteArrayOutputStream(); } }; } private static final class BosCollectorHolder { static final BiConsumer<ByteArrayOutputStream, byte[]> INSTANCE = new BiConsumer<ByteArrayOutputStream, byte[]>() { @Override public void accept(ByteArrayOutputStream bos, byte[] bytes) throws IOException { bos.write(bytes); } }; } private static final class BosToArrayHolder { static final Function<ByteArrayOutputStream, byte[]> INSTANCE = new Function<ByteArrayOutputStream, byte[]>() { @Override public byte[] apply(ByteArrayOutputStream bos) { return bos.toByteArray(); } }; } public static Observable<byte[]> bytes(final InputStream is) { return Observable.generate(emitter -> { byte[] buffer = new byte[DEFAULT_READ_BUFFER]; int count = is.read(buffer); if (count == -1) { emitter.onComplete(); } else if (count < DEFAULT_READ_BUFFER) { emitter.onNext(Arrays.copyOf(buffer, count)); } else { emitter.onNext(buffer); } }); } }
32.861538
123
0.64279
b52186b3388495c243e43a0f3211ad4147525d87
1,641
package com.islarf6546.gmail.myapplication; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; /** * Created by YamiVegeta on 15/11/2015. * References: * http://www.newthinktank.com/2014/06/make-android-apps-4/ * http://stackoverflow.com/questions/10905312/receive-result-from-dialogfragment */ public class DialogMaker extends DialogFragment { static boolean result = false; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle mArgs = getArguments(); savedInstanceState = this.getArguments(); final AlertDialog.Builder theDialog = new AlertDialog.Builder(getActivity()); theDialog.setTitle(mArgs.getString("title")); theDialog.setMessage(mArgs.getString("message")); theDialog.setPositiveButton(mArgs.getString("posButton"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result = true; } }); theDialog.setNegativeButton(mArgs.getString("negButton"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result = false; } }); return theDialog.create(); } public static boolean getResult() { if(result) { result = false; return true; } return result; } }
26.047619
105
0.658135
7f8521e2ba524001f6ae28811d1e1834dfe86d33
1,763
package com.deadsimplegui; import com.deadsimplegui.util.Gui; import com.deadsimplegui.util.resource.AnnotationScanner; import com.deadsimplegui.util.resource.ExternalResourceLogic; import com.deadsimplegui.util.resource.InternalResourceLogic; import com.deadsimplegui.util.resource.ResourceLogic; import com.deadsimplegui.util.resource.UrlBinding; import java.net.URI; import java.util.Arrays; public class GuiBuilder { private static final String DEFAULT_HOME_PAGE = "http://localhost/index.html"; private String title; private URI homePage; private ResourceLogic externalResourceLogic = new ExternalResourceLogic(); private ResourceLogic internalResourceLogic = new InternalResourceLogic(); private GuiBuilder() { try { this.homePage = new URI(DEFAULT_HOME_PAGE); } catch(Exception e) { //will never happen. } } public static GuiBuilder getInstance() { return new GuiBuilder(); } public GuiBuilder registerPackages(String... packageNames) { Arrays .stream(packageNames) .forEach(packageName -> AnnotationScanner.registerPackage(packageName, UrlBinding.class)); return this; } public GuiBuilder setTitle(String title) { this.title = title; return this; } public GuiBuilder setHomePage(URI homePage) { this.homePage = homePage; return this; } public GuiBuilder setExternalResourceLogic(ResourceLogic resourceLogic) { this.externalResourceLogic = resourceLogic; return this; } public GuiBuilder setInternalResourceLogic(ResourceLogic resourceLogic) { this.internalResourceLogic = resourceLogic; return this; } public Gui build() { return Gui.getInstance(title, homePage, externalResourceLogic, internalResourceLogic); } }
27.984127
98
0.754963